package main
import (
"fmt"
)
type Human struct {
name string
age int
phone string
}
type Student struct {
Human
school string
stuID int
}
type Employee struct {
Human
workname string
worktime int
}
func (h Human) RunAndGo() {
fmt.Printf("name:%s phone:%s run and go\n", h.name, h.phone)
}
func (e Employee) RunAndGo() {
fmt.Printf("RunAndGo work name:%s writecode\n", e.workname)
}
func (e Employee) Work(writecode string) {
fmt.Printf("work name:%s writecode:%s\n", e.workname, writecode)
}
type Men interface {
RunAndGo()
//Work(writecode string)
}
func main() {
m := Student{Human{"mary", 22, "130546587"}, "beijingdaxue", 123456}
m.RunAndGo()
w := Employee{Human{"xiaoli", 25, "150123456"}, "c++ engine", 8}
w.RunAndGo()
w.Work("go language")
x := make([]Men, 2)
x[0], x[1] = m, w //这2个都是不同类型的元素,但是他们实现了interface同一个接口
for _, value := range x {
value.RunAndGo()
}
}
运行:
go run testInterface.go
结果:
name:mary phone:130546587 run and go
RunAndGo work name:c++ engine writecode
work name:c++ engine writecode:go language
name:mary phone:130546587 run and go
RunAndGo work name:c++ engine writecode