go语言范围(range) go语言中range关键字用于for循环中迭代数组(array)、切片(slice)、通道(channel)或集合(map)的元素, 在数据和切片中它返回元素的索引和索引对应的值,在集合中返回key-value对 eg:

package main

import "fmt"

func main() {
    nums := []int{1,2,3}
    sum := 0
    for _, num := range nums {
        sum += num
    }
    fmt.Println("sum:",sum)

    for i, num :=range nums {
        if num == 3 {
            fmt.Println("index:",i)
        }
    }
    //range也可以用在map的键值对上
    kvs := map[string]string{"a": "apple", "b": "banana"}
    for k, v := range kvs {
        fmt.Printf("%s -> %s\n", k, v)
    }
    for i, c := range "go" {
        fmt.Println(i, c)
    }
}
% go run 1.4、go语言语句.go
sum: 6
index: 2
a -> apple
b -> banana
0 103
1 111