使用键作为数组类型进行哈希 [英] Hash with key as an array type

查看:134
本文介绍了使用键作为数组类型进行哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Go中创建一个数组作为地图。
例如在ruby中我可以实现它:

  quarters = {
[1,2, 3] => '第一季',
[4,5,6] => '第二季',
[7,8,9] => '第三季',
[10,11,12] => 'fourh quarter',
}
quarters [[1,2,3]]
#=> 第一季度

如何在高隆看到相同的情况?


Go中的数组类型(不同于切片)是可比较的,所以没有什么神奇的:你可以像任何其他地图一样定义它: map [KeyType] ValueType 其中 KeyType 将为 [3] int ValueType 字符串


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




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

m [[3] int {1,2,3}] =第一季度
m [[3] int {4,5,6}] =第二季度
m [[3 ] int {7,8,9}] =第三季度
m [[3] int {10,11,12}] =第四季度

fmt.Println )

输出:

 地图[[1 2 3]:第一季度[4 5 6]:第二季度
[7 8 9]:第三季度[10 11 12]:第四季度]

尝试在

要查询元素:

  fmt.Println(m [[3] int {1,2,3}])//打印第一季

您还可以一步创建地图:

  m:= map [[3 ] int] string {
[3] int {1,2,3}:第一季,
[3] int {4,5,6}:第二季,
[3] int {7,8,9}:第三季度,
[3] int {10,11,12}: 第四季,
}


How to create a key as array in Go for map. For example in ruby I can implement it such:

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"

How the same will be looked in Golang ?

Array types (unlike slices) in Go are comparable, so there is nothing magical in it: you can just define it like any other maps: map[KeyType]ValueType where KeyType will be [3]int and ValueType will be string.

The comparison operators == and != must be fully defined for operands of the key type; thus the key type must not be a function, map, or slice.

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)

Output:

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

Try it on the Go Playground.

To query an element:

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

You can also create the map in one step:

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",
}

这篇关于使用键作为数组类型进行哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆