Golang中的for…range语法


=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)
}
参考链接:

=EOF=

,

《 “Golang中的for…range语法” 》 有 2 条评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注