package main import ( "fmt" ) //注意:1:interface 可以被任意對象實現,一個類型/對象也可以實現多個 interface,2:方法不能重載,如 eat() eat(s string) 不能同時存在 //組合:將一個 interface1 嵌入到另一個 interface2 的聲明中。其作用相當於把 interface1 的函數包含到 interface2 中,但是組合中不同有重複的方法。1.只要兩個接口中的方法列表相同(與順序無關),即爲相同的接口,可以相互賦值。2. interface1 的方法列表屬於另一個 interface2 的方法列表的子集,interface2 可以賦值給 interface1,反之不成立(因爲方法缺失),interface2 中的方法會覆蓋 interface1 中同名的方法。3.可以嵌入包中的 interface type person struct { name string age int } func (p person) printMsg() { fmt.Printf("I am %s, and my age is %d.\n", p.name, p.age) } func (p person) eat(s string) { fmt.Printf("%s is eating %s ...\n", p.name, s) } func (p person) drink(s string) { fmt.Printf("%s is drinking %s ...\n", p.name, s) } type people interface { printMsg() peopleEat //組合 peopleDrink //eat() //不能出現重複的方法 } /** type people interface { printMsg() eat() drink() } */ type peopleDrink interface { drink(s string) } type peopleEat interface { eat(s string) } type peopleEatDrink interface { eat(s string) drink(s string) } type foodie struct { name string } func (f foodie) eat(s string) { fmt.Printf("I am foodie, %s. My favorite food is the %s.\n", f.name, s) } func echoArray(a interface{}) { b, _ := a.([]int) //這裡是斷言實現類型轉換,如何不使用就會報錯 for _, v := range b { fmt.Println(v, " ") } return } //要點:1interface關鍵字用來定義一個接口,2.Go沒有implements、extends等關鍵字,3.實現一個接口的方法就是直接定義接口中的方法4.要實現多態,就要用指針或&object語法 func main() { //定義一個people interface類型的變量p1 var p1 people p1 = person{"zhuihui", 40} p1.printMsg() p1.drink("orange juice") //同一類可以屬於多個 interface, 只要這個類實現了這個 interface中的方法 var p2 peopleEat p2 = person{"zengzhihai", 40} p2.eat("bread") //不同類也可以實現同一個 interface var p3 peopleEat p3 = foodie{"ceshi"} p3.eat("noodle") //interface賦值 p3 = p1 //p3中的方法會被p1中覆蓋 p3.eat("noodle") //interface查詢 //將子集peopleEat 轉成people類型 if p4, ok := p2.(people); ok { p4.drink("water") fmt.Println(p4) } //interface{}使得我們可以向函數傳遞任意類型的變量; //斷言解決在使用interface{}的情況下,空接口類型向普通類型轉換的類型轉換問題; //普通類型之間的轉換最好使用顯式的類型轉換,否者很可能導致嚴重的錯誤。 a := []int{3, 5, 6} echoArray(a) } //可以作爲任何形參和返回類型,mixed
本文以代碼形式做案例,講述go語言當中interface的使用方法。
閲完此文,您的感想如何?
-
有用
0
-
沒用
0
-
開心
0
-
憤怒
0
-
可憐
0
1.如文章侵犯了您的版權,請發郵件通知本站,該文章將在24小時内刪除;
2.本站標注原創的文章,轉發時煩請注明來源;
3.交流群: 2702237 13835667
相關課文
-
GO語言GORM如何更新字段
-
gorm如何創建記錄與模型定義需要注意什麽
-
gorm一般查詢與高級查詢
-
GORM時間戳跟蹤及CURD(增刪改查)
我要說說
網上賓友點評
課文推薦