《Go语言实战》学习笔记——接口

第5章 Go语言的类型系统

5.4 接口

接口是用来定义行为的类型。这些被定义的行为不由接口直接实现,而是通过方法由用户定义的类型实现。如果用户定义的类型实现了某个接口类型声明的一组方法,那么这个用户定义的类型的值就可以给这个接口类型的赋值,从而实现多态(是指代码可以根据类型的具体实现采取不同行为的能力)。

package main

import "fmt"

type notifier interface {
	notify()
}

type user struct {
	name string
	email string
}

func (u *user) notify()  {
	fmt.Printf("Sending user email to %s<%s>\n",
		u.name,
		u.email)
}

func sendNotifycation(n notifier)  {
	n.notify()
}

func main(){
	u := user{"Bill", "bill@email.com"}
	//Cannot use 'u' (type user) as the type notifier Type does not implement 'notifier' as the 'notify' method has a pointer receiver
	//sendNotifycation(u)
	sendNotifycation(&u)
}

output: Sending user email to Bill<bill@email.com>

方法集定义了接口的接收规则,即定义方法时使用的接收者类型决定了这个方法是关联到值还是指针。例如上面的u,是user类型的值,只能包含值接收者声明的方法,而user的notify方法是指针接收者声明的方法。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值