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

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

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

问题

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

  1. p.X = 1e9

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

  1. *p.X = 1e9

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

有问题的代码如下:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type Vertex struct {
  6. X int
  7. Y int
  8. }
  9. func main() {
  10. v := Vertex{1, 2}
  11. p := &v
  12. p.X = 1e9
  13. fmt.Println(v)
  14. }
英文:

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

  1. 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:

  1. *p.X = 1e9

Naturally, this results in an error. Can someone explain why the Go example code works as it is?

Code in question:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type Vertex struct {
  6. X int
  7. Y int
  8. }
  9. func main() {
  10. v := Vertex{1, 2}
  11. p := &v
  12. p.X = 1e9
  13. fmt.Println(v)
  14. }

答案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:

确定