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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀