1、接口的定义
import "fmt"
type Personer interface {
SayHello()
}
type Student struct {
}
func (stu *Student)SayHello() {
fmt.Println("老师好")
}
func main() {
//创建一个学生对象
var stu Student
//通过接口变量的方式来调用,必须都实现接口中声明的所有方法
var person Personer
person = &stu
person.SayHello()//此时person调用的是Student对象中的SayHello方法
}
执行结果:
老师好
2、多态
多态是指同一个接口,使用不同的实例而执行不同的操作
import "fmt"
type Personer interface {
SayHello()
}
type Student struct {
}
type Teacher struct {
}
func (stu *Student)SayHello() {
fmt.Println("老师好")
}
func (stu *Teacher)SayHello() {
fmt.Println("学生好")
}
func WhoSayHello(p Personer) {
p.SayHello()
}
func main() {
var stu Student
var tea Teacher
WhoSayHello(&stu)
WhoSayHello(&tea)
}
执行结果:
老师好
学生好