golang interface判断为空nil的实现代码


Posted in Golang onApril 24, 2021

要判断interface 空的问题,首先看下其底层实现。

interface 底层结构

根据 interface 是否包含有 method,底层实现上用两种 struct 来表示:iface 和 eface。eface表示不含 method 的 interface 结构,或者叫 empty interface。

对于 Golang 中的大部分数据类型都可以抽象出来 _type 结构,同时针对不同的类型还会有一些其他信息。

1.eface

type eface struct {
    _type *_type
    data  unsafe.Pointer
}
type _type struct {
    size       uintptr // type size
    ptrdata    uintptr // size of memory prefix holding all pointers
    hash       uint32  // hash of type; avoids computation in hash tables
    tflag      tflag   // extra type information flags
    align      uint8   // alignment of variable with this type
    fieldalign uint8   // alignment of struct field with this type
    kind       uint8   // enumeration for C
    alg        *typeAlg  // algorithm table
    gcdata    *byte    // garbage collection data
    str       nameOff  // string form
    ptrToThis typeOff  // type for pointer to this type, may be zero
}

2.iface

iface 表示 non-empty interface 的底层实现。相比于 empty interface,non-empty 要包含一些 method。method 的具体实现存放在 itab.fun 变量里。如果 interface 包含多个 method,这里只有一个 fun 变量怎么存呢?这个下面再细说。

type iface struct {
    tab  *itab
    data unsafe.Pointer
}
// layout of Itab known to compilers
// allocated in non-garbage-collected memory
// Needs to be in sync with
// ../cmd/compile/internal/gc/reflect.go:/^func.dumptypestructs.
type itab struct {
    inter  *interfacetype
    _type  *_type
    link   *itab
    bad    int32
    inhash int32      // has this itab been added to hash?
    fun    [1]uintptr // variable sized
}

概括起来,接口对象由接口表 (interface table) 指针和数据指针组成,或者说由动态类型和动态值组成。

struct Iface
{
    Itab* tab;
    void* data;
};
struct Itab
{
    InterfaceType* inter;
    Type* type;
    void (*fun[])(void);
};

接口表存储元数据信息,包括接口类型、动态类型,以及实现接口的方法指针。无论是反射还是通过接口调用方法,都会用到这些信息。

再来看下nil的定义。

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

也就是说,只有pointer, channel, func, interface, map, or slice 这些类型的值才可以是nil.

如何判定interface里面的动态值是否空

对于一个接口的零值就是它的类型和值的部分都是nil。

一个接口值基于它的动态类型被描述为空或非空。

例如,

var w io.Writer

一般情况下,通过使用w==nil或者w!=nil来判读接口值是否为空,只是判断了动态类型,而没有判断动态值。

例如,下面的例子。

package main
import ("fmt")
func main(){
       var a interface{} = nil // tab = nil, data = nil
       var b interface{} = (*int)(nil) // tab 包含 *int 类型信息, data = nil
       fmt.Println(a==nil)
       fmt.Println(b==nil)
}

output:

true

false

上面代码中,接口b的动态类型为*int, 而动态值为nil,直接使用等于号无法判断。

所以不能直接通过与nil比较的方式判断动态值是否为空。

那如何判断动态值是否为空?

可以借助反射来判断。

func IsNil(i interface{}) bool {
    defer func() {
        recover()
    }()
    vi := reflect.ValueOf(i)
    return vi.IsNil()
}

其中,IsNil定义如下:

func (v Value) IsNil() bool

参数v必须是chan, func, interface, map, pointer, or slice,否则会panic。

如果调用IsNil的不是一个指针,会出现异常,需要捕获异常。

或者修改成这样:

func IsNil(i interface{}) bool {
    vi := reflect.ValueOf(i)
    if vi.Kind() == reflect.Ptr {
        return vi.IsNil()
    }
    return false
}

总结

一个接口包括动态类型和动态值。

如果一个接口的动态类型和动态值都为空,则这个接口为空的。

补充:golang返回值为interface{}的类型判断

看标题就知道,这是一个很简单的问题,就一个函数的事,但是,今天一同学golang的几个人中,已经不止一个人问我了,在这里我就说一下,也希望对不清楚的娃有些许帮助,大神别喷,飘过就行了。

大家知道,golang对于不确定返回值可以用interface{}代替,这确实很方便,但是也带来了问题,那就是如何判断返回值是什么类型的?其实可以用反射也就是reflect来判断,通过函数

reflect.TypeOf()

即返回类型!

以上为个人经验,希望能给大家一个参考,也希望大家多多支持三水点靠木。如有错误或未考虑完全的地方,望不吝赐教。

Golang 相关文章推荐
Golang 空map和未初始化map的注意事项说明
Apr 29 Golang
Go标准容器之Ring的使用说明
May 05 Golang
Go 自定义package包设置与导入操作
May 06 Golang
Go语言实现Snowflake雪花算法
Jun 08 Golang
Go语言空白表示符_的实例用法
Jul 04 Golang
手把手教你导入Go语言第三方库
Aug 04 Golang
go使用Gin框架利用阿里云实现短信验证码功能
Aug 04 Golang
Go语言安装并操作redis的go-redis库
Apr 14 Golang
golang的文件创建及读写操作
Apr 14 Golang
Golang 对es的操作实例
Apr 20 Golang
GO中sync包自由控制并发示例详解
Aug 05 Golang
golang判断key是否在map中的代码
Apr 24 #Golang
Go语言操作数据库及其常规操作的示例代码
Apr 21 #Golang
为什么不建议在go项目中使用init()
Apr 12 #Golang
Golang二维切片初始化的实现
Apr 08 #Golang
go语言map与string的相互转换的实现
Apr 07 #Golang
一文读懂go中semaphore(信号量)源码
Apr 03 #Golang
Go Gin实现文件上传下载的示例代码
Apr 02 #Golang
You might like
JavaScript实现滚动栏效果的方法
2015/04/27 PHP
PHP实现全角字符转为半角方法汇总
2015/07/09 PHP
PHP二维数组去重实例分析
2016/11/18 PHP
php+mysql+ajax实现单表多字段多关键词查询的方法
2017/04/15 PHP
tp5实现微信小程序多图片上传到服务器功能
2018/07/16 PHP
Javascript 面向对象 继承
2010/05/13 Javascript
JavaScript实现twitter puddles算法实例
2014/12/06 Javascript
微信小程序 数据封装,参数传值等经验分享
2017/01/09 Javascript
jQuery实现弹窗居中效果类似alert()
2017/02/27 Javascript
使用vue制作FullPage页面滚动效果
2017/08/21 Javascript
javascript获取图片的top N主色值方法详解
2018/01/26 Javascript
JavaScript树的深度优先遍历和广度优先遍历算法示例
2018/07/30 Javascript
javascript中UMD规范的代码推演
2018/08/29 Javascript
Vue中使用clipboard实现复制功能
2018/09/05 Javascript
JS实现指定区域的全屏显示功能示例
2019/04/25 Javascript
微信小程序自定义可滑动顶部TabBar选项卡实现页面切换功能示例
2019/05/14 Javascript
layui实现tab的添加拒绝重复的方法
2019/09/04 Javascript
JavaScript canvas动画实现时钟效果
2020/02/10 Javascript
python2.7删除文件夹和删除文件代码实例
2013/12/18 Python
整理Python最基本的操作字典的方法
2015/04/24 Python
简单总结Python中序列与字典的相同和不同之处
2016/01/19 Python
numpy找出array中的最大值,最小值实例
2018/04/03 Python
Python实现字符串的逆序 C++字符串逆序算法
2020/05/28 Python
Python解析并读取PDF文件内容的方法
2018/05/08 Python
python 脚本生成随机 字母 + 数字密码功能
2018/05/26 Python
彻底理解Python中的yield关键字
2019/04/01 Python
python 列表、字典和集合的添加和删除操作
2019/12/16 Python
五分钟带你搞懂python 迭代器与生成器
2020/08/30 Python
python的scipy.stats模块中正态分布常用函数总结
2021/02/19 Python
基础的CSS3弹性盒Flexbox布局使用实例
2016/04/08 HTML / CSS
CSS3 border-radius圆角的实现方法及用法详解
2020/09/14 HTML / CSS
四年的大学生生活自我评价
2013/12/09 职场文书
医院护士的求职信范文
2013/12/26 职场文书
2014年汽车销售工作总结
2014/12/01 职场文书
优秀高中学生评语
2014/12/30 职场文书
学生会干部任命书
2015/09/21 职场文书