Home > Article > Backend Development > Why Can\'t I Assign to a Struct Field in a Go Map?
In Go, when attempting to modify a field of a struct stored in a map, the error "can not assign to it" may arise. This issue stems from the concept of addressability, which restricts direct assignment to values within maps.
The pair struct holds two float64 values in a map, such as dictionary["xxoo"].b. Assigning a new value to dictionary["xxoo"].b fails because the map value is not addressable.
Go maps are designed to efficiently store and retrieve data. To maintain this efficiency, map values are not addressable, which means memory management allows them to be moved as needed. Without addressability, the selector (.) operator cannot be used to access the struct field for direct assignment.
To avoid this limitation, use a pointer type as the map value. For example, by defining a map[string]*pair, the pointer indirection makes the struct addressable. This allows for direct assignment, as seen in the following code:
dict := make(map[string]*pair) dict["xxoo"] = &pair{5.0, 2.0} dict["xxoo"].b = 5.0
Alternatively, if using a map with value types, assign a copy of the existing value or provide a new value entirely:
p := dict["xxoo"] p.b = 5.0 dict["xxoo"] = p // or dict["xxoo"] = pair{5.0, 5.0}
By understanding addressability and implementing the appropriate solution, you can effectively manipulate structs stored in Go maps.
The above is the detailed content of Why Can\'t I Assign to a Struct Field in a Go Map?. For more information, please follow other related articles on the PHP Chinese website!