douwen9343 2017-09-27 01:52
浏览 54
已采纳

如何在具有类型接口的情况下向syncmap.Map添加条目

In the example, I'm trying to store 1 at the key "xxxxxxx" in the syncmap called value. The type of value is interface{}. So, I have a type assertion to make it a syncmap.Map, which is mm. Then, I add the new entry to mm. Unfortunately the new entry, doesn't get added to value, only to mm. Looks like mm is a copy or something. I'm not sure how to make this work.

To be specific, I figure I need to do the type assertion to add the entry. But, I think the type assertion is making a copy. Can you advise on how to do this so that the entry ("xxxxxxx", 1) is actually added into the syncmap called value?

func Test(name string, m syncmap.Map) {
        log.Print(name, " ")
        m.Range(func(key, value interface{}) bool {
                log.Println(">>", value)
                mm := value.(syncmap.Map)
                mm.Store("xxxxxxx", 1)
                PrintMap(">>>>>>>>>>>>> " + key.(string), value.(syncmap.Map))
                return true
        })
        log.Println()
}
  • 写回答

1条回答 默认 最新

  • dongqiao9394 2017-09-27 10:23
    关注

    You are correct about the inner map being a copy. To make persistent changes to the maps, use pointers.

    func Test(name string, m *sync.Map) { // make parameter a pointer
        log.Print(name, " ")
        m.Range(func(key, value interface{}) bool {
            mm, ok := value.(*sync.Map) // outer map must also store inner maps as pointers
            mm.Store("xxxxxxx", 1)
            return true
        })
        log.Println()
    }
    

    Update the part of your code that declares the main outer map to store pointers to sync.Map type. Example:

    var m sync.Map // outer map
    m.Store("A", &sync.Map{})
    m.Store("B", &sync.Map{})
    m.Store("C", &sync.Map{})
    
    a, _ := m.Load("A")
    am, _ := a.(*sync.Map)
    am.Store("xxxx", 1)
    

    Note that I've used sync package instead of syncmap since syncmap.Map is now a part of standard library.

    Working example: https://play.golang.org/p/ib-dfXjPDy

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

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向