#Deep copying a map

17 messages · Page 1 of 1 (latest)

tribal bloom
#

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?

paper forge
#

There is no real deep copying in Go.

hardy flickerBOT
#
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.

daring kiln
#

basically the same as your existing solution except almost std and generic

paper forge
#

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

hardy flickerBOT
#
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.

paper forge
#

I know. Your runtime will complain. Phrasing might have been bad.

#

and the copy will break the mutex

#

kind of

#

which is why having a generic deep copy will not work for such cases

south sequoia
#

i thought it doesn’t compile pepeSus

#

can’t remember