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 用在我们已经学过的一些数据结构。

:::

  1. package main
  2. import "fmt"
  3. func main() {

::: {.en} Here we use range to sum the numbers in a slice. Arrays work like this too. :::

::: {.zh}

在这里,我们使用 range 来对 slice 中的数字求和。对数组也可以采用这种方法。

:::

  1. nums := []int{2, 3, 4}
  2. sum := 0
  3. for _, num := range nums {
  4. sum += num
  5. }
  6. 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 会返回每个条目的索引和值。上面我们不需要使用索引,所以我们用空白标识符 _ 忽略它。有时我们实际上需要索引。

:::

  1. for i, num := range nums {
  2. if num == 3 {
  3. fmt.Println("index:", i)
  4. }
  5. }

::: {.en} range on map iterates over key/value pairs. :::

::: {.zh}

range 在 map 中迭代键/值对。

:::

  1. kvs := map[string]string{"a": "apple", "b": "banana"}
  2. for k, v := range kvs {
  3. fmt.Printf("%s -> %sn", k, v)
  4. }

::: {.en} range can also iterate over just the keys of a map. :::

::: {.zh}

range 也可以仅遍历 map 的键。

:::

  1. for k := range kvs {
  2. fmt.Println("key:", k)
  3. }

::: {.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)。第一个值是字符的起始字节位置,第二个值是字符本身。

:::

  1. for i, c := range "go" {
  2. fmt.Println(i, c)
  3. }
  4. }
  1. $ go run range.go
  2. sum: 9
  3. index: 1
  4. a -> apple
  5. b -> banana
  6. key: a
  7. key: b
  8. 0 103
  9. 1 111