Home >Backend Development >Golang >How Do Pointer Receivers in Go Impact Struct Modification Within Functions?

How Do Pointer Receivers in Go Impact Struct Modification Within Functions?

Barbara Streisand
Barbara StreisandOriginal
2024-12-23 13:10:21533browse

How Do Pointer Receivers in Go Impact Struct Modification Within Functions?

Modifying Structure Field Values

In Go, when a function receives a structure, it generally receives a copy of the original object. Thus, any modifications made to the structure within that function will not affect the original object.

Consider the following example, where we define a structure Point with two fields, x and dx. The Move method increments x by dx and the Print method prints the value of x.

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()
}

In this code, the Move and Print methods are attached to the Point structure as value receivers. This means that when st is passed to these methods, a copy of the original st object is created. Any modifications made to the copy within these methods will not affect the original st object.

As a result, when we call st.Move(), the copy of st is modified, but the original st object remains unchanged. Consequently, when we print st in st.Print(), we still see the original value of x.

To address this, we must modify the Move and Print methods to use pointer receivers instead of value receivers. This ensures that any modifications made to the structure within these methods will affect 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()
}

By using pointer receivers, we now get the expected output:

2014/07/28 15:49:44 New X=5
2014/07/28 15:49:44 Final X=5

The above is the detailed content of How Do Pointer Receivers in Go Impact Struct Modification Within Functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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