Home > Backend Development > Golang > How Can I Modify Struct Fields within a Go Function?

How Can I Modify Struct Fields within a Go Function?

DDD
Release: 2024-12-17 05:51:25
Original
839 people have browsed it

How Can I Modify Struct Fields within a Go Function?

Passing a Struct by Pointer to Modify Fields

In Go, structs are passed by value, which means that any changes made to a struct within a function are not reflected in the original struct. This can be a problem when you want to modify the fields of a struct in a function.

Consider the following code:

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

In this code, the Move method attempts to modify the x field of the Point struct, but because structs are passed by value, the changes made to the struct within the Move method are not reflected in the original struct. As a result, the Print method outputs the original value of x (3), not the updated value (5).

To fix this issue, we need to pass the Point struct by pointer to the Move method. By passing the struct by pointer, we are passing a reference to the original struct, so any changes made to the struct within the Move method will be reflected in the original struct.

Here is the corrected code:

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

With this change, the Move method correctly modifies the x field of the Point struct, and the Print method outputs the updated value of x (5).

The above is the detailed content of How Can I Modify Struct Fields within a Go Function?. 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