How to copy a map with pointers?

I have a map with pointers and would like to copy/duplicate it and then change some parameters on the duplicated map (without changing the original map too). Here is a small working example:
https://play.golang.org/p/LxPGXpedqei

The problem is due to the pointers I guess that when I change the parameters on the copied map, they also change in original map. So, how to properly copy a map with pointers? Thanks

Your loop here:

	for key, value := range originalMap { //! must be done in this way via key,value otw is linked map
		targetMap[key] = new(str)
		targetMap[key] = value
	}

This part of your loop creates a new empty *str struct but then you overwrite it by copying the original value pointer into the targetMap.

I think what you want to do is something more like this:

	// ------ Copy from the original map to the target map
	for key, value := range originalMap { //! must be done in this way via key,value otw is linked map
		newStr := new(str)	// create the new str
		*newStr = *value	// dereference the value pointer
					// and copy the value of the str
					// into the newStr.
		targetMap[key] = newStr
	}

https://play.golang.org/p/EaqKrccPpy7

1 Like