go之interface
更新日期:
在go中interface本质上是一个struct:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19type interface struct{
typ *rtype //in reflect
data unsafe.Pointer
}
type rtype struct {
size uintptr
ptrdata uintptr
hash uint32 // hash of type; avoids computation in hash tables
_ uint8 // unused/padding
align uint8 // alignment of variable with this type
fieldAlign uint8 // alignment of struct field with this type
kind uint8 // enumeration for C
alg *typeAlg // algorithm table
gcdata *byte // garbage collection data
string *string // string form; unnecessary but undeniably useful
*uncommonType // (relatively) uncommon fields
ptrToThis *rtype // type for pointer to this type, if used in binary or has methods
}
typ表示interface存储内容的类型信息,data记录了interface存储内容的地址。
任何值X都可以赋予给一个空interface,这种赋予是值传递,即如果X是一个指针,data则等于X的值,如果X非指针,go会copy生成一个X的副本,data则等于这个副本的地址。
- 每一种类型都会有一个对应的rtype信息,相同的类型公用一个rtype,即相同类型产生的interface中typ是相等的。
- rtype中ptrToThis指向这个类型的指针的类型信息,例如rtype a表示类型A的信息,则a.ptrToThis表示类型*A的信息。
- interface中的内容之所有不可寻址就是因为interface存储的是信息的副本(只有存储指针时才可寻址,因为指针的副本和指针所指向的地址都是一样的,这样寻址才有意义)