此Go代码如何在不取消引用的情况下通过指针设置对象的值?
问题描述:
I'm learning Go from a Java/Python background, and am confused by this code from the Go tutorial. In the following code, the line
p.X = 1e9
sets the value of v.X to 1e9 using pointer p. As p is merely a pointer to v, isn't dereferencing necessary to set v's value? Thus the correct statement would be:
*p.X = 1e9
Naturally, this results in an error. Can someone explain why the Go example code works as it is?
Code in question:
package main
import (
"fmt"
)
type Vertex struct {
X int
Y int
}
func main() {
v := Vertex{1, 2}
p := &v
p.X = 1e9
fmt.Println(v)
}
答
In go, the compiler automatically converts the expression to (*p).X
. From the the language spec:
if the type of x is a named pointer type and (*x).f is a valid selector expression denoting a field (but not a method), x.f is shorthand for (*x).f.