doutuoben6908 2016-10-26 04:54
浏览 13
已采纳

相当于Python的字典

I am looking for a way to store multiple values for each key (just like we can in python using dictionary) using Go. Is there a way this can be achieved in Go?

  • 写回答

2条回答 默认 最新

  • doushijia5684 2016-10-26 05:21
    关注

    Based on your response in comments I would suggest something like the following using a struct (though if you are only interested in a single value like name for each item in your slice then you could just use a map[int][]string{}

    type Thing struct {
        name string
        age  int
    }
    
    myMap := map[int][]Thing{}
    

    If you want to add things then you just do...

    myMap[100] = append(myMap[100], Thing{"sberry": 37})
    

    Or if you want to create it in place:

    myMap := map[int][]Thing{
            100: []Thing{Thing{"sberry", 37}},
            2:   []Thing{Thing{"johndoe", 22}},
        }
    

    EDIT: Adding a "nameIn" function based on comments as demo:

    func nameIn(things []Thing, name string) bool {
        for _, thing := range things {
            if thing.name == name {
                return true
            }
        }
        return false
    }
    
    if nameIn(myMap[100], "John") {
        ...
    

    If the slices are really big and speed is concern then you could keep a reverse lookup map like map[string]int where an entry would be John: 100, but you will need to most likely use some user defined functions to do your map modifications so it can change the reverse lookup as well. This also limits you by requiring unique names.

    Most likely the nameIn would work just fine.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?