2,348
社区成员




package main
import "fmt"
type IInfo interface {
GetName() string
GetInfo() string
}
type a struct {
Name string
}
func (this *a) GetName() string {
return "a is " + this.Name
}
func (this *a) GetInfo() string {
return this.GetName()
}
type b struct {
a
}
// 重写一下该方法
func (this *b) GetName() string {
return "b is " + this.Name
}
func main() {
a := a{Name: "dog"}
fmt.Printf("a.GetName: %s\n", a.GetName())
fmt.Printf("a.GetInfo: %s\n", a.GetInfo())
b := b{a}
//输出 b.GetName: b is dog,说明是调用了重写后的方法
fmt.Printf("b.GetName: %s\n", b.GetName())
//输出 b.GetInfo: a is dog,说明是调用的是a的方法,希望得到的结果是调用重写后的方法
fmt.Printf("b.GetInfo: %s\n", b.GetInfo())
}
golang没有继承,就没有基类的概念,也就没有重写。