package main import "fmt" type Humaner interface { SayHi() } type Student struct { name string id int } func (tmp *Student) SayHi() { fmt.Printf("Student%s %d sayhi ", tmp.name, tmp.id) } type Teacher struct { group string addr string } func (tmp *Teacher) SayHi() { fmt.Printf("Teacher%s %s sayhi ", tmp.group, tmp.addr) } type MyStr string func (tmp *MyStr) SayHi() { fmt.Printf("MyStr %s sayhi", *tmp) } func main() { //定义接口类型的变量 var i Humaner //只是实现了此接口方法的类型,那么这个类型的变量(接收者类型)就可以给i赋值 s := &Student{"mike", 1} i = s i.SayHi() t := &Teacher{"mike", "NJ"} i = t i.SayHi() var str MyStr = "hello mike" i = &str i.SayHi() }
执行结果
Studentmike 1 sayhi Teachermike NJ sayhi MyStr hello mike sayhi