This is a creation in Article, where the information may have evolved or changed.
I. Overview
What is interface, simply said, interface is a group of method combinations that define an object's set of behaviors through interface;
The interface type defines a set of methods that implement this interface if an object implements all the methods of an interface;
1 Package Main2 3Import"FMT"4 5Type Humanstruct {6Namestring7Ageint 8Phonestring9 }Ten OneType Studentstruct { AHuman//Anonymous Functions -Schoolstring - Loan float32 the } - -Type Employeestruct { - Human +Companystring - Money float32 + } A at //Human Object Implementation Sayhi method -Func (H *Human) Sayhi () { -Fmt. Printf ("Hi, I am%s You can call me on%s\n", H.name, H.phone) - } - - //the Human object implements the Sing method inFunc (H *human) Sing (lyricsstring) { -Fmt. Println ("Lalala ...", lyrics) to } + - //the Human object implements the Guzzle method theFunc (H *human) guzzle (Beersteinstring) { *Fmt. Println ("guzzle guzzle ...", Beerstein) $ }Panax Notoginseng - //Student implements the Borrowmoney method theFunc (S *Student) Borrowmoney (amount float32) { +S.loan + =Amount A } the + //Empolyee Overloaded The human Sayhi method -Func (E *Employee) Sayhi () { $Fmt. Printf ("Hi, I am%s, I work with%s. Call me on%s\n", E.name, E.company, E.phone) $ } - - //employee realizes the method of Spendsalary theFunc (E *Employee) Spendsalary (amount float32) { -E.money-=AmountWuyi } the - //Define Interface Wu /* - type men Interface { About Sayhi () $ Sing (Lyrics string) - guzzle (Beerstein string) - } - A type Youngchap Interface { + Sayhi () the Sing (song string) - Borrowmoney (amount float32) $ } the the type Elderlygent Interface { the Sayhi () the Sing (song string) - spendsalary (amount float32) in } the */ the About //interface men were human,student, employee all realized the //Student, the employee contains the Human anonymous field, all of which also contains its interface implementation theType menInterface { the Sayhi () +Sing (lyricsstring) - } the Bayi Func Main () { theMike: = student{human{"Mike", -,"22-22-xx"},"MIT",0.00} thePAUL: = student{human{"Paul", -,"23-32-xx"},"Harvard",5.00} -Sam: = employee{human{"Sam", $,"33-33-33"},"Gling Inc", +} -Tom: = employee{human{"Tom", -,"33-334-11"},"Things Ltd", -} the the varI men//interface Type thei = &Mike theFmt. Println ("This is Mike, a student\n") - I.sayhi () theI.sing ("My name is Mike") the thei = &Tom94Fmt. Println ("This was Tom, an employee\n") the I.sayhi () theI.sing ("My name is Tom") the 98x: = Make ([]men,3) Aboutx[0], x[1], x[2] = &paul, &sam, &Mike - for_, Value: =range x {101 value. Sayhi ()102 }103}
Second, reflection mechanism
1 Package Main2 3 Import (4 "FMT"5 "reflect"6 )7 8 Func Main () {9 varx float64 =3.4TenP: = reflect. ValueOf (&x) OneV: =P.elem () A FMT. Println (v) -V.setfloat (8.3) - FMT. Println (v) the}