=Start=
缘由:
Go语言中的for…range语法对于刚接触的人来说稍微有那么点不适应,容易踩坑,所以在此记录一下,方便查阅。
参考解答:
如果在range表达式的左边只有一个变量,那对应的就是下表中的「1st value」列(If only one value is used on the left of a range expression, it is the 1st value in this table.):
Range expression | 1st value | 2nd value (optional) | notes |
---|---|---|---|
array or slice a [n]E ,*[n]E , or []E |
index i int |
a[i] E |
|
string s string type | index i int |
rune int |
range iterates over Unicode code points, not bytes |
map m map[K]V |
key k K |
valuem[k] V |
|
channel c chan E | elemente E |
none |
样例:
for k, v := range myMap { log.Printf("key=%v, value=%v", k, v) } for v := range myChannel { log.Printf("value=%v", v) } for i, v := range myArray { log.Printf("array value at [%d]=%v", i, v) } // `range` on strings iterates over Unicode code points. // The first value is the starting byte index of the `rune` and the second the `rune` itself. for i, c := range "go" { fmt.Println(i, c) } /* ==== */ var pow = []int{1, 2, 4, 8, 16, 32, 64, 128} for key, value := range pow { fmt.Printf("%d\t%d\n", key, value) } for key := range pow { fmt.Printf("%d\t", key) }
参考链接:
- https://gobyexample.com/range
- https://github.com/golang/go/wiki/Range
- https://tour.golang.org/moretypes/13
- http://www.cnblogs.com/howDo/archive/2013/06/01/GoLang-Control.html
=EOF=
《 “Golang中的for…range语法” 》 有 2 条评论
Go Range 循环内幕
https://lingchao.xin/post/go-range-loop-internals.html
https://garbagecollected.org/2017/02/22/go-range-loop-internals/
go语言坑之for range
https://studygolang.com/articles/9701
https://www.jianshu.com/p/04f117c22873