go中增加struct变量

Osc*_*Ryz 8 go

我期待看到3,发生了什么?

package main

import "fmt"

type Counter struct {
    count int
}

func (self Counter) currentValue() int {
    return self.count
}
func (self Counter) increment() {
    self.count++
}

func main() {
    counter := Counter{1}
    counter.increment()
    counter.increment()

    fmt.Printf("current value %d", counter.currentValue())
}
Run Code Online (Sandbox Code Playgroud)

http://play.golang.org/p/r3csfrD53A

小智 25

您的方法接收器是一个struct值,这意味着接收器在调用时获取结构的副本,因此它会增加副本并且不会更新原始结构.

要查看更新,请将方法放在结构指针上.

func (self *Counter) increment() {
    self.count++
}
Run Code Online (Sandbox Code Playgroud)

现在self是指向counter变量的指针,因此它将更新其值.


http://play.golang.org/p/h5dJ3e5YBC

  • @Corey:我总是使用“self”,这样我就不必尝试解释标识符所引用的内容。我总是知道这是调用该方法的值。我从未发现为每种不同的类型使用不同的名称有什么好处。 (2认同)