有了对 Named 类型与 Underlying Type 的了解,我们就可以对与类型相关的很多行为有更深入的理解了。Go Spec中将类型概述为 "A type determines a set of values together with operations and methods specific to those values", 简单来说就是值与方法的集合。对于 Named 类型而言,通过类型结构可以发现:值保存在 Underly Type 中,而方法保存在Named 类型之中。所以在形如X.sel的表达式,在不考虑内嵌属性的情况下,如果 sel 是属性,则会从 Underlying Type 中查找,而如果 sel 是方法,则与 Underlying Type 无关。参见如下代码:
上述代码中,类型 A, B, C 的 Underlying Type 都是struct { name string }, 对应Struct 类型, 所以类型 C 引用属性 name 没有问题。而方法getName()定义在类型 A 上,所以通过类型 C 无法引用。对于申明type name decl, name 的 Underlying Type 确定逻辑如下:
其中参数 t 是 decl 的类型,即如果 decl 是 Named 类型,则递归查找其 Underlying Type, 直到遇到非 Named 类型为止,则该类型就是整个链上所有 Named 类型的 Underlying Type.
type A struct {
name string
}
func (this *A) getName() string {
return "A: " + this.name
}
type B A
// 可以为类型 B 定义与类型 A 一样的方法
func (this *B) getName() string {
return "B: " + this.name
}
type C B
func TestABC(t *testing.T) {
var c C = C{name: "golang"} // OK, C 的 underlying type 是 A, 也有 name 属性
_ = c.name // 可以引用 name 属性
_ = c.getName() // Compile error: c.getName undefined (type C has no field or method getName) [MissingFieldOrMethod]
}
func under(t Type) Type {
if n := asNamed(t); n != nil {
return n.under()
}
return t
}