定義接口
type Namer interface {
Method1(param_list) return_type
Method2(param_list) return_type
...
}
基礎(chǔ)知識
- 接口不能包含變量,只能定義一組抽象的方法集合。
- 類型不需要顯式聲明它實現(xiàn)了某個接口:接口被隱式地實現(xiàn)。只要類型實現(xiàn)了接口包含的所有抽象方法。那么該類型便屬于該接口的實現(xiàn)類。
- 多個類型可以實現(xiàn)同一個接口,一個類型可以實現(xiàn)多個接口。
- 接口可以嵌套接口。
- **聲明一個
interface{}空接口,可接收任何類型。例如:萬能切片[]interface{},任意Mapmap[string]interface{}**。
多態(tài)
//利用接口實現(xiàn)多態(tài)
type IAnimal interface {
Eat()
}
type Dog struct {
name string
}
func (this *Dog) Eat() {
fmt.Printf("%v 吃 %v\n", this.name, "狗糧")
}
type Cat struct {
name string
}
func (this *Cat) Eat() {
fmt.Printf("%v 吃 %v\n", this.name, "貓糧")
}
func TestIAnimal(t *testing.T) {
//定義一個IAnimal接口類型的切片
anims := []IAnimal{&Dog{"旺財"}, &Cat{"咖啡貓"}}
for n, _ := range anims {
anims[n].Eat()
}
//旺財 吃 狗糧
//咖啡貓 吃 貓糧
}
接口嵌套接口
type IA interface {
AFun()
}
type IB interface {
BFun()
}
//接口可以嵌套接口
type IAB interface {
IA
IB
ABFun()
}
type AB struct {
name string
}
func (this *AB) AFun() {
fmt.Println(this.name + " is A Fun")
}
func (this *AB) BFun() {
fmt.Println(this.name + " is B Fun")
}
func (this *AB) ABFun() {
fmt.Println(this.name + " is AB Fun")
}
type BA struct {
name string
}
func (this *BA) AFun() {
fmt.Println(this.name + " is A Fun")
}
func (this *BA) BFun() {
fmt.Println(this.name + " is B Fun")
}
func (this *BA) ABFun() {
fmt.Println(this.name + " is AB Fun")
}
func TestIAB(t *testing.T) {
//AB和BA結(jié)構(gòu)體都實現(xiàn)了IA、IB、IAB接口
abs1 := []IA{&AB{"AB"}, &BA{"BA"}}
for n, _ := range abs1 {
abs1[n].AFun()
}
//AB is A Fun
//BA is A Fun
abs2 := []IB{&AB{"AB"}, &BA{"BA"}}
for n, _ := range abs2 {
abs2[n].BFun()
}
//AB is B Fun
//BA is B Fun
abs3 := []IAB{&AB{"AB"}, &BA{"BA"}}
for n, _ := range abs3 {
//既可以使用嵌套接口聲明的函數(shù),也可以使用本接口聲明的函數(shù)。
abs3[n].AFun()
abs3[n].ABFun()
}
//AB is A Fun
//AB is AB Fun
//BA is A Fun
//BA is AB Fun
}
類型斷言
類型斷言即Comma-ok斷言。寫法為 value, ok := em.(T)。
- em:要判斷的變量,em必須是interface類型;
- T:被判斷的類型;
- value:返回的值;
- ok:是否為該類型;
func TestCD(t *testing.T) {
cd := &CD{}
//如果變量cd沒有轉(zhuǎn)換成interface{}類型,報如下錯誤:
//invalid type assertion: cd.(IA) (non-interface type *CD on left)
if _, ok := interface{}(cd).(IA); !ok {
fmt.Println("沒有實現(xiàn)")
}
a := &AB{"AB"}
if v, ok := interface{}(a).(IA); ok {
v.AFun()
}
}