Home >Backend Development >Golang >Why Doesn't Modifying a Go Struct Field in a Value Receiver Method Change the Original Value?
Assigning a New Value to a Struct Field
In Go, when dealing with structures, it's important to understand the concept of value receivers versus pointer receivers. A value receiver operates on a copy of the original value, while a pointer receiver operates directly on the original value.
Consider this code snippet, where the question is raised about unexpectedly unchanged struct field values:
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 expectation is that the Move() method modifies the x field of the Point struct, which should be reflected in the Print() method. However, the output shows that the x field remains unchanged.
The Solution: Using Pointer Receivers
The issue lies in the use of a value receiver in the Move() and Print() methods. In Go, everything is passed by value, meaning that a copy of the original value is created when passing a struct to a function. Therefore, any modifications made to the copy within the function do not affect the original value.
To solve this, we need to use pointer receivers. A pointer receiver allows the function to operate directly on the original value. Here's 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() }
By using a pointer receiver for the Move() and Print() methods, we now operate directly on the original Point struct, and the changes to the x field are reflected correctly.
The above is the detailed content of Why Doesn't Modifying a Go Struct Field in a Value Receiver Method Change the Original Value?. For more information, please follow other related articles on the PHP Chinese website!