package main import "fmt" type Humaner interface { SayHi() } type Student struct { name string id int } func (s *Student) SayHi() { fmt.Printf("student %s id %d sayhi ", s.name, s.id) } type Teacher struct { group string addr string } func (t *Teacher) SayHi() { fmt.Printf("Teacher %s addr %s sayhi ", t.group, t.addr) } type MyStr string func (tmp *MyStr) SayHi() { fmt.Printf("%s sayhi ", *tmp) } //定义一个普通函数,函数的参数为接口类型 //只有一个函数,可以有不同的表现,这就是多态 func WhoSayHi(i Humaner) { i.SayHi() } func main() { s := &Student{"baylor", 1} t := &Teacher{"Mike", "NJ"} var str MyStr = "hello world" 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() } }
执行的结果为
student baylor id 1 sayhi Teacher Mike addr NJ sayhi hello world sayhi student baylor id 1 sayhi Teacher Mike addr NJ sayhi hello world sayhi