Go笔记-继承

【Go中继承的实现】
    当一个匿名类型被内嵌在结构体中时,匿名类型的可见方法也同样被内嵌,这在效果上等同于外层类型 继承 了这些方法:将父类型放在子类型中来实现亚型
 1 package main
 2  
 3 import "fmt"
 4  
 5 type Point struct{
 6     x,y float64
 7 }
 8  
 9 type NamePoint struct{
10     name string
11     Point
12 }
13  
14 func(p *Point)Abs()float64{
15     return math.Sqrt(p.x*p.x + p.y*p.y)
16 }
17  
18 func main(){
19     n := &NamePoint{"gao",Point{3.1,3.3}}
20     fmt.Println(n.Abs())
21 }
22  
23 // 输出
24 5
    内嵌将一个已存在类型的字段和方法注入到了另一个类型里:匿名字段上的方法“晋升”成为了外层类型的方法。当然类型可以有只作用于本身实例而不作用于内嵌“父”类型上的方法,可以覆写方法(像字段一样):和内嵌类型方法具有同样名字的外层类型的方法会覆写内嵌类型对应的方法。
 1 package main
 2  
 3 import "fmt"
 4  
 5 type point struct{
 6     x,y float64
 7 }
 8  
 9 type NamePoint struct{
10     name string
11     point
12 }
13  
14 func(p *point)Abs()float64{
15     return math.Sqrt(p.x*p.x + p.y*p.y)
16 }
17  
18 // 重写
19 func(np *NamePoint)Abs()float64{
20     return np.point.Abs() * 100
21 }
22  
23 func main(){
24     n := &NamePoint{"gao",point{3.1,3.3}}
25     fmt.Println(n.Abs())
26 }
27  
28 // 输出,如果注释掉重写的部分输出会变成5
29 500
    
 
【Go中的多继承】
    Go支持多继承,方式就是在结构体中添加需要继承的类型
 1 package main
 2 
 3 import "fmt"
 4 
 5 //  多继承的方式和实现
 6 
 7 type Musician struct {
 8 }
 9 
10 type Soldier struct {
11 }
12 
13 type Doctor struct {
14 }
15 
16 type SupperMan struct {
17     Soldier
18     Doctor
19     Musician
20 }
21 
22 func (m *Musician) Sing() string {
23     return "i can singing"
24 }
25 func (s *Soldier) War() string {
26     return "i can use gun and kill enemy"
27 }
28 
29 func (d *Doctor) Heal() string {
30     return "i can heal your injure"
31 }
32 
33 func main() {
34     man := new(SupperMan)
35     fmt.Println(man.Sing())
36     fmt.Println(man.War())
37     fmt.Println(man.Heal())
38 }
39 
40 // 输出
41 An important answer
42 How much there are
43 The name of the thing
 
 
原文地址:https://www.cnblogs.com/ymkfnuiwgij/p/7912249.html