// `iface` is for non-empty interface
typeifacestruct{tab*itabdataunsafe.Pointer}// `eface` is for the empty interface.
typeefacestruct{_type*_typedataunsafe.Pointer}
iface是一个非空接口类型,它用于描述包含方法的接口类型。
tab:描述了接口定义和实现的信息。
data:一个指向数据的unsafe.Pointer。
eface是一个空接口类型,它用于描述不包含方法的接口类型。
_type:描述了数据的类型信息,指向数据的指针指向实际的值,它可以是任何类型的值
unsafe.Pointer:数据的位置。
常见问题
接口带有类型不等于 nil
1
2
3
4
5
6
funcmain(){varvinterface{}fmt.Println(v==nil)// true
v=(*int)(nil)// 将一个*int类型的nil指针赋值给了一个空接口变量 v
fmt.Println(v==nil)// false
}
funcmain(){typeStringerinterface{String()string}variinterface{}=int64(100)s,ok:=i.(Stringer)// 如果这样写 s := i.(Stringer) 会抛出异常:panic: interface conversion: int64 is not main.Stringer: missing method String,因为 int64 不能转为 Stringer 类型
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
funcwhatIsThis(iinterface{}){switcht:=i.(type){caseint:fmt.Println("It's an integer!")casestring:fmt.Println("It's a string!")default:fmt.Printf("Don't know what type %T is!\n",t)}}funcmain(){whatIsThis(42)whatIsThis("hello")whatIsThis(true)}
检查接口的实现
由于 Go 的接口是隐式实现,可以通过下面的方法检查接口是否实现。
1
2
3
4
// 验证 *People 是否实现 sort.Interface,可隐式转换成 People
var_sort.Interface=(*People)(nil)// 验证 People 是否实现 sort.Interface
var_sort.Interface=People{}