在Go中增加结构变量

huangapple go评论66阅读模式
英文:

Increment struct variable in 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("当前值 %d", counter.currentValue())
}

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

英文:

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

答案1

得分: 30

你的方法接收器是一个结构体值,这意味着当调用时,接收器会得到结构体的一个副本,因此它会增加副本的值,而不会更新原始值。

要看到更新的结果,请将你的方法放在一个结构体指针上。

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

现在,self 是指向你的 counter 变量的指针,因此它会更新它的值。

英文:

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++
}

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


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

答案2

得分: 1

如果你需要在map中使用自定义类型,你需要使用指针类型的map。因为for l,v :=range yourMapType会接收结构体的副本。

这里是一个示例:

package main

import "fmt"

type Counter struct {
        Count int
}

func (s *Counter) Increment() {
        s.Count++
}

func main() {
        // 使用指针类型的map
        m := map[string]Counter{
                "A": Counter{},
        }

        for _, v := range m {
                v.Increment()
        }
        fmt.Printf("A: %v\n", m["A"].Count)

        // 现在使用指针类型的map
        mp := map[string]*Counter{
                "B": &Counter{},
        }

        for _, v := range mp {
                v.Increment()
        }
        fmt.Printf("B: %v\n", mp["B"].Count)
}

输出结果为:

$ go build && ./gotest
A: 0
B: 1
英文:

I want to add to @user1106925 response.

If you need to use the custom type inside a map you need to use a map to pointer. because the for l,v :=range yourMapType will receive a copy of the struct.

Here a sample:

package main

import "fmt"

type Counter struct {
        Count int
}

func (s *Counter) Increment() {
        s.Count++
}

func main() {
        // Using map to type
        m := map[string]Counter{
                "A": Counter{},
        }

        for _, v := range m {
                v.Increment()
        }
        fmt.Printf("A: %v\n", m["A"].Count)

        // Now using map to pointer
        mp := map[string]*Counter{
                "B": &Counter{},
        }

        for _, v := range mp {
                v.Increment()
        }
        fmt.Printf("B: %v\n", mp["B"].Count)
}

The output is:

$ go build && ./gotest
A: 0
B: 1

huangapple
  • 本文由 发表于 2013年5月17日 21:55:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/16610857.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定