(Transferred from: https://blog.csdn.net/a595364628/article/details/54598227)
First, interface
The interface type defines a set of methods that implement this interface if an object implements a method of an interface 所有 . For a detailed syntax reference, the following example
Type Human struct {name string age int phone String}type Student struct {Human//anonymous field Human School string Loan Float32}type Employee struct {Human//anonymous field Human Company string Money Float32}//human Object Implementation Sayhi method func (H * Human) Sayhi () {fmt. Printf ("Hi, I am%s can call me on%s\n", H.name, H.phone)}//Human Object Implementation Sing method func (H *human) Sing (lyrics string) { Fmt. The}//human object implements the Guzzle method ("La La, la la, Los Angeles, La La la Println), lyrics) *human (guzzle string) {FMT . Println ("Guzzle guzzle guzzle ...", Beerstein)}//Employee Overloads Human Sayhi method func (E *employee) Sayhi () {fmt. Printf ("Hi, I am%s, I work in%s." Call me on%s\n ", E.name, E.company, E.phone)//This sentence can be divided into multiple lines}//student implement Borrowmoney Square Law func (S *student) Borrowmoney (amount float32) {S.loan + = amount//(again and again and ...)} The Employee implements the Spendsalary method func (E *employee) spendsalary (amount float32) {e.money-= amount//More vodka!!! Get me through the day!} Define INTERFACEType Men Interface {sayhi () Sing (lyrics string) guzzle (Beerstein string)}type Youngchap interface {sayhi () Sing (song string) Borrowmoney (amount float32)}type Elderlygent Interface {sayhi () Sing (song string) spends Alary (Amount float32)}
By the above code we can know that interface can be implemented by arbitrary objects. We see the men interface above being implemented by human, student and employee. Similarly, an object can implement any number of interface, such as the above student implements the men and Youngchap two interface.
Finally, any type implements the Null interface (we define this: interface{}), which is the interface with 0 method.