Go语言之组合(十九)

  • 面向对象特性:继承
  • 组合实现

目录结构

    ├── demo
    │    └── demo.go
    ├── go.mod
    └── main.go

demo.go文件

        package demo
        import "fmt"
        
        type Animal struct {
            Colour string
        }
        type Dog struct {//dog 结构体包含了Animal结构体的属性和方法
            Animal       //组合
            ID int
            Name string
            Age int
        }
        func (d *Dog)Run()  {
            fmt.Println("ID:",d.ID,"DOG is running")
        }
        func (a *Animal)Eat()  {
            fmt.Println("yu yu yu yu")
        }

main.go文件

    package main
    
    import (
        "./demo"
        "fmt"
    )
    func main()  {
        dog := new(demo.Dog)
        dog.ID = 1
        dog.Name = "GG"
        dog.Age = 5
        dog.Colour = "red"   //继承了Animal的属性
        dog.Eat()            //继承了Animal的方法       yu yu yu yu
        fmt.Println("\r")
        fmt.Println(dog)     //&{{red} 1 GG 5}            
    }

关注友儿不迷路

Last modification:September 23rd, 2020 at 03:07 pm
如果觉得我的文章对你有用,请随意赞赏