Go - 范围
range 关键字在 for 循环中用于迭代数组、切片、通道或 map 的项目。使用 array 和 slices,它将项目的索引作为整数返回。使用 maps 时,它会返回下一个键值对的键。Range 返回一个值或 2 个值。如果范围表达式的左侧只使用一个值,则它是下表中的第 1 个值。
范围表达式 | 第 1 个值 | 第 2 个值(可选) |
---|---|---|
Array or slice a [n]E | index i int | a[i] E |
String s string type | index i int | rune int |
map m map[K]V | key k K | value m[k] V |
channel c chan E | element e E | none |
例
以下段落显示了如何使用 range -
package main
import "fmt"
func main() {
/* 创建切片 */
numbers := []int{0,1,2,3,4,5,6,7,8}
/* 打印数字 */
for i:= range numbers {
fmt.Println("Slice item",i,"is",numbers[i])
}
/* 创建地图 */
countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo"}
/* 使用按键打印地图 */
for country := range countryCapitalMap {
fmt.Println("Capital of",country,"is",countryCapitalMap[country])
}
/* 使用键值打印地图 */
for country,capital := range countryCapitalMap {
fmt.Println("Capital of",country,"is",capital)
}
}
编译并执行上述代码时,它会产生以下结果——
Slice item 0 is 0
Slice item 1 is 1
Slice item 2 is 2
Slice item 3 is 3
Slice item 4 is 4
Slice item 5 is 5
Slice item 6 is 6
Slice item 7 is 7
Slice item 8 is 8
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Slice item 1 is 1
Slice item 2 is 2
Slice item 3 is 3
Slice item 4 is 4
Slice item 5 is 5
Slice item 6 is 6
Slice item 7 is 7
Slice item 8 is 8
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo