简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM