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二维切片初始化的实现
Apr 08 Golang
golang中切片copy复制和等号复制的区别介绍
Apr 27 Golang
golang中的空slice案例
Apr 27 Golang
golang 实现时间戳和时间的转化
May 07 Golang
Golang 实现获取当前函数名称和文件行号等操作
May 08 Golang
Golang生成Excel文档的方法步骤
Jun 09 Golang
go web 预防跨站脚本的实现方式
Jun 11 Golang
Go语言并发编程 sync.Once
Oct 16 Golang
Go语言基础切片的创建及初始化示例详解
Nov 17 Golang
Golang ort 中的sortInts 方法
Apr 24 Golang
Go语言测试库testify使用学习
Jul 23 Golang
Go语言编译原理之变量捕获
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
各种战术和打法的原创者
2020/03/04 星际争霸
Windows下的PHP安装文件线程安全和非线程安全的区别
2014/04/23 PHP
PHP中的socket_read和socket_recv区别详解
2015/02/09 PHP
基于PHP的加载类操作以及其他两种魔术方法的应用实例
2017/08/28 PHP
PHP清除缓存的几种方法总结
2017/09/12 PHP
tp5(thinkPHP5)框架连接数据库的方法示例
2018/12/24 PHP
laravel-admin 管理平台获取当前登陆用户信息的例子
2019/10/08 PHP
JavaScript将相对地址转换为绝对地址示例代码
2013/07/19 Javascript
javascript中打印当前的时间实现思路及代码
2013/12/18 Javascript
JavaScript调用ajax获取文本文件内容实现代码
2014/03/28 Javascript
jQuery中 prop() attr()使用详解
2015/05/19 Javascript
在Html中使用Requirejs进行模块化开发实例详解
2016/04/15 Javascript
使用RequireJS库加载JavaScript模块的实例教程
2016/06/06 Javascript
JavaScript实现审核流程状态的动态显示进度条
2017/03/15 Javascript
Vue完整项目构建(进阶篇)
2018/02/10 Javascript
js 解析 JSON 数据简单示例
2020/04/21 Javascript
python发送邮件示例(支持中文邮件标题)
2014/02/16 Python
Python提示[Errno 32]Broken pipe导致线程crash错误解决方法
2014/11/19 Python
对python的输出和输出格式详解
2018/12/08 Python
Django获取该数据的上一条和下一条方法
2019/08/12 Python
Python Pandas数据分析工具用法实例
2020/11/05 Python
python中turtle库的简单使用教程
2020/11/11 Python
西班牙自行车和跑步商店:Alltricks
2018/07/07 全球购物
JSP和EJB可以共享HttpSession么?EJB里面可以改变session里面的内容
2013/06/05 面试题
本科毕业生的求职信范文
2013/11/20 职场文书
预备党员入党思想汇报
2014/01/04 职场文书
岳父生日宴会答谢词
2014/01/13 职场文书
GMP办公室主任岗位职责
2014/03/14 职场文书
应届毕业生求职信范文
2014/07/07 职场文书
工作总结与自我评价
2014/09/18 职场文书
2014业务员年终工作总结
2014/12/09 职场文书
2015最新婚礼司仪主持词
2015/06/30 职场文书
升学宴祝酒词
2015/08/11 职场文书
2016拓展训练心得体会范文
2016/01/12 职场文书
个人工作总结怎么写?
2019/04/09 职场文书
Python常遇到的错误和异常
2021/11/02 Python