继承
package main
import "fmt"
type Animal struct {
name string
age int
}
func (a Animal) eat() {
fmt.Println("a eat")
}
func (a Animal) sleep() {
fmt.Println("a sleep")
}
type Dog struct {
Animal
test string
}
type Cat struct {
animal Animal
color string
}
func main() {
// 匿名继承,需要按顺序来
dog := Dog{
Animal{
name: "小狗",
age: 1,
},
"测试",
}
dog.eat()
dog.sleep()
// 具名继承,因为eat和sleep方法是挂载在Animal上,所以具名继承需要从animal调用
cat := Cat{animal: Animal{name: "大黄", age: 1}, color: "white"}
cat.animal.eat()
cat.animal.sleep()
}