Correct.

    a := make(map[int]string)
    b := a

means that b and a point to the same map.

> Do you know any way in go to copy a map? Or the only way to do it is to 
use json Marshal and Unmarshal?

That is called a "deep copy" and there are third party libraries for this.  
But if you think you need it - just to access a map safely - then almost 
certainly you are Doing It Wrong™.

One option is to use sync.Map, which is safe for concurrent access.

Better: protect your map properly against concurrent access. See 
"Rethinking Classical Concurrency Patterns" by Bryan C. Mills - although if 
you're not familiar with traditional approaches to concurrency, you may 
find this hard to understand (it's worth the effort though)
https://www.youtube.com/watch?v=5zXAHh5tJqQ

One of the patterns which comes out of this video is to use a 1-element 
channel as a way to hold a protected value.  Every time you want to use 
this value, you pop it out of the channel, use it, and then push it back in 
(without keeping a copy).  This gives you the same sort of protection as a 
mutex, but cleaner and simpler.

Here is an example: two goroutines both concurrently updating the same map.
https://go.dev/play/p/nY3ujWh3Mfj

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/38239c7c-2c62-45ef-85ad-3edeb26bda8bn%40googlegroups.com.

Reply via email to