This is a creation in Article, where the information may have evolved or changed.
Polymorphic usage
Package Main//a variety of forms of things, can be operated according to a unified interface// polymorphicImport ("FMT" "Math/rand" "Sort") Type Studentstruct{NamestringIdstring AgeintSortTypeint}type Bookstruct{NamestringAuthorstring}//Slice default pass -through addresstype Studentarray []studentfunc (P Studentarray) Len ()int { returnlen (P)}func (P studentarray) Less (i, Jint)BOOL { returnP[i]. Name <P[j]. Name}func (P studentarray) Swap (i, Jint) {P[i], P[j]=P[j], P[i]}func main () {varStus Studentarray forI: =0; I <Ten; i++{stu:=student{name:fmt. Sprintf ("stu%d", Rand. INTN ( -) ), id:fmt. Sprintf ("110%d", Rand. Int ()), Age:rand. INTN ( -),} stus=Append (Stus, Stu)} for_, V: =range Stus {fmt. Println (v)} FMT. Println ("\ n") sort. Sort (Stus) for_, V: =range Stus {fmt. Println (v)} }
Interface nesting
Package Mainimport"FMT"//interface nested one interface can be nested in another interfaceType ReaderInterface{Read ()}type WriterInterface{Write ()}type readwriterInterface{Reader Writer}type Filestruct{}func (f*File) Read () {fmt. Println ("Read Data")}func (f*File) Write () {fmt. Print ("Write Data")}func Test (rw readwriter) {rw. Read () RW. Write ()}func main () {varF File Test (&f)}
Type assertion
Package Mainimport"FMT"type Studentstruct{NamestringSexstring}//Type Assertion//A function that determines the type of the passed parameterFunc Just (Items ...Interface{}) { forIndex, V: =Range Items {Switchv. (type) { Case BOOL: FMT. Printf ("%d params is bool,value is%v\n", Index, v) Case int, Int64, int32:fmt. Printf ("%d params is int,value is%v\n", Index, v) Casefloat32, Float64:fmt. Printf ("%d params is float,value is%v\n", Index, v) Case string: FMT. Printf ("%d params is string,value is%v\n", Index, v) Casestudent:fmt. Printf ("%d params student,value is%v\n", Index, v) Case*student:fmt. Printf ("%d params *student,value is%v\n", Index, v)} }}func Main () {varb Student =student{Name:"stu01", Sex:"female",} just ( -,8.2,"This is a test", B, &b)}