package main
import "fmt"
// 接口是一系列方法的集合
type animal interface{
breathe()
walk()
}
// 需要实现interface的所有方法,否则会报错
type lion struct{
age int
}
// 指针变量和变量都可以实现这个方法
func (li lion) breathe(){
fmt.Println("lion breathes")
}
// 只有指针变量才能实现这个方法
func (li *lion) walk(){
fmt.Println("lion walk")
}
type dog struct {
age int
}
func (d dog) breathe() {
fmt.Println("Dog breathes")
}
func (d dog) walk() {
fmt.Println("Dog walk")
}
// interface作为一个函数参数传入
func callBreathe(a animal){
a.walk()
}
// interface断言:val := i.({type})
func print(a animal){
l,ok := a.(dog)
if ok{
fmt.Println(l)
}else {
fmt.Println("a is not of type lion")
}
}
func main(){
var a animal
// a = lion{age:15}会报错,因为存在指针变量指向这个类型
a = &lion{age :10}
a.breathe()
callBreathe(a)
b := dog{age: 30}
print(b)
}
运行结果:
lion breathes
lion walk
{30}