package main import "fmt" type Animal interface { Eat(food string) (shit string) GoDie() } type Fighter interface { Attack() (bloodloss int) Defend() } type Beast interface { //显示的继承Animal接口 Animal //隐式的继承Fighter接口 Attack() (bloodloss int) Defend() //独有的抽象方法 Run() } type Tiger struct { Name string Food string Shit string } func (t *Tiger)Eat(food string) (shit string){ fmt.Printf("本王%s正在吃%s ",t.Name,t.Food) return "虎翔" } func (t *Tiger)GoDie(){ fmt.Printf("本王%s驾鹤西归 ",t.Name) } func (t *Tiger)Attack() (bloodloss int){ fmt.Printf("本王%s发起攻击 ",t.Name) return 100 } func (t *Tiger)Defend(){ fmt.Printf("本王%s躺地上举起爪子,休想伤害本喵 ",t.Name) } func (t *Tiger)Run(){ fmt.Printf("本王%s在大地上奔跑 ",t.Name) } func main() { var animal Animal var fighter Fighter var beast Beast tiger := &Tiger{"辛巴", "一切会走动的活物", "虎翔"} animal = tiger fighter = tiger beast = tiger animal.GoDie() fighter.Attack() beast.Run() }
结果:
本王辛巴驾鹤西归 本王辛巴发起攻击 本王辛巴在大地上奔跑