上QQ阅读APP看书,第一时间看更新
range
The range keyword is used to iterate over a slice, map, or other data structure. The range keyword is used in combination with the for loop, to operate on an iterable data structure. The range keyword returns the key and value variables. Here are some basic examples of using the range keyword:
package main
import "fmt"
func main() {
intSlice := []int{2, 4, 6, 8}
for key, value := range intSlice {
fmt.Println(key, value)
}
myMap := map[string]string{
"d": "Donut",
"o": "Operator",
}
// Iterate over a map
for key, value := range myMap {
fmt.Println(key, value)
}
// Iterate but only utilize keys
for key := range myMap {
fmt.Println(key)
}
// Use underscore to ignore keys
for _, value := range myMap {
fmt.Println(value)
}
}