这段Go代码如何通过指针设置对象的值,而不进行解引用操作?

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

How does this Go code set the value of an object through a pointer, without dereferencing?

问题

我正在学习Go语言,之前有Java/Python的背景,对Go教程中的这段代码感到困惑。在下面的代码中,这一行:

p.X = 1e9

使用指针p将v.X的值设置为1e9。由于p只是指向v的指针,难道不需要解引用来设置v的值吗? 因此,正确的语句应该是:

*p.X = 1e9

当然,这会导致错误。有人能解释一下为什么Go示例代码按照现在的方式工作吗?

有问题的代码如下:

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)
}
英文:

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)
}

答案1

得分: 5

在Go语言中,编译器会自动将表达式转换为(*p).X。根据语言规范的说明:

如果x的类型是一个命名的指针类型,并且(*x).f是一个有效的选择器表达式,表示一个字段(但不是一个方法),那么x.f就是(*x).f的简写形式。

英文:

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.

huangapple
  • 本文由 发表于 2015年5月26日 10:27:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/30448483.html
匿名

发表评论

匿名网友

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

确定