package main
import "fmt"
/**
type Hummaner interface{
SayHi()
}
1接口习惯以er结尾
2接口中只有方法声明,没有实现,没有数据字段
3接口可以嵌入其他接口,或嵌入其他结构中
多态的体现
**/
type Humaner interface {
//只声明,有别的类型实现
SayHi()
}
type Student struct {
name string
age int
}
func (s *Student) SayHi() {
fmt.Println("此学生叫", s.name)
}
type Teacher struct {
name string
age int
}
func (s *Teacher) SayHi() {
fmt.Println("此老师叫", s.name)
}
func HumanerSayHi(h Humaner) {
h.SayHi()
}
func main() {
//定义接口变量
var i Humaner
s := Student{"小王", 22}
i = &s
//只是实现了此接口的方法,就可以将这个类型的变量(接受者类型)赋值给i
i.SayHi()
t := Teacher{"老王", 44}
i = &t
i.SayHi()
//多态的体现
HumanerSayHi(&s)
HumanerSayHi(&t)
x := make([]Humaner, 2)
x[0] = &s
x[1] = &t
for _, i := range x {
i.SayHi()
}
}
4.7 go接口定义
猜你喜欢
转载自blog.csdn.net/h4241778/article/details/105318128
今日推荐
周排行