This is a creation in Article, where the information may have evolved or changed.
The go interface is very powerful, in addition to being used as a general interface. It is also the basis for the run-time polymorphism of go. More capable of delivering beyond boost::any. Xu Xiwei's "Go Language programming" has a more in-depth analysis and introduction to the interface mechanism.
Combined with the description of the book plus my own understanding. Organized the data structure and basic operation description of the Go interface.
It is important to note that the following structure refers to some of the code in the book, and does a great deal of refinement, only to be able to describe and understand the implementation principle of the Go interface in the simplest way. If my understanding and realization of the situation of thousands of miles, but also to correct.
Types of data structures
typedefstruct _MemberInfo { constchar * tag; // 方法原型 void * addr; // 方法地址(函数入口地址)} MemberInfo;typedefstruct _TypeInfo { MemberInfo* members[]; // 成员数组} TypeInfo;
Data structure of the interface
typedef struct _InterfaceMemberInfo { const char** tags;} InterfaceMemberInfo;// 接口typedef struct _Interface { InterfaceMemberInfo* inter; TypeInfo* type;//...} Interface;
The data structures for interfaces and types are as follows:
Interface Operation algorithm
Type assigns a value to the interface
Very simple, check the type of MemberInfo structure of tags is not the interface of the INTERFACEMEMBERINFO structure of tags in the super-set
- Yes, let the typeinfo of the interface point to that type
- No, cannot assign value, neither the type nor the interface is implemented
Interface Query
Directly checks the data structure of the type of the interface to which the TypeInfo points
- If a matching content interface query is found successfully
- If no matching content query fails
Interface Assignment Value
Is still a comparison between tags in the INTERFACEMEMBERINFO structure and whether the fit one is another superset of the relationship.
- Can be assigned if established
- cannot be assigned if not established