Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang: I have a map of int to struct. Why can't I directly modify a field in a map value? [duplicate]

Tags:

Why do we have to first read the struct, modify it, and then write it back to the map? Am I missing some kind of implied hidden cost in modifying fields of structs in other data structures (like a map or a slice)?

Edit: I realize I can use pointers, but why is this not allowed by Go?

type dummy struct {     a int } x := make(map[int]dummy) x[1] = dummy{a:1} x[1].a = 2 
like image 311
kanu Avatar asked Nov 13 '16 20:11

kanu


People also ask

How do I change the value of maps in Golang?

To update value for a key in Map in Go language, assign the new value to map[key] using assignment operator. If the key we are updating is already present, then the corresponding value is updated with the new value.

How do I deep copy a map in Golang?

Maps in Go are reference types, so to deep copy the contents of a map, you cannot assign one instance to another. You can do this by creating a new, empty map and then iterating over the old map in a for range loop to assign the appropriate key-value pairs to the new map.

Can struct be key in map Golang?

In maps, most of the data types can be used as a key like int, string, float64, rune, etc. Maps also allow structs to be used as keys.

How do you assign a struct value in Golang?

Assign Default Value for Struct Field Method of assigning a custom default value can be achieve by using constructor function. Instead of creating a struct directly, the Info function can be used to create an Employee struct with a custom default value for the Name and Age field.


1 Answers

You are storing a struct by value which means that accession of that struct in the map gives you a copy of the value. This is why when you modify it, the struct in the map remains unmutated until you overwrite it with the new copy.

As RickyA pointed out in the comment, you can store the pointer to the struct instead and this allows direct modification of the struct being referenced by the stored struct pointer.

i.e. map[whatever]*struct instead of map[whatever]struct

like image 59
Corvus Crypto Avatar answered Oct 06 '22 23:10

Corvus Crypto