func (x *operand) assignableTo(check *Checker, T Type, reason *string) bool {
V := x.typ
if check.identical(V, T) { // x 的类型与目标类型等价,则可以赋值
return true
}
Vu := optype(V) // 拿到运算符的 underlying type
Tu := optype(T) // 拿到目标类型的 underlying type
// 处理 x 是常量值的情况
if isUntyped(Vu) {
switch t := Tu.(type) {
case *Basic:
// 目标类型是基础类型,此处判断 x 是否能够表示为该基础类型
case *Sum:
// 如果 x 可以赋值给 Sum 类型所带表的所有类型,则返回 true
return t.is(func(t Type) bool {
return x.assignableTo(check, t, reason)
})
case *Interface:
check.completeInterface(nopos, t)
return x.isNil() || t.Empty() // 如果 T 是 interface, 此时因为 x 是基础类型。那么只有当 x 是 nil, 或者 T 是 interface{} 时,x 才可以赋值给 T
case *Pointer, *Signature, *Slice, *Map, *Chan:
return x.isNil() // nil 可以赋值给指针、函数、切片、Map 以及 chan 类型
}
}
/*
* 如果两个类型的 underlying type 是等价的,那么只要两个类型不同时是 defined type, 就可以进行赋值
* 详见 underlying type 一节的讨论
*/
if check.identical(Vu, Tu) && (!isNamed(V) || !isNamed(T)) {
return true
}
// 如果 T 是 interface, 则判断 x 是否实现了该接口
if Ti, ok := Tu.(*Interface); ok {
// 判断类型 V 是否实现接口 Ti 的方式是检查 V 的方法集合是否覆盖了 Ti 的所有方法
if m, wrongType := check.missingMethod(V, Ti, true); m != nil /* Implements(V, Ti) */ {
// 找到缺失方法,进行错误处理
return false
}
return true
}
// 判断两个 channel 类型是否可以赋值
if Vc, ok := Vu.(*Chan); ok && Vc.dir == SendRecv {
if Tc, ok := Tu.(*Chan); ok && check.identical(Vc.elem, Tc.elem) {
return !isNamed(V) || !isNamed(T)
}
}
return false
}
这两个方法是兼容性检查的主体思路,check.identical()我们已经在类型的等价规则中讨论过,UntypedXXX 的转换规则也已经在基础类型的Untyped 部分中讨论过,后续章节会详细讨论 Underlying Type 的赋值规则,以及如何判断一个类型是否实现了某个接口。