Range {.en}
Range 遍历 {.zh}
::: {.en}
range iterates over elements in a variety of data
structures. Let’s see how to use range
with some
of the data structures we’ve already learned.
:::
::: {.zh}
range 遍历各种数据结构中的元素。让我们看看如何将 range
用在我们已经学过的一些数据结构。
:::
package main
import "fmt"
func main() {
::: {.en}
Here we use range
to sum the numbers in a slice.
Arrays work like this too.
:::
::: {.zh}
在这里,我们使用 range
来对 slice 中的数字求和。对数组也可以采用这种方法。
:::
nums := []int{2, 3, 4}
sum := 0
for _, num := range nums {
sum += num
}
fmt.Println("sum:", sum)
::: {.en}
range
on arrays and slices provides both the
index and value for each entry. Above we didn’t
need the index, so we ignored it with the
blank identifier _
. Sometimes we actually want
the indexes though.
:::
::: {.zh}
对数组和切片使用 range
会返回每个条目的索引和值。上面我们不需要使用索引,所以我们用空白标识符 _
忽略它。有时我们实际上需要索引。
:::
for i, num := range nums {
if num == 3 {
fmt.Println("index:", i)
}
}
::: {.en}
range
on map iterates over key/value pairs.
:::
::: {.zh}
range
在 map 中迭代键/值对。
:::
kvs := map[string]string{"a": "apple", "b": "banana"}
for k, v := range kvs {
fmt.Printf("%s -> %sn", k, v)
}
::: {.en}
range
can also iterate over just the keys of a map.
:::
::: {.zh}
range
也可以仅遍历 map 的键。
:::
for k := range kvs {
fmt.Println("key:", k)
}
::: {.en}
range
on strings iterates over Unicode code
points. The first value is the starting byte index
of the rune
and the second the rune
itself.
:::
::: {.zh}
range
在字符串中遍历 Unicode 码点(code points)。第一个值是字符的起始字节位置,第二个值是字符本身。
:::
for i, c := range "go" {
fmt.Println(i, c)
}
}
$ go run range.go
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111