1、接口的定義和實現以及接口的繼承
示例:
package main
import "fmt"
//定義接口類型
type Humaner interface {
//方法,只有聲明,沒有實現,由別的類型(自定義類型)實現
sayhi()
}
type Student struct {
name string
id int
}
//Student實現了此方法
func (tmp *Student) sayhi() {
fmt.Printf("Student[%s, %d] sayhi\n", tmp.name, tmp.id)
}
type Teacher struct {
addr string
group string
}
//Teacher實現了此方法
func (tmp *Teacher) sayhi() {
fmt.Printf("Teacher[%s, %s] sayhi\n", tmp.addr, tmp.group)
}
type MyStr string
//MyStr實現了此方法
func (tmp *MyStr) sayhi() {
fmt.Printf("MyStr[%s] sayhi\n", *tmp)
}
//定義一個普通函數,函數的參數為接口類型
//只有一個函數,可以有不同表現,多態
func WhoSayHi(i Humaner) {
i.sayhi()
}
func main() {
s := &Student{"mike", 666}
t := &Teacher{"bj", "go"}
var str MyStr = "hello mike"
//調用同一函數,不同表現,多態,多種形態
WhoSayHi(s)
WhoSayHi(t)
WhoSayHi(&str)
//創建一個切片
x := make([]Humaner, 3)
x[0] = s
x[1] = t
x[2] = &str
//第一個返回下標,第二個返回下標所對應的值
for _, i := range x {
i.sayhi()
}
}
func main01() {
//定義接口類型的變量
var i Humaner
//只是實現了此接口方法的類型,那么這個類型的變量(接收者類型)就可以給i賦值
s := &Student{"mike", 666}
i = s
i.sayhi()
t := &Teacher{"bj", "go"}
i = t
i.sayhi()
var str MyStr = "hello mike"
i = &str
i.sayhi()
}
#執行結果:
Student[mike, 666] sayhi Teacher[bj, go] sayhi MyStr[hello mike] sayhi Student[mike, 666] sayhi Teacher[bj, go] sayhi MyStr[hello mike] sayhi
