package main import ( "fmt" ) type Dog struct { Name string Age int } func (d *Dog)bite() { fmt.Printf("%s要咬你了 ", d.Name) } type PoliceDog struct { //一行代码拥有父类的全部成员(属性+方法) Dog //扩展出新的属性 Skill string } //扩展出新的方法 func (pd *PoliceDog)DoPoliceJob(){ fmt.Printf("%s正在执行警务工作:%s ",pd.Name,pd.Skill) } //重写父类方法(overwrite) func (d *PoliceDog)bite() { fmt.Printf("%s要把你大卸八块了 ", d.Name) } func main21() { pd := PoliceDog{} //通过子类对象访问父类成员 pd.Name = "战狼" pd.bite() //访问子类独有成员 pd.Skill = "徒手接RPG" pd.DoPoliceJob() //访问子类复写了的父类方法 pd.bite() } func main() { //pd := PoliceDog{} //pd := PoliceDog{Dog{Name: "战狼"}, "徒手接炮弹"} //pd := PoliceDog{Dog: Dog{Name:"战狼"}} //pd := PoliceDog{Skill: "徒手接炮弹"} //pd := new(PoliceDog) pd := NewPoliceDog("战狼", 40, "徒手接炮弹") fmt.Println(pd.Name,pd.Age,pd.Skill) pd.bite() pd.DoPoliceJob() } func NewPoliceDog(name string,age int,skill string) *PoliceDog { //pd:=new(PoliceDog) //pd.Name=name //pd.Age=age //pd.Skill=skill pd := &PoliceDog{Dog{name, age}, skill} return pd }