63 lines
981 B
Go
63 lines
981 B
Go
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)
|
|
}
|