Go语言的range
关键字用于在for
语句中遍历数组Array, Slice, Map和Channel中的元素.
遍历Array
1 2 3 4 5 6 7 8 9 10 11 12 13
| package main
import "fmt"
func main() { arr := [4]string {"a", "b", "c", "d"} for i, v := range arr { fmt.Println(i, v) }
}
|
执行结果:
遍历Slice
1 2 3 4 5 6 7 8 9 10 11 12 13
| package main
import "fmt"
func main() { arr := []string {"a", "b", "c", "d"} for i, v := range arr { fmt.Println(i, v) }
}
|
执行结果:
遍历Map
1 2 3 4 5 6 7 8 9 10 11 12 13
| package main
import "fmt"
func main() { m := map[string]string{"k1": "polarsnow", "k2": "larry", "k3": "lyu"} for k, v := range m { fmt.Println(k, v) }
}
|
执行结果:
1 2 3
| k1 polarsnow k2 larry k3 lyu
|