Maps {.en}

关联数组 {.zh}

::: {.en} Maps are Go’s built-in associative data type (sometimes called hashes or dicts in other languages). :::

::: {.zh}

Maps 是 Go 的内建 关联数据类型(有时在其他语言中称为 哈希(hashes)或 字典(dicts))。

:::

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

::: {.en} To create an empty map, use the builtin make: make(map[key-type]val-type). :::

::: {.zh}

要创建一个空 map,请使用内建的 makemake(map[key-type]val-type)

:::

  1. m := make(map[string]int)

::: {.en} Set key/value pairs using typical name[key] = val syntax. :::

::: {.zh}

使用典型的 name[key] = val 语法 设置键/值对。

:::

  1. m["k1"] = 7
  2. m["k2"] = 13

::: {.en} Printing a map with e.g. fmt.Println will show all of its key/value pairs. :::

::: {.zh}

使用 fmt.Println 打印 map 的所有所有键/值对。

:::

  1. fmt.Println("map:", m)

::: {.en} Get a value for a key with name[key]. :::

::: {.zh}

使用 name[key] 获取一个键的值。

:::

  1. v1 := m["k1"]
  2. fmt.Println("v1: ", v1)

::: {.en} The builtin len returns the number of key/value pairs when called on a map. :::

::: {.zh}

map 调用内建的 len 时返回 键/值对 的数量。

:::

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

::: {.en} The builtin delete removes key/value pairs from a map. :::

::: {.zh}

内建的 delete 方法从 map 中删除键/值对。

:::

  1. delete(m, "k2")
  2. fmt.Println("map:", m)

::: {.en} The optional second return value when getting a value from a map indicates if the key was present in the map. This can be used to disambiguate between missing keys and keys with zero values like 0 or "". Here we didn’t need the value itself, so we ignored it with the blank identifier _. :::

::: {.zh}

从 map 获取一个值时,可选第二个返回值表示该键是否存在于这个 map 中。这可用于消除缺失键和键值为 0 值或空值( 0 或者 "")之间的歧义。这里我们不需要值,所以我们用 blank identifier (空白标识符)_ 忽略了它。

:::

  1. _, prs := m["k2"]
  2. fmt.Println("prs:", prs)

::: {.en} You can also declare and initialize a new map in the same line with this syntax. :::

::: {.zh}

你也可以使用此语法在同一行中声明和初始化一个新的 map。

:::

  1. n := map[string]int{"foo": 1, "bar": 2}
  2. fmt.Println("map:", n)
  3. }

::: {.en} Note that maps appear in the form map[k:v k:v] when printed with fmt.Println. :::

::: {.zh}

请注意,当使用 fmt.Println 打印时,map 以map [k:v k:v]的格式输出。

:::

  1. $ go run maps.go
  2. map: map[k1:7 k2:13]
  3. v1: 7
  4. len: 2
  5. map: map[k1:7]
  6. prs: false
  7. map: map[bar:2 foo:1]