Arrays {.en}

数组 {.zh}

::: {.en} In Go, an array is a numbered sequence of elements of a specific length. :::

::: {.zh}

在 Go 中,数组是具有固定长度的且编号的元素序列。

:::

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

::: {.en} Here we create an array a that will hold exactly 5 int s. The type of elements and length are both part of the array’s type. By default an array is zero-valued, which for ints means 0s. :::

::: {.zh}

在这里,我们创建一个数组 a 来存放刚好 5 个 int。元素的类型和长度都是数组类型的一部分。默认情况下,数组是零值,对于 int 数组来说就是 0。

:::

  1. var a [5]int
  2. fmt.Println("emp:", a)

::: {.en} We can set a value at an index using the array[index] = value syntax, and get a value with array[index]. :::

::: {.zh}

我们可以使用 array [index] = value 语法设置数组指定索引的值,并使用 array [index] 获取特定索引的值。

:::

  1. a[4] = 100
  2. fmt.Println("set:", a)
  3. fmt.Println("get:", a[4])

::: {.en} The builtin len returns the length of an array. :::

::: {.zh}

内置函数 len 返回数组的长度。

:::

  1. fmt.Println("len:", len(a))

::: {.en} Use this syntax to declare and initialize an array in one line. :::

::: {.zh}

使用此语法在一行中声明和初始化数组。

:::

  1. b := [5]int{1, 2, 3, 4, 5}
  2. fmt.Println("dcl:", b)

::: {.en} Array types are one-dimensional, but you can compose types to build multi-dimensional data structures. :::

::: {.zh}

数组类型是一维的,但您可以组合类型来构建多维数据结构。

:::

  1. var twoD [2][3]int
  2. for i := 0; i < 2; i++ {
  3. for j := 0; j < 3; j++ {
  4. twoD[i][j] = i + j
  5. }
  6. }
  7. fmt.Println("2d: ", twoD)
  8. }

::: {.en} Note that arrays appear in the form [v1 v2 v3 ...] when printed with fmt.Println. :::

::: {.zh}

请注意,当使用 fmt.Println 打印时,数组以“[v1 v2 v3 …]”的形式出现。

:::

  1. $ go run arrays.go
  2. emp: [0 0 0 0 0]
  3. set: [0 0 0 0 100]
  4. get: 100
  5. len: 5
  6. dcl: [1 2 3 4 5]
  7. 2d: [[0 1 2] [1 2 3]]

::: {.en} You’ll see slices much more often than arrays in typical Go. We’ll look at slices next. :::

::: {.zh}

在典型的 Go 程序种,切片(slide)比数组更常见。我们接下来会讨论切片。

:::