From 2e69f9483ab689aea7bb6ad24ef000b031a50435 Mon Sep 17 00:00:00 2001 From: wandoubaba Date: Fri, 15 Nov 2024 16:57:45 +0800 Subject: [PATCH] =?UTF-8?q?inherit=E5=92=8Cinterface?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bilibili/aceid/struct/inherit/test.go | 51 ++++++++++++++++++++ bilibili/aceid/struct/interface/test.go | 62 +++++++++++++++++++++++++ 2 files changed, 113 insertions(+) create mode 100644 bilibili/aceid/struct/inherit/test.go create mode 100644 bilibili/aceid/struct/interface/test.go diff --git a/bilibili/aceid/struct/inherit/test.go b/bilibili/aceid/struct/inherit/test.go new file mode 100644 index 0000000..6ee40db --- /dev/null +++ b/bilibili/aceid/struct/inherit/test.go @@ -0,0 +1,51 @@ +package main + +import "fmt" + +type Human struct { + name string + sex string +} + +func (this *Human) Eat() { + fmt.Println("Human.Eat()...") +} + +func (this *Human) Walk() { + fmt.Println("Human.Walk()...") +} + +type Superman struct { + Human + level int +} + +func (this *Superman) Eat() { + fmt.Println("Superman.Eat()...") +} + +func (this *Superman) Fly() { + fmt.Println("Superman.Fly()...") +} + +func (this *Superman) Show() { + fmt.Println("name = ", this.name) + fmt.Println("sex = ", this.sex) + fmt.Println("level = ", this.level) +} + +func main() { + h := Human{"zhang3", "female"} + h.Eat() + h.Walk() + + var s Superman + s.name = "li4" + s.sex = "male" + s.level = 96 + // s := Superman{Human{"li4", "female"}, 88} + s.Walk() // 父类方法(子类没有重载) + s.Eat() // 子类方法 + s.Fly() // 子类方法 + s.Show() +} diff --git a/bilibili/aceid/struct/interface/test.go b/bilibili/aceid/struct/interface/test.go new file mode 100644 index 0000000..09cde17 --- /dev/null +++ b/bilibili/aceid/struct/interface/test.go @@ -0,0 +1,62 @@ +package main + +import "fmt" + +// 本质是一个指针 +type AnimalIF interface { + Sleep() + GetColor() string // 获取颜色 + GetType() string // 获取种类 +} + +// 定义具体的类 +type Cat struct { + color string // 颜色 +} + +func (this *Cat) Sleep() { + fmt.Println("Cat is sleep") +} + +func (this *Cat) GetColor() string { + return this.color +} + +func (this *Cat) GetType() string { + return "Cat" +} + +type Dog struct { + color string +} + +func (this *Dog) Sleep() { + fmt.Println("Dog is sleep") +} + +func (this *Dog) GetColor() string { + return this.color +} + +func (this *Dog) GetType() string { + return "Dog" +} + +func showAnimal(animal AnimalIF) { + animal.Sleep() + fmt.Println("color = ", animal.GetColor()) + fmt.Println("type = ", animal.GetType()) +} + +func main() { + var animal AnimalIF // 接口数据类型(父类指针) + animal = &Cat{"green"} + animal.Sleep() + animal = &Dog{"yellow"} + animal.Sleep() + + cat := Cat{"gray"} + dog := Dog{"black"} + showAnimal(&cat) + showAnimal(&dog) +}