go接口

时间:2021-09-17 13:55:36
// 接口例子
package main import "fmt" type Human struct {
Name string
Age int
Sex string
Phone string
}
type Student struct {
Human
School string
Id string
}
type Employee struct {
Human
Company string
Salary float32
} func (h *Human) SayHello() {
fmt.Printf("Hello!,I am %s you can call me on %s\n", h.Name, h.Phone)
}
func (h *Human) Sing(lyrics string) {
fmt.Println("La la la la ...", lyrics)
}
func (e *Employee) SayHello() {
fmt.Printf("Hello!,I am %s ,I work at %s,you can call me on %s\n", e.Name, e.Company, e.Phone) } type Men interface {
SayHello()
Sing(lyrics string)
} func main() {
mike := &Student{Human{"Mike", 25, "boy", "222-222-XXX"}, "MIT", "00001"}
paul := &Student{Human{"Paul", 26, "girl", "111-222-XXX"}, "Harvard", "00002"}
sam := &Employee{Human{"Sam", 36, "girl", "444-222-XXX"}, "Golang Inc.", 1000}
tom := &Employee{Human{"Tom", 37, "boy", "222-444-XXX"}, "Things Ltd.", 5000}
var i Men
i = mike
fmt.Println("This is Mike ,a Student!")
i.SayHello()
i.Sing("葫芦娃,葫芦娃,啦啦啦啦,叮当叮叮当当葫芦娃....\n")
//
i = tom
fmt.Println("This is Mike ,a Emploee!")
i.SayHello()
i.Sing("葫芦娃,葫芦娃,啦啦啦啦,叮当叮叮当当葫芦娃....\n")
//
x := make([]Men, 3)
x[0], x[1], x[2] = paul, sam, mike
for _, v := range x {
v.SayHello()
}
}