以下代码在go1.5验证通过
package main
import (
"fmt"
)
type Person struct {
name string
age int
tel string
}
type Student struct {
Person // 有另一个字段
school string
}
func (p *Person) Print() {
fmt.Printf("Print\n")
p.Hello() //指向person的hello
}
//在person上面定义了一个传值的method
func (p *Person) Hello() {
p.tel = "186"
fmt.Printf("Person My name is %s, and my tel number is %s\n", p.name, p.tel)
}
//多态
func (p *Student) Hello() {
p.tel = "0117"
fmt.Printf("student My name is %s, and my tel number is %s\n", p.name, p.tel)
}
func main() {
anna := new(Student)
anna.Person.name = "jim"
anna.tel = "12345678"
anna.Hello() //student My name is jim, and my tel number is 0117
anna.Person.Hello() //Person My name is jim, and my tel number is 186
anna.Print() //Print
//Person My name is jim, and my tel number is 186 此处在c++会调用Student的Hello接口
}
有疑问加站长微信联系(非本文作者)