4.4.4-6 Interface 类型

Interface 类型的结构定义如下:

type Interface struct {
	methods   []*Func // 接口内显示声明的方法集合,按照 Func 的 less 方法定义的顺序排序
	types     Type    // 当 interface 用于泛型的 constraint 时,用来记录限定的类型集合,当前实现是 Sum 类型
	embeddeds []Type  // 内嵌的接口类型

	allMethods []*Func // 所有内嵌类型的方法与自身方法的全集
	allTypes   Type    // 当通过 type 关键字申明 constraint 类型时,该字段用来保存所有内嵌类型的 constraint 与自身 constraint 的交集。用于泛型

	obj Object // type declaration defining this interface; or nil (for better error messages)
}

从语义上来说,一个接口可能包含一组方法声明、一组内嵌的接口类型、以及一组泛型的 constraints。因为 go 的接口类型非常重要,类型检查器还专门定义了一些用于接口类型的辅助方法:

// $GCROOT/compile/internal/types2/api.go
// 判断类型 V 是否实现了接口 T
func Implements(V Type, T *Interface) bool { /* 忽略函数体 */ }

// $GCROOT/compile/internal/types2/api.go
// 判断 V.(T) 是否合法
func AssertableTo(V *Interface, T Type) bool { /* 忽略函数体 */ }

// $GCROOT/compile/internal/types2/lookup.go
// 该方法用来判断类型 V 的方法集合是否是接口 T 方法集合的子集,如果不是,则返回第一个在 V 中但不在 T 中的方法。该方法用来实现上文的 Implements 方法
func MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool) { /* 忽略方法体 */
}

最后更新于