Assigning New Values to Struct Fields
Consider the following scenario: A Point class is defined with a Move() method that adjusts the x coordinate and a Print() method to display results. However, the code exhibits unexpected behavior, displaying the initial x value instead of the adjusted one after calling Move().
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() }
The issue stems from the fact that Move() is defined as a value receiver, meaning it operates on a copy of the original Point object. Therefore, modifications to s within Move() have no effect on the actual instance.
To resolve this, the Move() method should be defined as a pointer receiver, allowing it to directly interact with the original object:
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() }
Now, when Move() is called, the s variable points to the original Point object, so changes to s.x directly affect the instance. Consequently, calling Print() after Move() correctly displays the updated x coordinate.
The above is the detailed content of Why Does My Go Struct Method Not Modify the Original Object?. For more information, please follow other related articles on the PHP Chinese website!