Technique/Tips一个小技术
多态的要素
package mainimport ("fmt")//多态的要素//有一个父类(有接口) ,interface接口的本质是一个指针type AnimalIF interface {Sleep()GetColor() string //获取动物的颜色GetType() string //获取动物的种类}//具体的类,子类实现了父类的所有接口方法type Cat struct {color string //猫的颜色}//子类cat完全实现一个接口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 //猫的颜色}//子类dog完全实现一个接口func (this *Dog) Sleep() {fmt.Println("Cat 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("kind=", animal.GetType())}func main() {//父类类型的变量(指针)指向(引用)子类的具体数据变量/* var animal AnimalIF //接口的数据类型,父类指针animal = &Cat("Green")animal.Sleep() //调用cat的sleep方法,多态现象animal = &Dog("Yellow")animal.Sleep() //调用dog的sleep方法,多态现象*/cat := Cat{"Green"}dog := Dog{"Yellow"}showAnimal(&cat)showAnimal(&dog)}
interface{}
可以引用任意的数据类型
