在go中增加struct变量 [英] Increment struct variable in go

查看:109
本文介绍了在go中增加struct变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我原本希望看到3,这是怎么回事?

I was expecting to see 3, what's going on?

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())
}

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

推荐答案

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

Your method receiver is a struct value, which means the receiver gets a copy of the struct when invoked, therefore it's incrementing the copy and your original isn't updated.

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

To see the updates, put your method on a struct pointer instead.

func (self *Counter) increment() {
    self.count++
}

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

Now self is a pointer to your counter variable, and so it'll update its value.

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

这篇关于在go中增加struct变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆