Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Go (deep) copy keys when inserting into a map?

Tags:

dictionary

key

go

I have a map with complex keys - for example, 2D arrays:

m := make(map[[2][3]int]int)

When I insert a new key into the map, does Go make a deep copy of the key?

a := [2][3]int{{1, 2, 3}, {4, 5, 6}}
m[a] = 1

In other words, if I change the array a after using it as a map key, does the map still contain the old value of a?

like image 395
user200783 Avatar asked Jan 05 '23 23:01

user200783


1 Answers

Short answer, it is copied.

By specification, Arrays are value types.

Go's arrays are values. An array variable denotes the entire array; it is not a pointer to the first array element (as would be the case in C). This means that when you assign or pass around an array value you will make a copy of its contents. (To avoid the copy you could pass a pointer to the array, but then that's a pointer to an array, not an array.) https://blog.golang.org/go-slices-usage-and-internals

See for yourself:

https://play.golang.org/p/fEUYWwN-pm

package main

import (
    "fmt"
)

func main() {
    m := make(map[[2][3]int]int)
    a := [2][3]int{{1, 2, 3}, {4, 5, 6}}

    fmt.Printf("Pointer to a: %p\n", &a)

    m[a] = 1
    for k, _ := range m {
        fmt.Printf("Pointer to k: %p\n", &k)
    }
}

The pointers do not match.

EDIT: The real reason is when inserting into a map, the key value is copied. Or, you can continue to just remember the rule above: arrays are value types and their reuse denotes a copy. Either works here. :)

like image 51
eduncan911 Avatar answered Jan 19 '23 08:01

eduncan911