接口的定义与实现

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()
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值