How to Correctly Modify Struct Fields in Go?
Dec 17, 2024 pm 05:58 PMAssigning 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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Go language pack import: What is the difference between underscore and without underscore?

How to implement short-term information transfer between pages in the Beego framework?

How to convert MySQL query result List into a custom structure slice in Go language?

How do I write mock objects and stubs for testing in Go?

How can I define custom type constraints for generics in Go?

How can I use tracing tools to understand the execution flow of my Go applications?

How to write files in Go language conveniently?
