In Go, structs are passed by value, which means that any changes made to a struct within a function are not reflected in the original struct. This can be a problem when you want to modify the fields of a struct in a function.
Consider the following code:
type Point struct { x, dx int } func (s Point) Move() { s.x += s.dx log.Printf("New X=%d", s.x) } func (s Point) Print() { log.Printf("Final X=%d", s.x) } func main() { st := Point{ 3, 2 }; st.Move() st.Print() }
In this code, the Move method attempts to modify the x field of the Point struct, but because structs are passed by value, the changes made to the struct within the Move method are not reflected in the original struct. As a result, the Print method outputs the original value of x (3), not the updated value (5).
To fix this issue, we need to pass the Point struct by pointer to the Move method. By passing the struct by pointer, we are passing a reference to the original struct, so any changes made to the struct within the Move method will be reflected in the original struct.
Here is the corrected code:
type Point struct { x, dx int } func (s *Point) Move() { s.x += s.dx log.Printf("New X=%d", s.x) } func (s *Point) Print() { log.Printf("Final X=%d", s.x) } func main() { st := Point{ 3, 2 }; st.Move() st.Print() }
With this change, the Move method correctly modifies the x field of the Point struct, and the Print method outputs the updated value of x (5).
The above is the detailed content of How Can I Modify Struct Fields within a Go Function?. For more information, please follow other related articles on the PHP Chinese website!