Go Range 关键字
Go - Range 表达式
Section titled “Go - Range 表达式”Go 语言中的 range 关键字提供了一种方便的方式,可以在 for 循环中迭代数组、切片、字符串、映射 (map) 和通道 (channel) 等各种数据结构中的元素。
迭代时,range 通常返回两个值:索引/键和元素/值。您可以选择接收这两个值、只接收第一个值,或者忽略这两个值。
| Range 表达式作用于 | 第一个值 | 第二个值 (可选) |
|---|---|---|
数组或切片 a | 索引 i (int) | 元素 a[i] (元素类型) |
字符串 s | 索引 i (int, 字节索引) | Rune r (int32, Unicode 码点) |
映射 (Map) m | 键 k (键类型) | 值 v (值类型) |
通道 (Channel) c | 元素 e (元素类型) | (没有第二个值) |
如果您只需要第一个值(例如,索引或键),可以省略第二个值:
for i := range numbers { // i 获取索引 // ...}for key := range countryCapitalMap { // key 获取 map 的键 // ...}如果您只需要第二个值(例如,元素本身),可以使用空白标识符 _ 来忽略第一个值:
sum := 0for _, num := range numbers { // 忽略索引,获取数值 sum += num}如果您不需要任何一个值(例如,只是为了计数迭代次数),可以忽略这两个值,尽管这种情况不太常见:
count := 0for range numbers { // 忽略索引和值 count++}下面是一个使用 range 迭代切片、映射和字符串的示例:
package main
import "fmt"
func main() { // --- 切片示例 --- numbers := []int{0, 1, 2, 3, 4, 5, 6, 7, 8}
fmt.Println("Iterating over slice (index and value):") for i, num := range numbers { fmt.Printf("Slice index %d has value %d\n", i, num) }
fmt.Println("\nIterating over slice (value only):") sum := 0 for _, num := range numbers { sum += num } fmt.Printf("Sum of numbers: %d\n", sum)
// --- 映射示例 --- countryCapitalMap := map[string]string{ "France": "Paris", "Italy": "Rome", "Japan": "Tokyo", }
fmt.Println("\nIterating over map (key and value):") for country, capital := range countryCapitalMap { fmt.Printf("Capital of %s is %s\n", country, capital) }
fmt.Println("\nIterating over map (key only):") for country := range countryCapitalMap { fmt.Printf("Country: %s, Capital: %s\n", country, countryCapitalMap[country]) }
// --- 字符串示例 (迭代 runes) --- fmt.Println("\nIterating over string (runes):") for index, runeValue := range "Go语言" { fmt.Printf("Byte index: %d, Rune: %c (Unicode: %U)\n", index, runeValue, runeValue) }}编译并执行上述代码,将产生以下结果(map 的迭代顺序可能有所不同):
Iterating over slice (index and value):Slice index 0 has value 0Slice index 1 has value 1Slice index 2 has value 2Slice index 3 has value 3Slice index 4 has value 4Slice index 5 has value 5Slice index 6 has value 6Slice index 7 has value 7Slice index 8 has value 8
Iterating over slice (value only):Sum of numbers: 36
Iterating over map (key and value):Capital of France is ParisCapital of Italy is RomeCapital of Japan is Tokyo
Iterating over map (key only):Country: France, Capital: ParisCountry: Italy, Capital: RomeCountry: Japan, Capital: Tokyo
Iterating over string (runes):Byte index: 0, Rune: G (Unicode: U+0047)Byte index: 1, Rune: o (Unicode: U+006F)Byte index: 2, Rune: 语 (Unicode: U+8BED)Byte index: 5, Rune: 言 (Unicode: U+8A00)重要说明:当通过 range 迭代切片或数组时,range 操作的是值的副本。如果您需要修改原始元素,请使用索引来访问它们:numbers[i] = newValue。
对于字符串,range 迭代的是 Unicode 码点 (runes),而不是字节。返回的第一个值是 rune 的起始字节索引。