Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Go Language Range


May 11, 2021 Go


Table of contents


Go Language Range

The range keyword in the Go language is used for elements of iterative arrays, slices, channels, or collections (map) in the for loop. In arrays and slices it returns the index value of the element and the key value of the key-value pair in the collection.

For a map, it returns the key for the next key value pair. R ange returns one or two values. I f only one value is used to the left of the Range expression, the value is the first value in the table below.

Range expression The first value Second value (optional)
Array or slice a sn.e Index i int a[i] E
String s string type Index i int rune int
map m map[K]V Key k K The value is m.k.V
channel c chan E Element e E none

Instance

package main
import "fmt"
func main() {
    //这是我们使用range去求一个slice的和。使用数组跟这个很类似
    nums := []int{2, 3, 4}
    sum := 0
    for _, num := range nums {
        sum += num
    }
    fmt.Println("sum:", sum)
    //在数组上使用range将传入index和值两个变量。上面那个例子我们不需要使用该元素的序号,所以我们使用空白符"_"省略了。有时侯我们确实需要知道它的索引。
    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)
    }
    //range也可以用来枚举Unicode字符串。第一个参数是字符的索引,第二个是字符(Unicode的值)本身。
    for i, c := range "go" {
        fmt.Println(i, c)
    }
}

The above instance runs the output as:

sum: 9
index: 1
a -> apple
b -> banana
0 103
1 111