内容简介:比如《Go语言实战》中的一个例子:如何判断类型是否实现了某个接口?对一个接口赋值的时候,会拷贝类型信息和该类型的方法集。只要这个类型的方法集中包括这个接口的所有方法,那么它就是实现了这个接口,才能够赋值给这个接口。
比如《Go语言实战》中的一个例子:
// compile error // cannot use u (type user) as type notifier in argument to sendNotification: // user does not implement notifier (notify
package main
import "fmt"
type user struct {
name string
email string
}
type notifier interface {
notify()
}
func (u *user) notify() {
fmt.Printf("sending user email to %s<%s>\n",
u.name,
u.email)
}
func sendNotification(n notifier) {
n.notify()
}
func main() {
u := user{
name: "stormzhu",
email: "abc@qq.com",
}
sendNotification(u)
}
// compile error
// cannot use u (type user) as type notifier in argument to sendNotification:
// user does not implement notifier (notify method has pointer receiver)
如何判断类型是否实现了某个接口?
- 接口的定义
type iface struct {
tab *itab // 类型信息
data unsafe.Pointer //实际对象指针
}
type itab struct {
inter *interfacetype // 接口类型
_type *_type // 实际对象类型
fun [1]uintptr // 实际对象方法地址
}
对一个接口赋值的时候,会拷贝类型信息和该类型的方法集。只要这个类型的方法集中包括这个接口的所有方法,那么它就是实现了这个接口,才能够赋值给这个接口。
- 方法集
-
类型
T的方法集包含所有 receiverT方法。 -
类型
*T的方法集包含所有 receiverT+*T方法。 -
匿名嵌入
S,类型T的方法集包含所有 receiverT+S方法。 -
匿名嵌入
*S,类型T的方法集包含所有 receiverT+S+*S方法。 -
匿名嵌入
S或*S,类型*T的方法集包含所有 receiverT+*T+S+*S方法。
总结:
-
T和*T不是一个类型,他们的方法集不同 -
类型
*T的方法集包含所有 receiverT+*T方法,类型T的方法集只包含所有 receiverT方法。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- golang中接口赋值与方法集
- golang接口的使用:给实现类中属性赋值
- 少说话多写代码之Python学习023——赋值语句的用户02(链式赋值、增量赋值)
- 理解Golang多重赋值
- ES6 解构赋值
- 【ES6复习】解构赋值
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Four
Scott Galloway / Portfolio / 2017-10-3 / USD 28.00
NEW YORK TIMES BESTSELLER USA TODAY BESTSELLER Amazon, Apple, Facebook, and Google are the four most influential companies on the planet. Just about everyone thinks they know how they got there.......一起来看看 《The Four》 这本书的介绍吧!
CSS 压缩/解压工具
在线压缩/解压 CSS 代码
SHA 加密
SHA 加密工具