pointers - 通过结构指针定义结构

标签 pointers struct go

我不明白为什么在用结构指针(&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/

相关文章:

c - c 中的段错误 - 可能与指针有关

if-statement - Golang 模板变量 isset

linux - 日期转换代码在不同机器上表现不同

c - fgets 无法正常工作

[Array of Struct in [Array of Struct in [Array of Struct ]]] 中的结构体动态数组

python - Python 中的 C 风格指针,这是正确的吗?

c - 如何跟踪某个循环的运行量并将值存储到数组中

python - 在 Python 中解包嵌套的 C 结构

使用标准库的好示例 Go 代码

go - 加密/sha256 未声明名称中的 GetSha224