接口应用
type sayer interface {
say()
}
type dog struct {
}
func (d dog) say() {
fmt.Println("汪汪汪")
}
type cat struct {
}
func (c cat) say() {
fmt.Println("喵喵喵")
}
func main() {
var x sayer
c := cat{}
x = c
x.say()
d := dog{}
x = d
x.say()
}
--结果---
喵喵喵
汪汪汪
接口嵌套
// Sayer 接口
type Sayer interface {
say()
}
// Mover 接口
type Mover interface {
move()
}
// 接口嵌套
type animal interface {
Sayer
Mover
}
type cat struct {
name string
}
func (c cat) say() {
fmt.Println("喵喵喵")
}
func (c cat) move() {
fmt.Println("猫会动")
}
func main() {
var x animal
x = cat{name: "花花"}
x.move()
x.say()
}
空接口
空接口是指没有定义任何方法的接口。因此任何类型都实现了空接口。
空接口类型的变量可以存储任意类型的变量。