Explain shared map state and addressability
Explain shared map state and addressability
Assigning a map to another variable does not copy its entries. Both variables refer to the same map data. A function can change entries, but assigning a different map to a parameter changes only that parameter. Make a separate map and copy entries for independent top-level storage.
package main
import "fmt"
func update(m map[string]int) { m["x"] = 5; m = map[string]int{"x": 99}; fmt.Println(m["x"]) }func main() { a := map[string]int{"x": 1} b := a update(b) fmt.Println(a["x"], b["x"])}The entry update is visible through a and b. Rebinding the parameter is not. Concurrent reads are safe when no goroutine modifies the map; concurrent writes or reads with writes require synchronization, covered later.
Expected output:
995 5Update an array value and copy entries
package main
import "fmt"
func main() { a := map[string][2]int{"p": {1, 2}} v := a["p"] v[0] = 8 a["p"] = v b := make(map[string][2]int) for k, val := range a { b[k] = val } v = b["p"] v[0] = 9 b["p"] = v fmt.Println(a["p"], b["p"])}Map entries are not addressable: &a["p"] and a["p"][0] = 8 for this array-valued map are invalid. Read the array, change the copy and write it back. Direct m[k] = v and m[k]++ for integers are permitted. Copying entries is shallow; slice or map values can still share nested data. The library function maps.Clone (Go 1.21+) also makes a shallow copy.
Expected output:
[8 2] [9 2]Try it locally
Copy map[string]int{"tea":3} into a new map using range. Set the copy tea count to 9 and print the original and copied counts.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Maps 08: Explain shared map state and addressability
Check the lesson objective before moving on.
What does b := a do when a is a map?
How do you modify the first element of an array stored in a map?