Brendan W
Brendan W

Reputation: 3453

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

Upvotes: 7

Views: 4388

Answers (2)

Thundercat
Thundercat

Reputation: 120941

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.

Upvotes: 15

Nyta
Nyta

Reputation: 555

Just like the Cerise answer sais- it is not possible. Instead, you could hold a pointer as a value in the map.

Dereferencing a map index in Golang

Upvotes: 0

Related Questions