赞
踩
太忙,太累,不啰嗦,干起来
golang继承没有关键字,直接内置需要继承的类型,非常类似组合,但是没有属性名
package main import ( "fmt" ) //Animal animal type Animal struct { Name string Age byte } //Cat cat type Cat struct { //直接内置需要继承的类型 无属性名 注意与组合的区别 Animal Sound string } func main() { //创建 //方式一 cat0 := Cat{} cat0.Animal.Name = "cat-0" cat0.Animal.Age = 2 cat0.Sound = "mi-ao-" fmt.Println("cat0", cat0) //方式二 cat1 := Cat{} cat1.Name = "cat-1" cat1.Age = 3 cat1.Sound = "mi--" fmt.Println("cat1", cat1) //方式三 animal := Animal{ Name: "cat-2", Age: 10, } cat2 := Cat{ Animal: animal, Sound: "miao~", } fmt.Println("cat2", cat2) //方式四 cat3 := Cat{ Animal: Animal{ Name: "cat-3", Age: 12, }, Sound: "miao", } fmt.Println("cat3", cat3) //mixture of field:value and value initializers //嗯,来个反例,定义时属性要么属性名对应,要么顺序对应,不可混乱 mixture /* cat4 := Cat { Animal{ Name: "cat", Age: 12, }, Sound: "miao", } */ }
子类型与父类型有相同属性或方法时遵循就近原则
package main import ( "fmt" ) //Animal animal type Animal struct { Name string Age byte } //Show show func (a *Animal) Show() { fmt.Printf(" animal name = %v age = %d \n", a.Name, a.Age) } //SayHi say func (a *Animal) SayHi() { fmt.Printf(" hi, %v \n", a.Name) } //Cat cat type Cat struct { Animal Name string Sound string } //Show show func (c *Cat) Show() { fmt.Printf("cat name = %v age = %d sound = %v \n", c.Name, c.Age, c.Sound) } //Biology 生物 type Biology struct { Name string Age byte } //Dog dog type Dog struct { Biology Animal Age byte Sound string } func main() { cat := Cat{ Animal: Animal{ Name: "cat", Age: 3, }, Sound: "mimiao", } //子结构体与父结构体 有同名属性时遵循就近原则 fmt.Println(cat) cat.Show() cat.Animal.Show() cat.SayHi() fmt.Println("-------") cat.Name = "cat-0" cat.Show() cat.Animal.Show() fmt.Println("-------") cat.Animal.Name = "cat-1" cat.Show() cat.Animal.Show() cat.SayHi() //允许多重继承,但仍旧不推荐多重继承 dog := Dog{} //多重继承时,继承的父类型存在同名字段且子类型无此同名属性时,必须指定父类型来定义对应属性 // dog.Name = "dog" dog.Animal.Name = "animal-dog" dog.Biology.Name = "biology-dog" fmt.Println("dog", dog) //若多夫类型存在同名属性且子类型有次同名属性时,仍旧遵循就近原则 dog.Age = 2 fmt.Println("dog - ", dog) }
基本类型也可以继承
package main import ( "fmt" "go_code/test/model" ) //SubInt sub type SubInt struct { int subName string } //SubModel model type SubModel struct { model.Model attribute string } func main() { //基本类型也可以被继承 subint := SubInt{12, "sub"} fmt.Printf("subint type %T , int = %d, subName = %v \n", subint, subint.int, subint.subName) //被继承的父类属性或方法 对 子类型 无论首字母大小写均可见,但仍旧受包的可见限制 subModel := SubModel{ Model: model.Model{ Name: "model", }, attribute: "ok", } fmt.Println(subModel) amodel := model.AModel{} amodel.Show() }
package model import "fmt" //Model test type Model struct { Name string size int } func (m *Model) printModel() string { return fmt.Sprintf("model name = %v , size = %d \n", m.Name, m.size) } type AModel struct { Model atrr string } func (a *AModel) Show() { fmt.Printf("amodel name = %v , size = %d, atrr = %v \n", a.Name, a.size, a.atrr) }
先这样吧
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。