Perhaps it's a very noob question, but I can't exactly understand why this difference happens in my copy methods.
Until now I have had the assumption that you can not copy maps due to the internal structure being a "reference" and all you are passing around is basically a map header. (... paraphrasing a bit)
Given the following simplified example:
// go version go1.19.6 linux/amd64
var globalMap = map[int]string{
0: "foo",
1: "bar",
}
func copyGlobalMap() map[int]string {
copiedMap := make(map[int]string)
globalMap, copiedMap = copiedMap, globalMap
return copiedMap
}
func copyMap(sourceMap map[int]string) map[int]string {
copiedMap := make(map[int]string)
sourceMap, copiedMap = copiedMap, sourceMap
return copiedMap
}
func main() {
fmt.Println("--- Example 1 ----")
copiedMap := copyMap(globalMap)
globalMap[1] = "moo"
fmt.Printf("Original map %+v\n", globalMap)
fmt.Printf("Copied map %+v\n", copiedMap)
fmt.Println("--- Example 2 ----")
copiedMap = copyGlobalMap()
globalMap[1] = "moo"
fmt.Printf("Original map %+v\n", globalMap)
fmt.Printf("Copied map %+v\n", copiedMap)
}
I receive a following output:
--- Example 1 ----
Original map map[0:foo 1:moo]
Copied map map[0:foo 1:moo]
--- Example 2 ----
Original map map[1:moo]
Copied map map[0:foo 1:moo]
As you can see the Example 1 behaves as is always thought - maps are "entangled". But the second example seems to imply that a separate copy was achieved.
Can anyone explain why this (seemingly?) works?
Note: Observed such global swap in a code-base taking a snapshot of a global cache. Firstly I didn't believe it was working properly, but seems to be.