--------------------Interface interface
//Definition:Type IhumanerInterface{sayhi ()//interfaces can only be method declarations, no implementations, no data fields}//Student ...Type Studentstruct{IDintnamestring}func (TMP*Student) Sayhi () {fmt. Println ("student[%s,%d] sayhi", Tmp.name, tmp.id)}//Teacher ...Type Teacherstruct{addrstringGroupstring}func (TMP*Teacher) Sayhi () {fmt. Println ("teacher[%s,%d] sayhi", Tmp.addr, Tmp.group)}//mystrType MyStrstringfunc (TMP*mystr) Sayhi () {fmt. Println ("mystr[%s,%d] sayhi", *tmp)} Func Main () {//variables that define interface types varI ihumaner//just the type of method that implements this interface, then this type of variable (receiver type) can be assigned to IS: = &student{"Loong",666} i=s I.sayhi () T:= &teacher{"CLS","ShenZhen"} i=T I.sayhi ()varstr mystr ="Hello Loong"I= &str i.sayhi ()//Print Result//Loong 666. CLS ... hello Loong}
Application of--------------------Interface interface polymorphism
//Application of polymorphismfunc whosayhi (i ihumaner) {i.sayhi ()}//Call polymorphicS: = &student{"Loong",666}t:= &teacher{"CLS","ShenZhen"}varstr mystr ="Hello Loong"Whosayhi (s) whosayhi (t) whosayhi (&str)//Create a slicex: = Make ([]ihumaner,3) x[0] =sx[1] =tx[2] = &Str for_, I: =range x {i.sayhi ()}
--------------------Interface Null interface (task type)
Func Main () { // NULL interface is universal type interface1 // string "ABC"= & v2 // ... And so on . Data type // * * * * * The internal implementation of the printing parameters is the use of NULL interface // FTM. Println (args ... interface{})}
-------------------- Type assertion (type query)
structStudentstruct{IDintnamestring}func Main () {i:= Make ([]Interface{},3) i[0] =1i[1] ="Hello go"i[2] = student{666,"Loong"} //type Query forIndex, data: =Range I {//The first return value, the second returns the true and false of the judging result ifValue, OK: = data. (int); OK = =true { } //data. (string) data. (Student) can be used as a judgment } //Similarly, data. (type) can also be used to determine the type of return int, string, ...}