为什么我的结构体中的变量不能保持其值?

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

Why does a variable in my struct not hold its value?

问题

如果我有以下代码:

type Foo struct {
  bar int
}

并且在Foo上定义了一个方法(注意它不是*Foo,只是Foo):

func (self Foo) incrementBar() {
  self.bar++
}

为什么在创建一个Foo并调用该方法两次后:

myFoo := Foo{}
myFoo.incrementBar()
myFoo.incrementBar()

每次myFoo调用incrementBar方法时,bar仍然是0?也就是说,它从未达到2,每次调用incrementBar时,它都对值0执行++操作。

英文:

If I have:

type Foo struct {
  bar int
}

And a method defined on Foo (notice it's not *Foo, just Foo):

func (self Foo)incrementBar() {
  self.bar++
}

Why after making a Foo and calling the method twice:

myFoo := Foo{}
myFoo.incrementBar()
myFoo.incrementBar()

is bar still 0 inside the incrementBar method every time myFoo calls it? i.e. it never gets to 2, each time I call incrementBar it does a ++ operation on the value 0.

答案1

得分: 5

你应该使用指针方法接收器,因为你正在修改内部变量。
当你在incrementBar中使用非指针方法接收器时,会复制一个Foo实例并传递给incrementBar。在incrementBar中修改self不会改变myFoo的值,因为它只是一个副本。

这是一篇关于这个问题的好文章:
http://nathanleclaire.com/blog/2014/08/09/dont-get-bitten-by-pointer-vs-non-pointer-method-receivers-in-golang/

英文:

You should use pointer method receiver since you're altering internal variables.
When you use non-pointer method receiver for incrementBar, an instance of Foo is copied and passed to incrementBar. Altering self in incrementBar does not change value of myFoo because it's merely a copy.

Here is a good article regarding the issue:
http://nathanleclaire.com/blog/2014/08/09/dont-get-bitten-by-pointer-vs-non-pointer-method-receivers-in-golang/

huangapple
  • 本文由 发表于 2016年4月4日 12:51:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/36394778.html
匿名

发表评论

匿名网友

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

确定