Search code examples
dictionarygopass-by-referencepass-by-value

Is golang map lookup by value or by reference?


When I retrieve a struct from a map in Go, do I get a copy of the value? Or do I get the actual value that's in the map?

For example, let's say I have a map from strings to structs:

type quality struct {
    goodness    int
    crunchiness int 
}
cookies := make(map[string]quality)
cookies["nutrageous"] = quality{goodness: 3, crunchiness: 10}

and I want to modify an entry.

Can I count on the returned value being the same as what's in the map?

c := cookies["nutrageous"]
c.goodness += 5

Or do I also have to go back and modify what's in the map?

c := cookies["nutrageous"]
c.goodness += 5
cookies["nutrageous"] = c

Solution

  • Indexing a map returns a copy of the map value. If the map value is a struct, then modifications to the returned struct value will not change the struct value in the map. You must assign the modified value back to the map.

    If the value is a pointer to a struct, then modifications to the struct will be accessible through the pointer stored in the map.