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中切片copy复制和等号复制的区别介绍
Apr 27 Golang
golang import自定义包方式
Apr 29 Golang
golang 实现Location跳转方式
May 02 Golang
浅谈golang 中time.After释放的问题
May 05 Golang
Golang 获取文件md5校验的方法以及效率对比
May 08 Golang
go xorm框架的使用
May 22 Golang
golang 语言中错误处理机制
Aug 30 Golang
Golang中channel的原理解读(推荐)
Oct 16 Golang
如何利用golang运用mysql数据库
Mar 13 Golang
Go语言实现一个简单的并发聊天室的项目实战
Mar 18 Golang
实现GO语言对数组切片去重
Apr 20 Golang
GoFrame基于性能测试得知grpool使用场景
Jun 21 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
数字转英文
2006/12/06 PHP
php使用百度天气接口示例
2014/04/22 PHP
详解强大的jQuery选择器之基本选择器、层次选择器
2012/02/07 Javascript
JavaScript实现班级随机点名小应用需求的具体分析
2014/05/12 Javascript
Node.js中对通用模块的封装方法
2014/06/06 Javascript
JavaScript中统计Textarea字数并提示还能输入的字符
2014/06/10 Javascript
理解javascript中的回调函数(callback)
2014/09/02 Javascript
javascript实现复制与粘贴操作实例
2014/10/16 Javascript
javascript表单验证大全
2015/08/12 Javascript
Node学习记录之cluster模块
2017/05/31 Javascript
angularjs数组判断是否含有某个元素的实例
2018/02/27 Javascript
使用electron制作满屏心特效的示例代码
2018/11/27 Javascript
element ui table(表格)实现点击一行展开功能
2018/12/04 Javascript
微信小程序MUI导航栏透明渐变功能示例(通过改变opacity实现)
2019/01/24 Javascript
Angular CLI 使用教程指南参考小结
2019/04/10 Javascript
python 实时遍历日志文件
2016/04/12 Python
Python pygorithm模块用法示例【常见算法测试】
2018/08/16 Python
基于腾讯云服务器部署微信小程序后台服务(Python+Django)
2019/05/08 Python
Python进程间通信Queue消息队列用法分析
2019/05/22 Python
Python检查 云备份进程是否正常运行代码实例
2019/08/22 Python
python ffmpeg任意提取视频帧的方法
2020/02/21 Python
python GUI库图形界面开发之PyQt5切换按钮控件QPushButton详细使用方法与实例
2020/02/28 Python
python判断正负数方式
2020/06/03 Python
浅谈Django前端后端值传递问题
2020/07/15 Python
python 动态绘制爱心的示例
2020/09/27 Python
整理HTML5中表单的常用属性及新属性
2016/02/19 HTML / CSS
美国基督教约会网站:ChristianCafe.com
2020/02/04 全球购物
基层干部十八大感言
2014/01/19 职场文书
运动会跳远加油稿
2014/02/20 职场文书
团支书竞选演讲稿
2014/04/28 职场文书
读书伴我成长演讲稿
2014/05/07 职场文书
导师推荐信范文
2014/05/09 职场文书
民政局标准版离婚协议书
2014/12/01 职场文书
一年级小学生评语大全
2014/12/25 职场文书
2016秋季校长开学典礼致辞
2015/11/26 职场文书
php png失真的原因及解决办法
2021/11/17 PHP