您的位置 首页 golang

学习Golang第17天 – 结构体内嵌模拟类的继承

 package main

import "fmt"

// 可飞行的
type Flying struct{}

func (f *Flying) Fly() {
   fmt.Println("can fly")
}

// 可行走的
type Walkable struct{}

func (f *Walkable) Walk() {
   fmt.Println("can walk")
}

// 人类
type Human struct {
   Walkable // 人类能行走
}

// 鸟类
type Bird struct {
   Walkable // 鸟类能行走
   Flying   // 鸟类能飞行
}

func main() {

   // 实例化鸟类
   b := new(Bird)
   fmt.Println("Bird: ")
   b.Fly()
   b.Walk()

   // 实例化人类
   h := new(Human)
   fmt.Println("Human: ")
   h.Walk()

}  


运行结果:

 Bird:
can fly
can walk
Human:
can walk  

文章来源:智云一二三科技

文章标题:学习Golang第17天 – 结构体内嵌模拟类的继承

文章地址:https://www.zhihuclub.com/98199.shtml

关于作者: 智云科技

热门文章

网站地图