Go笔记-继承

时间:2023-03-09 03:57:09
Go笔记-继承
【Go中继承的实现】
    当一个匿名类型被内嵌在结构体中时,匿名类型的可见方法也同样被内嵌,这在效果上等同于外层类型 继承 了这些方法:将父类型放在子类型中来实现亚型
 package main

 import "fmt"

 type Point struct{
x,y float64
} type NamePoint struct{
name string
Point
} func(p *Point)Abs()float64{
return math.Sqrt(p.x*p.x + p.y*p.y)
} func main(){
n := &NamePoint{"gao",Point{3.1,3.3}}
fmt.Println(n.Abs())
} // 输出
5
    内嵌将一个已存在类型的字段和方法注入到了另一个类型里:匿名字段上的方法“晋升”成为了外层类型的方法。当然类型可以有只作用于本身实例而不作用于内嵌“父”类型上的方法,可以覆写方法(像字段一样):和内嵌类型方法具有同样名字的外层类型的方法会覆写内嵌类型对应的方法。
 package main

 import "fmt"

 type point struct{
x,y float64
} type NamePoint struct{
name string
point
} func(p *point)Abs()float64{
return math.Sqrt(p.x*p.x + p.y*p.y)
} // 重写
func(np *NamePoint)Abs()float64{
return np.point.Abs() * 100
} func main(){
n := &NamePoint{"gao",point{3.1,3.3}}
fmt.Println(n.Abs())
} // 输出,如果注释掉重写的部分输出会变成5
500
【Go中的多继承】
    Go支持多继承,方式就是在结构体中添加需要继承的类型
 package main

 import "fmt"

 //  多继承的方式和实现

 type Musician struct {
} type Soldier struct {
} type Doctor struct {
} type SupperMan struct {
Soldier
Doctor
Musician
} func (m *Musician) Sing() string {
return "i can singing"
}
func (s *Soldier) War() string {
return "i can use gun and kill enemy"
} func (d *Doctor) Heal() string {
return "i can heal your injure"
} func main() {
man := new(SupperMan)
fmt.Println(man.Sing())
fmt.Println(man.War())
fmt.Println(man.Heal())
} // 输出
An important answer
How much there are
The name of the thing