douzun4443 2015-03-20 20:25
浏览 22
已采纳

哈希与键作为数组类型

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 ?

  • 写回答

2条回答 默认 最新

  • douxitao8170 2015-03-20 20:31
    关注

    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",
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?