go 结构体继承,及其方法
package main
import (
"fmt"
)
type Animal struct {
Name string
Sex string
}
func (a *Animal)Talk(){
fmt.Printf("Animal is talk, i'm %s\n", a.Name)
}
func (a *Animal)Eat(){
fmt.Println("dog Animal is eat")
}
type PuruAnimal struct{}
type Dog struct{
Feet string
//Animal // 值类型
*Animal // 指针类型
*PuruAnimal // 指针类型
}
func (p *PuruAnimal)Talk(){
fmt.Println("puru dongwu is talking\n")
}
func (p *PuruAnimal)Walk(){
fmt.Println("puru dongwu is walking\n")
}
func (d *Dog)Talk(){
fmt.Printf("dog %s is talking\n",d.Name)
}
func (d *Dog)Eat(){
fmt.Printf("dog %s is eat\n",d.Name)
}
func main(){
var d *Dog = &Dog{
Feet:"four feet",
Animal:&Animal{
Name:"旺财",
Sex:"公",
},
PuruAnimal:&PuruAnimal{},
}
d.Eat()
d.Talk()
d.Name = "小黑"
d.Sex ="公"
d.Eat()
d.Talk()
d.Animal.Talk()
d.PuruAnimal.Talk()
d.Talk()
d.Walk()
}
输出:
dog 旺财 is eat
dog 旺财 is talking
dog 小黑 is eat
dog 小黑 is talking
Animal is talk, i'm 小黑
puru dongwu is talking
dog 小黑 is talking
puru dongwu is walking
写入自己的博客中才能记得长久