Reputation: 1171
I've a few Actors in my Golang App which require two maps to do their work. Those maps are generated by some intensive database transactions so I don't want to do that in every actor, as a result I've separated the maps generation from the Actors.
The issue that I'm having with this approach is that if I pass those maps to every single one of them they are passed by reference which causes panic as I'm writing and reading concurrently.
My solution to that was to Marshal and Unmarshal those maps every time those are passed to a new Actor, but I want to know if there is a better solution to that.
Upvotes: 2
Views: 2623
Reputation: 1307
Copying the map in loop will be cheaper. Benchmark to be sure. go playground
package main
import (
"fmt"
)
func main() {
src := map[string]string{`one`: `one1`, `two`: `two1`, `three`: `tree1`}
dst := mapClone(src)
delete(src, `one`)
fmt.Println(src)
fmt.Println(dst)
}
func mapClone(src map[string]string) map[string]string {
dst := make(map[string]string, len(src))
for k, v := range src {
dst[k] = v
}
return dst
}
Upvotes: 2