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) }
funcmain() { 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", 36, "444-222-XXX"}, "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") //i也能存储Employee i = Tom fmt.Println("This is Tom, an Employee:") i.SayHi() i.Sing("Born to be wild") //定义了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() } }
运行结果:
1 2 3 4 5 6 7 8 9 10
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 am Sam, I work at Golang Inc.. Call me on 444-222-XXX Hi, I am Mike you can call me on 222-222-XXX