Understanding of interfaces in go and the realization of polymorphism

What kind of duck model? The explanation of the duck model usually uses a very interesting example. Whether a thing is a duck or not depends on its ability. If it swims like a duck and screams like a duck, then it can be a duck.

package main

import "fmt"

type Duck interface {
    
    
	Quack()
	DuckGo()
}

type Chicken struct {
    
    
	name string
}

func (c Chicken) Quack() {
    
    
	fmt.Println("嘎嘎")
}

func (c Chicken) DuckGo() {
    
    
	fmt.Println("大摇大摆的走")
}

func DuckDo(d Duck){
    
    
	d.DuckGo()
	d.Quack()
}

func main() {
    
    
	a:=Chicken{
    
    "ming"}
	DuckDo(a)

}

As long as the chicken implements the DuckGo and Quack methods of the duck (all the methods of the duck must be implemented by the chicken, the chicken can be regarded as a duck), then the chicken can be regarded as a duck. According to the understanding in C++, Duck interface can be regarded as an abstract parent class with pure virtual functions, and chicken is a subclass of this parent class, and these two interfaces must be implemented

Guess you like

Origin blog.csdn.net/Fengfgg/article/details/113616533