Go 语言接口
Go 语言提供了另外一种数据类型即接口,它把所有的具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了这个接口。
特点:
1. interface 是一种类型
interface 是一种具有一组方法的类型,这些方法定义了 interface 的行为。go 允许不带任何方法的 interface ,这种类型的 interface 叫 empty interface
2. interface 变量存储的是实现者的值
interface 的重要用途就体现在函数参数中,如果有多种类型实现了某个 interface,这些类型的值都可以直接使用 interface 的变量存储。
3. 空的 interface
interface{} 是一个空的 interface 类型,根据前文的定义:一个类型如果实现了一个 interface 的所有方法就说该类型实现了这个 interface,空的 interface 没有方法,所以可以认为所有的类型都实现了 interface{}。如果定义一个函数参数是 interface{} 类型,这个函数应该可以接受任何类型作为它的参数
package main
import "fmt"
type Animal interface {
Eat(food string)
Call() string
}
type Sheep struct {
food string
}
// 实现接口方法
func (sheep *Sheep) Eat(food string){
sheep.food = food
}
// 实现接口方法
func (sheep Sheep) Call() string{
fmt.Println("Sheep has eat: ", sheep.food)
return "mm"
}
func main() {
var sheep Animal
// 两种写法一样
// sheep = new(Sheep)
sheep = &Sheep{food:""}
sheep.Eat("grass")
sing := sheep.Call()
fmt.Print("Sheep song: ", sing)
}
结果: