英文:
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())
}
答案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.
答案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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论