使用键作为数组类型进行哈希 [英] Hash with key as an array type
问题描述
如何在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]:第四季度]
尝试在 要查询元素: 您还可以一步创建地图: How to create a key as array in Go for map.
For example in ruby I can implement it such: 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: 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.
Output: Try it on the Go Playground. To query an element: You can also create the map in one step:
这篇关于使用键作为数组类型进行哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
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}: 第四季,
}
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"
map[KeyType]ValueType
where KeyType
will be [3]int
and ValueType
will be string
.
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]
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",
}