Hi I am trying out Go, I am used to pure functions, I just ran into the problem of passing a map to a function. I found out map are passed by reference and I can't find a way to deep copy the map.
At the moment I can simply iterate over the keys and create an identical map, that is because the map is a simple string-string.
If the map was more complex, perhaps with big types or nested maps, how would I deep-copy such maps?
#Deep copying a map
17 messages · Page 1 of 1 (latest)
Stack Overflow
I want to duplicate an instance of a data structure. Since go does not have any builtins, I am using a third party library: https://github.com/emirpasic/gods.
For example, I may try use deep copy...
There is no real deep copying in Go.
func Copy[M1 ~map[K]V, M2 ~map[K]V, K comparable, V any](dst M1, src M2)
Copy copies all key/value pairs in src adding them to dst. When a key in src is already present in dst, the value in dst will be overwritten by the value associated with the key in src.
basically the same as your existing solution except almost std and generic
shallow copy, tho
deep copy does only make sense for a small subset of objects, imo
I doubt that copying resources like network connections or mutexes does even make sense to deep copy.
would break a lot of stuff
func Clone[M ~map[K]V, K comparable, V any](m M) M
Clone returns a copy of m. This is a shallow clone: the new keys and values are set using ordinary assignment.
you can’t copy a mutex
