go语言接口的实现


接口可以很好的封装有同一类功能的方法

首先在具体实现里面定义自己的实现,这边定义了2个

type Cat struct{}

func (c *Cat) Call() {
	fmt.Println("miao,miao...")
}

func (c *Cat) Eat() {
	fmt.Println("fish")
}
///////
type Dog struct{}

func (d *Dog) Call() {
	fmt.Println("wang,wang...")
}

func (d *Dog) Eat() {
	fmt.Println("meat")
}

然后定义接口

type Animal interface {
	Call()
	Eat()
}

具体实现

func TestReflect(t *testing.T) {
	d := Dog{}
	d.Call()
	d.Eat()

	c := Cat{}
	c.Call()
	c.Eat()
}

输出内容:

wang,wang... meat miao,miao... fish   实际调用场景应该是这样的,会将多个实例放在字典映射里面,然后动态调用
func TestReflect(t *testing.T) {
	animalMap := map[string]Animal{}
	animalMap["cat"] = &Cat{}
	animalMap["dog"] = &Dog{}
	animalMap["cat"].Call()
	animalMap["cat"].Eat()
}
Go