Home > Backend Development > Golang > How to Correctly Modify Struct Fields in Go?

How to Correctly Modify Struct Fields in Go?

Mary-Kate Olsen
Release: 2024-12-17 17:58:10
Original
220 people have browsed it

How to Correctly Modify Struct Fields in Go?

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)
}
Copy after login

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
Copy after login

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)
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template