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

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

报告相同问题?

悬赏问题

  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失