英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论