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()
}
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