给结构体字段赋新值

huangapple go评论90阅读模式
英文:

Assign a new value to a struct field

问题

我有一个关于结构字段的问题。

我创建了一个名为Point的类,其中有一个方法Move(),它通过dx增加或减少对象变量x的值。另一个方法Print()用于输出结果。

main()函数中,我创建了一个新的实例,其中x的默认值为3,dx的默认值为2,然后我调用了Move()Print()方法。我期望在Move()方法中x的值会改变,并且Print()方法会输出Final x=5,但实际上它显示的是:

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

我的代码有什么问题?

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()
}
英文:

I have a problem with structure fields.

I've created a class Point with one method Move() that increases or decreases object variable x by dx. Another method Print is used to output results.

In main() a new instance is created with default x = 3 and dx = 2, then I call Move() and Print(). I expect that value of x is changed during Move() and Print() will produce Final x=5, but instead of it displays this:

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

What's wrong with my code?

<!-- language: lang-golang -->

type Point struct {
  x, dx int
}

func (s Point) Move() {
  s.x += s.dx
  log.Printf(&quot;New X=%d&quot;, s.x)
}

func (s Point) Print() {
  log.Printf(&quot;Final X=%d&quot;, s.x)
}

func main() {
  st := Point{ 3, 2 };
  st.Move()
  st.Print()
}

答案1

得分: 9

你需要在这里使用指针接收器,否则每次只会更改原始对象的副本。在Go语言中,所有东西都是按值传递的。

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()
}
英文:

You need to use a pointer receiver here or you are only changing a copy of the original object every time. Everything is passed by value in go.

type Point struct {
  x, dx int
}

func (s *Point) Move() {
  s.x += s.dx
  log.Printf(&quot;New X=%d&quot;, s.x)
}

func (s *Point) Print() {
  log.Printf(&quot;Final X=%d&quot;, s.x)
}

func main() {
  st := Point{ 3, 2 };
  st.Move()
  st.Print()
}

答案2

得分: 1

这是指针接收器和值接收器之间的区别。

这是指针接收器和值接收器之间的区别。

http://golang.org/doc/faq#methods_on_values_or_pointers

英文:

That's the difference between pointer receiver and value receiver

http://golang.org/doc/faq#methods_on_values_or_pointers

huangapple
  • 本文由 发表于 2014年7月28日 19:56:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/24994721.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定