type TypeParam struct {
check *Checker // for lazy type bound completion
id uint64 // unique id
obj *TypeName //
index int // parameter index
bound Type // *Named or *Interface; underlying type is always *Interface
}
除此之外还有三个类型用于泛型,其定义如下:
type instance struct {
check *Checker // for lazy instantiation
pos syntax.Pos // position of type instantiation; for error reporting only
base *Named // parameterized type to be instantiated
targs []Type // type arguments
poslist []syntax.Pos // position of each targ; for error reporting only
value Type // base(targs...) after instantiation or Typ[Invalid]; nil if not yet set
}
type bottom struct{}
type top struct{}
bottom 与 top 是两个标记类型。当接口中包含泛型的 constraints 时,我们需要推算出当前接口中 constraints 所包含的实际类型,例如如下申明:
type SmallInt interface {
type int8, int16, int32
}
type BigInt interface {
type int, int32, int64
}
type MediumInt interface {
SmallInt
BigInt
type int16, int32
}
但凡说道“参数”,就需要使用者将具体的实参传递进去。i, j 是函数 sum 的形参,我们可以将函数看着是一个计算模版,当调用者提供该模版的实参时,我们就可以通过该“模版”计算出最终值。那么“类型参数”该如何传递呢?我们先来看一个典型的泛型定义:
type Node[T comparable] struct {
val T
}
Node 是我们定义的一个类型,但是该类型并不完备:属性 val 的类型 T 还是未知的,由使用者提供。我们可以将 T 看着是 Node 的类型参数,从而将将 Node[T comparable] 看着是一个类型模版,当使用者提供具体的参数类型时,我们就可以得到一个具体的Node类型。例如当 T 为 int32 时,我们得到具体类型是: