Assigning New Values to Struct Fields in Go
In Go, structures are commonly used to encapsulate related data and provide a set of methods to manipulate their fields. However, one common problem encountered when working with structure fields is modifying their values correctly.
In the below example, a struct named Point is created with two fields, x and dx. Two methods, Move() and Print(), are defined to modify and output the x field, respectively.
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) }
In main(), a new Point instance is created with default values x=3 and dx=2. The Move() and Print() methods are called, with the expectation that the x field's value would be changed during Move() and the Print() output would reflect the updated value (Final x=5). However, the actual output is as follows:
2014/07/28 15:49:44 New X=5 2014/07/28 15:49:44 Final X=3
This unexpected behavior occurs because the receiver of both methods is defined as a value receiver (i.e., Point) instead of a pointer receiver (*Point). In Go, when a value is passed to a method with a value receiver, a copy of that value is created within the method, and any changes made to the fields of that copy do not affect the original value.
To resolve this issue and modify the original struct, a pointer receiver must be used in both methods. This ensures that the methods operate directly on the original struct and any changes made within them are reflected in the original instance.
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) }
With this modification, the Move() method correctly updates the x field, and the Print() method outputs the updated value.
The above is the detailed content of How to Correctly Modify Struct Fields in Go?. For more information, please follow other related articles on the PHP Chinese website!