你能解释一下这个Go指针操作的行为吗?

huangapple go评论89阅读模式
英文:

Can you explain the behavior of this Go pointer manipulation?

问题

package main
import "fmt"

type Item struct {
    val int
}

func main() {
    var items []*Item
    item := Item{}
    items = append(items, &item)
    x := items[0]
    y := *x
    x.val++
    fmt.Printf("x=%v, y=%v\n", *x, y)
}

这段代码输出:

x={1}, y={0}

我不明白为什么这两个值不同。x 是指向数组中第一个元素的指针,我们使用 x 增加了 val 字段的值,所以第一个元素已经改变了。y 是第一个元素,它的 val 也应该改变,但是没有改变?然而,如果将 y := *x 语句移到 x.val++ 之后,那么这两个值就相等了。为什么会这样呢?

英文:
package main
import "fmt"

type Item struct {
	val int
}

func main() {
    var items []*Item
    item := Item{}
    items = append(items, &item)
    x := items[0]
    y := *x
    x.val++
    fmt.Printf("x=%v, y=%v\n", *x, y)
}

This prints:

x={1}, y={0}

I can't understand why the values are different. x is a pointer to the 1st element in the array, and we increment the val field using x, then the 1st element has been changed. y is the first element, and its val should've changed too, but didn't? If, however, the y := *x statement is moved to after x.val++, then the values are equal. Why?

答案1

得分: 3

只有这一行需要解释:

y := *x

它的意思是从指针 *x 中取值,并将其赋给 y,现在 y 有一个与 x 没有关联的新值。

英文:

Only this line needs to be explained

y := *x

and it means to take value from this pointer (*x) and assign it to y, now y has a freshly non connected to x value.

答案2

得分: -2

因为x已经是指向Item的指针。尝试使用y := x

英文:

Because x is already a pointer to a Item. Try just y := x

huangapple
  • 本文由 发表于 2021年12月14日 17:26:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/70346547.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定