2013-05-17 83 views
5

我期待看到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()) 
} 

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

+2

差不多http://stackoverflow.com/questions/16540481/why-is-this-struct-not-working – nemo

回答

20

你的方法,接收器是一個結構值,這意味着接收器被調用時,該結構的副本,因此它的遞增副本,你原來不被更新。

要查看更新,請將您的方法放在結構指針上。

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

現在self是指向你的counter變量,所以它會更新它的值。


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

+0

的副本喔.. :)現在它是有道理的感謝 – OscarRyz

+0

不客氣。 – 2013-05-17 14:06:55

+0

@OscarRyz你應該標記這個答案,如果它解決了你的問題。 – Lander