Go結構體內嵌模擬類的繼承

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()

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章