Why don't changes made to a struct via a method persist? -
i'm trying understand why following test code not working expected:
package main import ( "fmt" "strings" ) type test struct { somestrings []string } func (this test) addstring(s string) { this.somestrings = append(this.somestrings, s) this.count() // print "1" } func (this test) count() { fmt.println(len(this.somestrings)) } func main() { var test test test.addstring("testing") test.count() // print "0" } this print:
"1" "0" meaning somestrings apparently modified... , it's not.
anybody know issue?
the addstring method using value (copy) receiver. modification made copy, not original. pointer receiver must used mutate original entity:
package main import ( "fmt" ) type test struct { somestrings []string } func (t *test) addstring(s string) { t.somestrings = append(t.somestrings, s) t.count() // print "1" } func (t test) count() { fmt.println(len(t.somestrings)) } func main() { var test test test.addstring("testing") test.count() // print "0" } output
1 1
Comments
Post a Comment