Golang选择器 – 关于指针规范示例的问题

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

Golang selectors - question about pointers spec sample

问题

我正在阅读有关选择器的规范:https://golang.org/ref/spec#Selectors

type T0 struct {
    x int
}

func (*T0) M0()

type T1 struct {
    y int
}

func (T1) M1()

type T2 struct {
    z int
    T1
    *T0
}

func (*T2) M2()

type Q *T2

var t T2     // t.T0 != nil
var p *T2    // p != nil and (*p).T0 != nil

我不理解最后两行的注释。
在我这里,t 和 p 都是 nil。

英文:

I'm reading the spec about selectors: https://golang.org/ref/spec#Selectors

type T0 struct {
	x int
}

func (*T0) M0()

type T1 struct {
	y int
}

func (T1) M1()

type T2 struct {
	z int
	T1
	*T0
}

func (*T2) M2()

type Q *T2

var t T2     // with t.T0 != nil
var p *T2    // with p != nil and (*p).T0 != nil

I don't understand the comments of the last two lines.
At me t and p = nil

答案1

得分: 1

规范中写道:

> 例如,给定以下声明:
>
> [你复制的代码片段]
>
> 可以这样写:
>
> [另一个带有选择器示例的代码片段]

考虑 var t T2。结构体 T2 嵌入了一个指向 T0 的指针。因此注释中的“with t.T0 != nil”表示类型为 T2 的变量 t 具有非空的嵌入 T0 字段。基本上是这样的:

var t = T2{
     T0: &T0{},
}

然后,对于这样的变量,你可以编写选择器表达式 t.x,它等同于后续代码片段中显示的 (*t.T0).x。由于 x 是仅在 T0 中声明的字段,表达式 t.x 相当于对嵌入的 t.T0 进行解引用,为了使其有效,t.T0 必须是非空的。

对于 var p *T2 也是一样的:嵌入的 T0 必须是非空的,而且 p 本身必须是非空的(它是一个指针)。基本上是这样的:

var p = &T2{
     T0: &T0{},
}

然后你可以编写表达式 p.x,它相当于对 p 和嵌入的 T0 字段进行解引用,就像注释中显示的 (*(*p).T0).x

英文:

The specs says:

> For example, given the declarations:
>
> [the code snippet you copied]
>
> one may write:
>
> [another code snippet with selector examples]

Consider var t T2. The struct T2 embeds a pointer to T0. So the comment "with t.T0 != nil" means a variable t of type T2 with a non-nil embedded T0 field. Basically this:

var t = T2{
     T0: &T0{},
}

Then with such a variable, you can write the selector expression t.x, which equals (*t.T0).x showed in the subsequent code snippet. Since x is a field declared only in T0, the expression t.x amounts to dereferencing the embedded t.T0, which must be non-nil for that to be valid.

Same goes for var p *T2: the embedded T0 must be non-nil, and p itself must be non-nil (it's a pointer). Basically this:

var p = &T2{
     T0: &T0{},
}

Then you can write the expression p.x, which amounts to dereferencing both p and the embedded T0 field as shown in the comment (*(*p).T0).x

huangapple
  • 本文由 发表于 2021年9月18日 00:22:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/69226683.html
匿名

发表评论

匿名网友

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

确定