funcisOrdered(typ Type) bool { returnis(typ, IsOrdered) }funcComparable(T Type) bool { returncomparable(T, nil) } // funccomparable(T Type, seen map[Type]bool) bool {if seen[T] {returntrue }if seen ==nil { seen =make(map[Type]bool) } seen[T] =true// If T is a type parameter not constrained by any type// list (i.e., it's underlying type is the top type),// T is comparable if it has the == method. Otherwise,// the underlying type "wins". For instance//// interface{ comparable; type []byte }//// is not comparable because []byte is not comparable.if t :=asTypeParam(T); t !=nil&&optype(t) == theTop {return t.Bound().IsComparable() }switch t :=optype(T).(type) {case*Basic:// assume invalid types to be comparable// to avoid follow-up errorsreturn t.kind != UntypedNilcase*Pointer, *Interface, *Chan:returntruecase*Struct:for _, f :=range t.fields {if!comparable(f.typ, seen) {returnfalse } }returntruecase*Array:returncomparable(t.elem, seen)case*Sum: pred :=func(t Type) bool {returncomparable(t, seen) }return t.is(pred)case*TypeParam:return t.Bound().IsComparable() }returnfalse}
可以发现 Function 类型不在 comparable 函数中的任何一个 case 中,因此它是不可比较的,而 struct 类型可比较的前提是其所有属性都是可比较类型。来看如下代码:
functypecheck() {typeUserstruct { Name string }typePeoplestruct { Name string }var u1, u2 User// case 1: 相同类型,且类型可比较,无编译错误if u1 == u2 {// No compile error }// case 2: 不同类型,虽然两个类型都是可比较类型,但由于类型不同,相互之间无法比较var p Peopleif u1 == p {// Compile error: cannot compare u1 == p (mismatched types User and People) [MismatchedTypes] }// case 3: 相同类型,但函数类型不可比较,所以变量之间不可比较var f1 func()var f2 func()if f1 == f2 {// Compile error: cannot compare f1 == f2 (operator == not defined for func()) }}
上例中 User 类型所有的属性都是可比较的,所以 u1 == u2 没有问题,而 u1 与 p 是不同的类型,所以无法比较。再看如下代码:
typeUserstruct { Name string Age func() int}var u1, u2 Userif u1 == u2 {// Compile error: cannot compare u1 == u2 (operator == not defuned for User) [UndefinedOp]}
当我们给 User 添加一个函数字段时,类型检查器报告了编译错误,因为通过上面 comparable 方法可以发现,函数属性的加入让 User 变成不可比较的类型了,所以类型检查器会说== 操作符对该类型没有定义。