dpyic24480 2015-02-13 08:52
浏览 176
已采纳

在golang中迭代Struct(地图键)值

I've looked up Structs as keys in Golang maps

I understand iteration over the maps in golang has no guaranteed order. I've followed the example in golang blog, and tried using a struct as a map key.

Here's my code

package main

func main() {
    req := make(map[mapKey]string)

    req[mapKey{1, "r"}] = "robpike"
    req[mapKey{2, "gri"}] = "robert griesemer"
    req[mapKey{3, "adg"}] = "andrew gerrand"
    req[mapKey{4, "rsc"}] = "russ cox"

    var keys []int
    for k := range req {
        keys = append(keys, k.Key)
    }

    for _, k := range keys {
        fmt.Printf("short name : %s , long name : %s
",req[k], req[k]) // How do I iterate here
    }

    sort.Ints(keys)
}

type mapKey struct {
    Key    int
    Option string
}

What I want the results to be is

short name : r , long name : rob pike
short name : gri , long name : robert griesemer
short name : adg , long name : andrew gerrand
short name : rsc , long name : russ cox

And I don't know how I can get the struct value and key iterated by separated data structure.

  • 写回答

1条回答 默认 最新

  • dpqg86714 2015-02-13 09:19
    关注

    Short version? You can't do it that way.

    Long version you, you can use a custom sorter:

    func main() {
        req := make(map[mapKey]string)
    
        req[mapKey{1, "r"}] = "robpike"
        req[mapKey{2, "gri"}] = "robert griesemer"
        req[mapKey{3, "adg"}] = "andrew gerrand"
        req[mapKey{4, "rsc"}] = "russ cox"
    
        var keys mapKeys
        for k := range req {
            keys = append(keys, k)
        }
        sort.Sort(keys)
        for _, k := range keys {
            fmt.Printf("short name : %s , long name : %s
    ", k.Option, req[k])
        }
    }
    
    type mapKey struct {
        Key    int
        Option string
    }
    
    type mapKeys []mapKey
    
    func (mk mapKeys) Len() int           { return len(mk) }
    func (mk mapKeys) Swap(i, j int)      { mk[i], mk[j] = mk[j], mk[i] }
    func (mk mapKeys) Less(i, j int) bool { return mk[i].Key < mk[j].Key }
    

    <kbd>play</kbd>

    Keep in mind that if your mapKey struct have a field that doesn't support equality (aka a struct or a slice) using req[k] won't work.

    In that case you can switch to type mapKeys []*mapKey and map[*mapKey]string.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn