详解Golang中interface{}的注意事项
作者:阿兵云原生 发布时间:2024-05-09 09:30:59
interface {} 可以用于模拟多态
xdm 咱们写一个简单的例子,就举动物的例子
写一个 Animal 的接口,类似于 java 里面的抽象类 ,Animal 的接口 中有 2 个方案待实现
写一个 Cat 来继承 Animal , 实现 Eat 方法和 Drink 方法
动物都有吃和喝的行为,小猫吃的行为是吃鱼,小猫的喝的行为是喝可乐
最后在主函数中,使用父类的指针,来指向子类的实例化的一个子类地址
type Animal interface {
Eat(string) string
Drink(string) string
}
type Cat struct{}
func (c *Cat) Eat(food string) string {
if food != "fish" {
return "i dislike"
} else {
return "i like"
}
}
func (c *Cat) Drink(drink string) string {
if drink == "coke" {
return "i love"
}else{
return "abandon"
}
}
func main(){
var a Animal = &Cat{}
fmt.Println(a.Eat("fish"))
fmt.Println(a.Drink("water"))
}
看到上述代码,会不会有这样的疑问,命名是 &Cat{}
是取地址的,为什么 var a Animal
不写成指针呢?
这里需要注意,Animal 本身是 接口类型,自身就是一个指针
运行上述代码查看效果
# go run main.go
i like
abandon
没有毛病,小猫眯爱吃鱼,不爱喝水
interface{} 需要注意空和非空的情况
什么叫做空的 interface{} , 什么又叫做非空的 interface{} 呢?
咱们还是用上面的例子, 添加一个 testInterface 函数
,来实践一下
func testInterface() Animal {
var c *Cat
return c
}
func main() {
test := testInterface()
if test == nil {
fmt.Println("test is nil")
} else {
fmt.Println("test is not nil")
}
}
可以猜猜看,上面这个小案例会输出什么结果
理论上来看,testInterface
函数中我们只是创建了一个 Cat 指针,并没有赋值,因此默认是一个零值,因此会是一个 nil,那么 return 的时候,应该也是 return nil 才对吧,因此按照代码的逻辑来说应该是输出 test is nil
执行上述代码后,查看结果
# go run main.go
test is not nil
看到上面的结果,是不是觉得很奇怪,和自己的预期不一致
没关系,之前的文章我们说到过,觉得一个技术点奇怪,不是我们所期望的效果,原因是我们对其原理不够了解,不够熟悉
现在先来回答一下上面的问题
空接口:意思是没有方法的接口,interface{} 源码中表示为 eface 结构体
非空接口:表示有包含方法的接口 , interface{} 源码中表示为 iface 结构体
暂时先来直接介绍源码中的结构体
iface结构体,非空
type iface struct {
tab *itab
data unsafe.Pointer
}
type itab struct {
inter *interfacetype
_type *_type
link *itab
hash uint32 // copy of _type.hash. Used for type switches.
bad bool // type does not implement interface
inhash bool // has this itab been added to hash?
unused [2]byte
fun [1]uintptr // variable sized
}
tab
指的是具体的类型信息,是一个 itab 结构,结构中成员如上,这里面包含的都是借口的关键信息,例如 hash 值 ,函数指针,等等,后续详细剖析 interface{} 原理的时候再统一说
data
具体的数据信息
eface结构体
type eface struct {
_type *_type
data unsafe.Pointer
}
type _type struct {
size uintptr // 表示的是 类型的大小
ptrdata uintptr // 值的是前缀指针的内存大小
hash uint32 // 计算数据的 hash 值
tflag tflag
align uint8 // 进行内存对齐的
fieldalign uint8
kind uint8
alg *typeAlg
gcdata *byte
str nameOff
ptrToThis typeOff
}
_type
类型信息,和上面的 非空接口类似 , 这个_type 类型决定下面的 data 字段如何去解释数据
data
具体的数据信息
看到这里,细心的 xdm 是不是就可以看出来,我们上面写的 Animal 接口,其实是一个非空接口,因为里面有包含方法,所以他的底层是一个 iface 结构体 ,非空接口
那么初始化的一个空指针 c ,实际上是 iface 结构体里面的 data 字段为空而已,数据为空而已,但是 iface 这个结构体自己不是空的,所以上述代码走的逻辑是 test is not nil
这里顺带说一下,golang 中,还有哪些数据结构是和 nil 比较是否为零值,这个点我们也可以看看源码
// nil is a predeclared identifier representing the zero value for a
// pointer, channel, func, interface, map, or slice type.
var nil Type // Type must be a pointer, channel, func, interface, map, or slice type
源码中有说到,可以对 指针,通道,函数,接口,map,切片类型使用 nil
好了,本次就到这里,知识点要用起来才有价值
来源:https://segmentfault.com/a/1190000043506591
猜你喜欢
- 本文讲述了线程安全及Python中的GIL。分享给大家供大家参考,具体如下:摘要什么是线程安全? 为什么python会使用GIL的机制?在多
- 前言:很多人都在使用mysql数据库,但是很少有人能够说出来整个sql语句的执行过程是怎样的,如果不了解执行过程的话,就很难进行sql语句的
- 基本使用import unittestclass Testcase(unittest.TestCase): @classmeth
- 0. 学习目标线性表在计算机中的表示可以采用多种方法,采用不同存储方法的线性表也有着不同的名称和特点。线性表有两种基本的存储结构:顺序存储结
- 作为python和机器学习的初学者,目睹了AI玩游戏的各种风骚操作,心里也是跃跃欲试。然后发现微信跳一跳很符合需求,因为它不需要处理连续画面
- 引言在刚入门python时,模块化编程、模块、类库等术语常常并不容易理清。尤其是Modules(模块)和Packages(包),在impor
- logging模块介绍Python的logging模块提供了通用的日志系统,熟练使用logging模块可以方便开发者开发第三方模块或者是自己
- 1.ES6 解构[...arr, ...array]不改原数组值,生成新的数组。 2.遍历添加array.forEac
- 刚开始接触Python,首先要解决的就是Python开发环境的搭建。目前比较好用的Python开发工具是PyCharm,他有社区办和专业版两
- 原文:http://www.htmldog.com/guides/htmlintermediate/badtags/十六 有害的标签 Bad
- 实例如下所示:from tensorflow.python import pywrap_tensorflowcheckpoint_path
- 标题:按某字段合并字符串之一(简单合并)描述:将如下形式的数据按id字段合并value字段。id val
- 一、前言我打开4399小游戏网,点开了一个不知名的游戏,唔,做寿司的,有材料在一边,客人过来后说出他们的要求,你按照菜单做好端给他便好~要怎
- <?php function getDerivativeByFormulaAndXDATA($formula, $x_data){ $
- 1.计算变量缺失率df=pd.read_csv('titanic_train.csv')def missing_cal(df
- function createHashDir($sign) { $md5 = md5($sign); if(!is_dir(MB_CACHE
- USE masterDECLARE @spid intDECLARE CUR CURSORFOR SELECT spid FROM sysp
- namedtuple是Python中存储数据类型,比较常见的数据类型还有有list和tuple数据类型。
- 什么是聚类算法聚类是一种机器学习技术,它涉及到数据点的分组。给定一组数据点,我们可以使用聚类算法将每个数据点划分为一个特定的组。理论上,同一
- 下载mysql for mac: https://downloads.mysql.com/archives/community/