Go语言-interface
概念
Go 语言提供了另外一种数据类型即接口,它把所有的具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了这个接口。
代码
package main import "fmt" type Human struct { name string age int phone string } type Student struct { Human //匿名字段 school string loan float32 } type Employee struct { Human //匿名字段 company string money float32 } //Human实现Sayhi方法 func (h Human) SayHi() { fmt.Printf("Hi,I am %s you can call me on %s\n",h.name,h.phone) } //Human实现Sing方法 func (h Human) Sing(lyrics string) { fmt.Println("La la la la...",lyrics) } //Employee重载Human的SayHi方法 func (e Employee) SayHi() { fmt.Printf("Hi,I am %s,I work at %s. Call me on %s\n",e.name,e.company,e.phone) //Yes you can split into 2 lines here. } // Interface Men被Human,Student和Employee实现 // 因为这三个类型都实现了这两个方法 type Men interface { SayHi() Sing(lyrics string) } func main() { fmt.Println("-- -- --") mike := Student{Human{"Mike",25,"222-222-XXX"},"MIT",0.00} paul := Student{Human{"Paul",26,"111-222-XXX"},"Harvard",100} sam := Employee{Human{"Sam",36,"444-222-XXX"},"Golang Inc.",1000} Tom := Employee{Human{"Sam","Things Ltd.",5000} //定义Men类型的变量i var i Men //i能存储Student i = mike fmt.Println("This is Mike,a Student:") i.SayHi() i.Sing("November rain") fmt.Println("") //i也能存储Employee i = Tom fmt.Println("This is Tom,an Employee:") i.SayHi() i.Sing("Born to be wild") fmt.Println("") //定义了slice Men fmt.Println("Let's use a slice of Men and see what happens") x := make([]Men,3) //T这三个都是不同类型的元素,但是他们实现了interface同一个接口 x[0],x[1],x[2] = paul,sam,mike for _,value := range x { value.SayHi() } fmt.Println("-- -- --") }
运行:
D:\2019\hellotoday\src\main1>go run go2.6.go -- -- -- This is Mike,a Student: Hi,I am Mike you can call me on 222-222-XXX La la la la... November rain This is Tom,an Employee: Hi,I am Sam,I work at Things Ltd.. Call me on 444-222-XXX La la la la... Born to be wild Let's use a slice of Men and see what happens Hi,I am Paul you can call me on 111-222-XXX Hi,I work at Golang Inc.. Call me on 444-222-XXX Hi,I am Mike you can call me on 222-222-XXX -- -- --