我的练习
把一个数从1加到100package mainimport (
"fmt"
)
func main() {
a := 0
for i := 0; i <= 100; i++ {
a = a + i
}
fmt.Printf("1+1+2...+100=%d", a)
}
从1-100里选一个数,如果不是你心里想的数就输入n否则就输入y退出循环// searchNumber project main.go
package main
import (
"fmt"
"sort"
)
func main() {
fmt.Println("pick number from 0 to 100")
fmt.Printf("you number is %d\n", sort.Search(100, func(i int) bool {
fmt.Printf("is you number <=%d?", i)
var s string
fmt.Scanf("%s\n", &s)
return s != "" && s == 'y'
}))
}
注意:两个文件不能放在一个文件目录里 用迭代给数组赋值跟遍历package main
import (
"fmt"
)
func main() {
a := make([]int, 6, 6)
for i := 0; i < 6; i++ {
a = i
}
for _, i := range a {
fmt.Printf("%d\n", i)
}
} {:5_108:}{:5_106:} 打印时长package main
import (
"fmt"
"time"
)
func main() {
t1 := time.Now()
for j := 0; j < 7; j++ {
t := time.Weekday(j)
fmt.Println(t)
}
time.Sleep(time.Second)
t2 := time.Now()
d := t2.Sub(t1)
fmt.Println(d)
}
调用结构体的方法package main
import (
"fmt"
"math"
)
type Vertex struct{ X, Y float64 }
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)//开方
}
func main() {
v := &Vertex{3, 4}
fmt.Println(v.Abs())
}
做一个int型的方法打印出100个数package main
import (
"fmt"
)
type A int
func (self *A) Increase() {
for a := 0; a < 100; a++ {
fmt.Println(a)
}
}
func main() {
var a A
a.Increase()
}
利用接口实现反射机制package main
import (
"fmt"
"reflect"
)
type Apple struct {
Id int
Color string
}
func Set(o interface{}) {
v := reflect.ValueOf(o)
if v.Kind() == reflect.Ptr && !v.Elem().CanSet() {
fmt.Println("erro")
return
} else {
v = v.Elem()
}
if f := v.FieldByName("Color"); f.Kind() == reflect.String {
f.SetString("green") //把值修改成绿色
}
}
func main() {
u := Apple{1, "red"}
Set(&u)
fmt.Println(u)
}
结构体的嵌套package main
import (
"fmt"
)
type Rectangle struct {
Text
Widthint
Height int
}
type Text struct {
FontColor string
}
func (rect Rectangle) PrintAttr() {
fmt.Println(rect)
}
func main() {
rectangle := Rectangle{Text{"black"}, 70, 80}
rectangle.PrintAttr()
rectangle.Text.FontColor = "red" //把字体颜色修改为红色
rectangle.PrintAttr()
}
通道传值package main
import (
"fmt"
"time"
)
func main() {
c := make(chan bool)
go Go(c)
b := <-c //等待通道数据传过来才继续往下执行
fmt.Println(b)
}
func Go(c chan bool) {
fmt.Println("go go go")
time.Sleep(3 * time.Second)
c <- true
}
简单计时器功能import (
"fmt"
"time"
)
func main() {
c := make(chan bool)
for i := 0; i < 60; i++ {
fmt.Println(i)
go TimeOut(c)
<-c
}
fmt.Println("哎!时间又过去了一分钟")
}
func TimeOut(c chan bool) {
time.Sleep(time.Second)
c <- true
}
写文件package main
import (
"fmt"
"os"
)
func main() {
userFile := "test.txt"
fout, err := os.Create(userFile)
defer fout.Close()//强制关闭资源
if err != nil {
fmt.Println(userFile, err)
return
}
for i := 0; i < 10; i++ {
fout.WriteString("Just a test!\r\n")
fout.Write([]byte("Just a test!\r\n"))
}
}
读文件package main
import (
"fmt"
"os"
)
func main() {
userFile := "test.txt"
fin, err := os.Open(userFile)
defer fin.Close()
if err != nil {
fmt.Println(userFile, err)
return
}
buf := make([]byte, 1024)
for {
n, _ := fin.Read(buf)
if 0 == n {
break
}
os.Stdout.Write(buf[:n])
}
}
同步锁package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
type LockMap struct {
sync.Mutex
m mapint
}
var lockMap = make([]LockMap, 10)
func init() {
for i := range lockMap {
lockMap.m = make(mapint)
}
}
func counter(s string) {
i := int(s - '0')
time.Sleep(time.Duration(i) * time.Millisecond)
lockMap.Lock()
defer lockMap.Unlock()
lockMap.m++
}
func main() {
for i := 0; i < 20; i++ {
r := fmt.Sprintf("%d", rand.Uint32())
go counter(r)
}
time.Sleep(time.Second)
for i := range lockMap {
for k, v := range lockMap.m {
fmt.Printf("[%d]%s = %d\n", i, k, v)
}
}
}
select语句用法package main
import (
"fmt"
"strconv"
)
func main() {
c := make(chan int)
go Run(c)
select {
case b := <-c:
a := strconv.Itoa(b)
fmt.Println("send number is " + a)
}
}
func Run(c chan int) {
select { //随机传一个数
case c <- 1:
case c <- 2:
}
} 输出XML格式package main
import (
"encoding/xml"
"fmt"
"os"
)
type Address struct {
City, State string
}
type Person struct {
XMLName xml.Name `xml:"person"`
Id int `xml:"id,attr"`
FirstName string `xml:"name>first"`
LastNamestring `xml:"name>last"`
Age int `xml:"age"`
Height float32`xml:"height,omitempty"`
Married bool
Address
Comment string `xml:",comment"`
}
func main() {
v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42}
v.Comment = " Need more details. "
v.Address = Address{"Hanga Roa", "Easter Island"}
output, err := xml.MarshalIndent(v, "", " ")
if err != nil {
fmt.Printf("error: %v\n", err)
}
os.Stdout.Write(output)
}
变换成json格式再转换回字典package main
import (
"encoding/json"
"fmt"
)
func main() {
//json encode
j1 := make(mapinterface{})
j1["name"] = "脚本之家"
j1["url"] = "http://www.jb51.net/"
js1, err := json.Marshal(j1)
if err != nil {
panic(err)
}
fmt.Println(string(js1))
//json decode
j2 := make(mapinterface{})
err = json.Unmarshal(js1, &j2)
if err != nil {
panic(err)
}
fmt.Printf("%#v\n", j2)
}
页:
[1]