英文:
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/
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论