type 接口名 interface{
方法1(参数列表) [返回值]
方法2(参数列表)[返回值]
}
func (变量 结构体类型)方法1 ([参数列表])(返回值){
}
func (变量 结构体类型)方法2([参数列表])(返回值){
}
package main import ( "fmt" ) //接口的定义与实现 type Hello interface { hello() } type Cat struct { } type Dog struct { } func (c Cat)hello() { fmt.Println("喵~喵~") } func (d Dog)hello() { fmt.Println("汪~汪~") } func main() { var hello Hello hello = Cat{} hello.hello() hello = Dog{} hello.hello() }
Go没有implements或extends关键字,这类编程语言叫作duck typing编程语言。
package main import "fmt" //多态 type Income interface { calculate() float64 source() string } // 固定账单项目 type FixedBinding struct { name string amount float64 } // 其他 type Other struct { name string amount float64 } func (f FixedBinding) calculate() float64{ return f.amount } func (f FixedBinding) source() string { return f.name } func (o Other) calculate() float64{ return o.amount } func (o Other) source() string { return o.name } func main() { f1:=FixedBinding{"project1",1111} f2:=FixedBinding{"project2",2222} o1:=Other{"other1",3333} o2:=Other{"other2",4444} fmt.Println("f1:",f1.source(),f1.calculate()) fmt.Println("f2:",f2.source(),f2.calculate()) fmt.Println("o1:",o1.source(),o1.calculate()) fmt.Println("o2:",o2.source(),o2.calculate()) }
空接口中没有任何方法。任意类型都可以实现该接口。空接口这样定义:interface{},也就是包含0个方法(method)的interface。空接口可表示任意数据类型,类似于Java中的object。
空接口使用场景:
package main import "fmt" //空接口 type I interface{ } func main() { // map的key是string,value是任意类型 map1:=make(map[string]interface{}) map1["name"]="玫瑰" map1["color"]= "红" map1["num"]=22 // 切片是任意类型 sli:=make([]interface{},2,2) fmt.Println(sli) }
instance,ok:=接口对象.(实际类型)
原文:https://www.cnblogs.com/shix0909/p/12991900.html