我试图了解为什么以下测试代码没有按预期工作:
package main
import (
"fmt"
"strings"
)
type Test struct {
someStrings []string
}
func (this Test) AddString(s string) {
this.someStrings = append(this.someStrings, s)
this.Count() // will print "1"
}
func (this Test) Count() {
fmt.Println(len(this.someStrings))
}
func main() {
var test Test
test.AddString("testing")
test.Count() // will print "0"
}
这将打印:
"1"
"0"
意思是 someStrings
显然被修改了......然后它不是。
有人知道可能是什么问题吗?
最佳答案
AddString 方法正在使用值(复制)接收器。修改是对副本,而不是原件。必须使用指针接收器来改变原始实体:
package main
import (
"fmt"
)
type Test struct {
someStrings []string
}
func (t *Test) AddString(s string) {
t.someStrings = append(t.someStrings, s)
t.Count() // will print "1"
}
func (t Test) Count() {
fmt.Println(len(t.someStrings))
}
func main() {
var test Test
test.AddString("testing")
test.Count() // will print "0"
}
输出
1
1
关于methods - 为什么通过方法对结构所做的更改不会持续存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16540481/