接口的定义与实现

1.接口的定义与实现
接收者是指针*T时,接口实例必须是指针
接收者是值 T时,接口实力可以是指针也可以是值
接口的定义和类型转换与接收者的定义是关联的
2.
package main

import “fmt”

type Humaner interface {
//方法,只有声明没有实现,有别的类型(自定义类型)实现
sayhi()
}
type Student struct {
name string
id int
}
//student实现此方法
func (tmp *Student) sayhi(){
fmt.Printf(“student[%s,%d]\n”,tmp.name,tmp.id)
}
type Teacher struct {
addr string
group int
}
//Teacher实现此方法
func (tmp *Teacher) sayhi(){
fmt.Printf(“Teacher[%s,%d]\n”,tmp.addr,tmp.group)
}

type Mystr string

//student实现此方法
func (tmp *Mystr) sayhi(){
fmt.Printf(“Mystr[%s]\n”,*tmp)
}

func main() {
//定义接口类型的变量
var i Humaner
//只要实现了此接口方法的类型,那么这个类型的变量就可以给i赋值
s :=&Student{“mike”,111}
i=s //根据实例化选择自动匹配程序
i.sayhi()

t:=&Teacher{“55555”,15}
i=t
i.sayhi()

var str Mystr =“hello you”
i=&str
i.sayhi()
}
多态的表现
package main

import “fmt”

type Humaner interface {
//方法,只有声明没有实现,有别的类型(自定义类型)实现
sayhi()
}
type Student struct {
name string
id int
}
//student实现此方法
func (tmp *Student) sayhi(){
fmt.Printf(“student[%s,%d]\n”,tmp.name,tmp.id)
}
type Teacher struct {
addr string
group int
}
//Teacher实现此方法
func (tmp *Teacher) sayhi(){
fmt.Printf(“Teacher[%s,%d]\n”,tmp.addr,tmp.group)
}

type Mystr string

//student实现此方法
func (tmp *Mystr) sayhi(){
fmt.Printf(“Mystr[%s]\n”,*tmp)
}

func main() {
//定义接口类型的变量
var i Humaner
//只要实现了此接口方法的类型,那么这个类型的变量就可以给i赋值
s :=&Student{“mike”,111}
i=s
i.sayhi()

t:=&Teacher{“55555”,15}
i=t
i.sayhi()

var str Mystr =“hello you”
i=&str
i.sayhi()
}
//2.自定义一个普通函数,函数的参数为这个接口类型
//函数只有一个接口,可以有不同的表现,都是多态
func WhoSayHi(i Humaner) {
i.sayhi()
}
func main01() {
s :=&Student{“mike”,111}
t:=&Teacher{“55555”,15}
var str Mystr =“hello you”
//调用统一函数,不同表现,多态,各种形式
WhoSayHi(s)
WhoSayHi(t)
WhoSayHi(&str)

//创建一个切片
x:=make([]Humaner,3)
x[0]=s
x[1]=t
x[2]=&str
//第一个返回的下标,第二个返回下标所对应的值
for _,i :=range x{
i.sayhi()
}
}

猜你喜欢

转载自blog.csdn.net/C540743204/article/details/107463436