点运算符在结构体和指向结构体的指针上的工作方式有何不同?

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

How does dot operator work on struct vs pointer to struct?

问题

这可能是Go语言中的基础知识。
在结构体和指向结构体的指针上,点号.运算符是如何工作的?

type cc struct {
  x int
}

func main() {
    obj := cc{x:2}
	ptr := &cc{x:3}
	
	fmt.Printf("Hello, %v\n", obj.x) // Hello, 2
	fmt.Printf("Hello, %v\n", ptr.x) // Hello, 3
}

它是如何能够在上述两种情况下访问字段的?

英文:

This might a basic in Go.
How does the dot . operator work on struct vs pointer to struct?

type cc struct {
  x int
}

func main() {
    obj := cc{x:2}
	ptr := &cc{x:3}
	
	fmt.Printf("Hello, %v\n", obj.x) // Hello, 2
	fmt.Printf("Hello, %v\n", ptr.x) // Hello, 3
}

How is it able to access the field in both cases above?

答案1

得分: 3

编译器会自动为指针接收器添加必要的间接引用。因此,ptr.x(*ptr).x是相同的。

> https://golang.org/ref/spec#Selectors

英文:

The compiler adds the necessary indirection automatically for pointer receivers. Thus, ptr.x is the same as (*ptr).x

> https://golang.org/ref/spec#Selectors

答案2

得分: 1

根据语言规范,它只是允许这样做,选择器

  1. 对于类型为 T *T 的值 x,其中 T 不是指针类型或接口类型,x.f 表示在 T 中最浅层的位置上具有 f 的字段或方法。[...]

  2. [...]

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

在你的例子中,ptr 是一个定义的指针类型 *cc,根据规则 1,(*cc).f 是一个有效的选择器,因此规则 3 适用。

英文:

It is simply allowed by the language specifications, Selectors:

> 1. For a value x of type T or *T where T is not a pointer or interface type, x.f denotes the field or method at the shallowest depth in T where there is such an f. [...]
>
> 2. [...]
>
> 3. [...], if the type of x is a defined pointer type and (*x).f is a
> valid selector expression denoting a field (but not a method), x.f is
> shorthand for (*x).f.

In your example, ptr is of a defined pointer type *cc and (*cc).f is a valid selector based on rule 1, therefore rule 3 applies.

huangapple
  • 本文由 发表于 2021年8月7日 04:32:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/68687200.html
匿名

发表评论

匿名网友

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

确定