小编典典

哈希与键作为数组类型

go

如何在Go for map中将键创建为数组。例如在ruby中,我可以这样实现:

quarters = {
  [1, 2, 3] => 'First quarter',
  [4, 5, 6] => 'Second quarter',
  [7, 8 ,9] => 'Third quarter',
  [10, 11, 12] => 'Fourh quarter',
}
quarters[[1, 2, 3]] 
# => "First quarter"

Golang的外观如何?


阅读 211

收藏
2020-07-02

共1个答案

小编典典

数组类型(不像片)在Go具有可比性,所以在它什么神奇:你可以定义它像任何其他地图:map[KeyType]ValueType这里KeyType[3]intValueTypestring

比较操作符
==和=必须为键类型的操作数被完全定义!; 因此,键类型不能为函数,映射或切片。

m := map[[3]int]string{}

m[[3]int{1, 2, 3}] = "First quarter"
m[[3]int{4, 5, 6}] = "Second quarter"
m[[3]int{7, 8, 9}] = "Third quarter"
m[[3]int{10, 11, 12}] = "Fourth quarter"

fmt.Println(m)

输出:

map[[1 2 3]:First quarter [4 5 6]:Second quarter 
    [7 8 9]:Third quarter [10 11 12]:Fourth quarter]

Go Playground上尝试一下。

要查询元素:

fmt.Println(m[[3]int{1, 2, 3}]) // Prints "First quarter"

您还可以一步创建地图:

m := map[[3]int]string{
    [3]int{1, 2, 3}:    "First quarter",
    [3]int{4, 5, 6}:    "Second quarter",
    [3]int{7, 8, 9}:    "Third quarter",
    [3]int{10, 11, 12}: "Fourth quarter",
}
2020-07-02