Home >Backend Development >Golang >How Can I Correctly Modify Struct Fields Within a Go Map?
Directly Modifying Fields in a Map of Structs in Go
In Go, a map of int to struct allows you to access the struct values by using the key. However, directly modifying a field in the struct value may result in unexpected behavior.
Reason for Indirection
When you access the struct value from the map, you are actually accessing a copy of the struct. Modifying this copy does not modify the original struct in the map. To change the original struct, you need to read it, modify it, and then write it back to the map.
This is because Go stores the struct value in a separate memory location when it is assigned to the map. Modifying the copy does not affect the original value.
Implied Hidden Cost
There is no implied hidden cost in modifying fields of structs in other data structures like slices or maps. The behavior is the same as in the case of a map of ints to structs, where modifications to a copy of the struct do not affect the original.
Use of Pointers
You can use pointers to modify the original struct value in place. By storing the pointer to the struct instead of the struct itself in the map, you can directly access and modify the fields of the original struct.
Example:
import "fmt" type dummy struct { a int } func main() { x := make(map[int]*dummy) x[1] = &dummy{a: 1} x[1].a = 2 fmt.Println(x[1].a) // Output: 2 }
In this example, we access the struct value using a pointer, allowing us to modify its fields directly.
The above is the detailed content of How Can I Correctly Modify Struct Fields Within a Go Map?. For more information, please follow other related articles on the PHP Chinese website!