在 go 文档中 named pointer type 是什么意思?

Go Document
中第三个条目说道

3. As an exception, 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.

那么其中 named pointer type 是什么意思?
我的理解是这样的

type A struct {t int}
type B **A

其中 B 我认为是 named pointer type。但如果是的话,那么下面的代码应该是可以运行的。

a := A{t:1}
c := &a
var b B = &c
fmt.Println(c.t)

因为 (*c).t is valid selector,所以 c.t 应该是 (*c).t 的缩写。但是运行之后,发现出现如下的错误

c.t undefined (type B has no field or method t)

那么既然出错了,那么我猜我理解错了,那么我想知道,究竟什么样的算作 named pointer type

阅读 2.5k
1 个回答

你把B拆开就会看的更明白些:

type A struct {t int}
type B *A
type C **A
func main() {
    a := A{t:1}
    b := &a
    c := &b
    fmt.Println(b.t, c.t)
}
// run & output:
main.go:14: c.t undefined (type **A has no field or method t)

如果变量是x一个指针,那么x.t就是(*x).t的缩写,类似于语法糖。但是go只会进行一级推导,如果你是多重指针,就推导不出来了。所以*AA本质上是不同类型的,只是go给你提供了一些书写上的便利。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题