我不明白为什么在用结构指针(&s
)定义结构(sp
)后,初始结构(s
) 在改变后者 (sp
) 的同时不断被修改。
http://play.golang.org/p/TdcL_QJqfB
type person struct {
name string
age int
}
func main() {
s := person{name: "Sean", age: 50}
fmt.Printf("%p : %g\n", &s, s.age)
sp := &s
fmt.Printf("%p : %g\n", &sp, sp.age)
sp.age = 51
fmt.Printf("%p : %g\n", &sp, sp.age) // yield 51
fmt.Printf("%p : %g\n", &s, s.age) // yields 51, but why not 50 ???
}
输出:
0xc0100360a0 : %!g(int=50)
0xc010000000 : %!g(int=50)
0xc010000000 : %!g(int=51)
0xc0100360a0 : %!g(int=51) // why not 50 ???
我是 C 系列语言、Go 和指针的新手,所以任何指向正确概念或错误的指针 (:) ) 都非常感谢您。提前致谢!
最佳答案
你有一个对象s
。还有一个 sp
指针,它指向 s
。所以当你通过sp
设置age
时,你实际上是在修改s
。
请记住,sp
不是一个单独的对象。这就像一个别名。
关于pointers - 通过结构指针定义结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19774712/