我期待看到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)
小智 25
您的方法接收器是一个struct值,这意味着接收器在调用时获取结构的副本,因此它会增加副本并且不会更新原始结构.
要查看更新,请将方法放在结构指针上.
func (self *Counter) increment() {
self.count++
}
Run Code Online (Sandbox Code Playgroud)
现在self是指向counter变量的指针,因此它将更新其值.
http://play.golang.org/p/h5dJ3e5YBC
| 归档时间: |
|
| 查看次数: |
4691 次 |
| 最近记录: |