doushuo2834
2016-04-04 04:51
浏览 21
已采纳

为什么结构中的变量不保留其值?

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.

图片转代码服务由CSDN问答提供 功能建议

如果我有:

  type Foo struct {
  bar int 
} 
   
 
 

以及在Foo上定义的方法(注意,它不是* Foo,只是Foo):

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

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

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

每次myFoo调用incrementBar方法时,其内部是否为0? 即,它永远不会达到2,每次我调用increasBar时,它都会对值0进行++操作。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doushang1890 2016-04-04 05:05
    已采纳

    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/

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题