// init s :=[] int {1,2,3 } s :=make([]int,len,cap)
// 截取,和py一致 numbers[1:4]
// append() and copy() var numbers []int numbers = append(numbers, 0) copy(numbers1,numbers)
指针
1 2 3 4 5 6 7 8 9 10 11
i := 8 f := 3.00 var ip *int var fp *float64 // 取地址 ip = &i fp = &f fmt.Printf("%d\n", *ip) fmt.Printf("%f\n", *fp) fmt.Printf("%x\n", ip) fmt.Printf("%x\n", fp)
map集合
1 2 3 4 5 6 7 8
m := map[string]int{ "ゼロ": 0, } m["いち"]=1 m["に"]=2 m["さん"]=3
delete(m,"ゼロ")
range遍历
1 2 3 4 5 6 7 8
var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}
funcmain() { for i, v := range pow { // do somethings // i,v是索引和值 } }
funcsum(s string, nList ...int)int { // 类似es6的拓展运算符,以切片形式接受变长参数 fmt.Println("received vars:", s, nList) var res int = 0 for _, v := range nList { res += v } return res }
funcmain() { arr := []int{1, 2, 3, 4} // 类似es6的拓展运算符 res := sum("hello", arr...) fmt.Println("result of sun(): ", res) fmt.Println()
res = sum("hello", arr[0], arr[1]) fmt.Println("result of sun(): ", res) }
类型转换
1 2
a := int16 b := float64 = float64(a)
字符串类型转换
1 2 3 4 5 6 7 8
// str -> int var str string = "10" var num int num, _ = strconv.Atoi(str)
funcfibonacci(n int, c chanint) { x, y := 0, 1 for i := 0; i < n; i++ { c <- x fmt.Printf("trans %d\n", x) time.Sleep(100 * time.Millisecond) x, y = y, y+1 } close(c) }
funcmain() { c := make(chanint, 5) go fibonacci(2*cap(c), c) time.Sleep(5 * time.Second) for i := range c { // 这里会阻塞fibonacci线程 time.Sleep(1 * time.Second) fmt.Printf("recive %d\n", i) } }
trans 0 trans 1 trans 2 trans 3 trans 4 trans 5 recive 0 trans 6 recive 1 trans 7 recive 2 trans 8 recive 3 trans 9 recive 4 recive 5 recive 6 recive 7 recive 8 recive 9