package mainimport "fmt"// Animal 声明一个接口type Animal interface {eat()getName() stringgetColor() string}// Cat 定义结构体type Cat struct {name stringcolor string}//Cat 必须实现animal的所有函数接口,否则无法关联func (cat *Cat) getName() string {return cat.name}func (cat *Cat) getColor() string {return cat.color}func (cat *Cat) eat() {fmt.Println("今天吃了小鱼")}//Dog 定义结构体type Dog struct {name stringcolor string}//Dog 必须实现animal的所有函数接口,否则无法关联func (dog *Dog) getName() string {return dog.name}func (dog *Dog) getColor() string {return dog.color}func (dog *Dog) eat() {fmt.Println("今天吃了骨头")}func printAnimal(animal Animal) {fmt.Println(animal.getColor(), animal.getName())animal.eat()}func main() {var animal Animal = &Cat{"小猫", "橘色"}printAnimal(animal)printAnimal(&Dog{"小狗", "白色"})}
嵌套interface
package maintype Animal interface {MoverEater}type Mover interface {move()}type Eater interface {eat()}type Cat struct {}func (c *Cat) move() {}func (c *Cat) eat() {}func main() {var a Mover;a= &Cat{}a.move()}
空接口
package mainimport "fmt"//空接口可以接受任何类型的数据func aa(a interface{}){fmt.Println(a)}func main() {aa(1)aa(make(map[string]string))aa(make(map[string]interface{}))aa(make([]interface{},0))}
