Home > Backend Development > Golang > Why Does My Go Struct Method Not Modify the Original Object?

Why Does My Go Struct Method Not Modify the Original Object?

DDD
Release: 2024-12-18 15:04:11
Original
840 people have browsed it

Why Does My Go Struct Method Not Modify the Original Object?

Assigning New Values to Struct Fields

Consider the following scenario: A Point class is defined with a Move() method that adjusts the x coordinate and a Print() method to display results. However, the code exhibits unexpected behavior, displaying the initial x value instead of the adjusted one after calling Move().

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

The issue stems from the fact that Move() is defined as a value receiver, meaning it operates on a copy of the original Point object. Therefore, modifications to s within Move() have no effect on the actual instance.

To resolve this, the Move() method should be defined as a pointer receiver, allowing it to directly interact with 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()
}
Copy after login

Now, when Move() is called, the s variable points to the original Point object, so changes to s.x directly affect the instance. Consequently, calling Print() after Move() correctly displays the updated x coordinate.

The above is the detailed content of Why Does My Go Struct Method Not Modify the Original Object?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template