Golang Range: The Complete Guide to Iteration
In Golang, the range keyword can be used to iterate over data structures such as arrays, slices, maps, and channels.具體使用方法如下:
- Iterating through arrays and slices:
arr := []int{1, 2, 3, 4, 5}
for idx, val := range arr {
fmt.Printf("Index: %d, Value: %d\n", idx, val)
}
- Iterative mapping:
m := map[string]int{"a": 1, "b": 2, "c": 3}
for key, val := range m {
fmt.Printf("Key: %s, Value: %d\n", key, val)
}
- Iterative channel.
ch := make(chan int)
go func() {
ch <- 1
ch <- 2
ch <- 3
close(ch)
}()
for val := range ch {
fmt.Println(val)
}
During the iteration process, the range keyword will return two values, which are the index (or key) and the corresponding value. You can choose to use a variable to receive one of the values, or use an underscore _ to discard the value that is not needed.