golang interface判断为空nil
要判断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
}
总结
一个接口包括动态类型和动态值。
如果一个接口的动态类型和动态值都为空,则这个接口为空的。
参考
https://golang.org/src/builtin/builtin.go?h=var+nil+Type#L101
《Go学习笔记--雨痕》
http://legendtkl.com/2017/07/01/golang-interface-implement/
https://www.jianshu.com/p/97bfe8104e03
golang interface判断为空nil的更多相关文章
- go中interface空指针不为nil判断方法
interface空指针不为nil 当把一个空指针对象赋值给一个interface后,再判断!= nil就不再成立了 代码如下 package main import "fmt" ...
- Golang Interface 解析
转自 https://zhuanlan.zhihu.com/p/27652856 先看一段代码: 123456789101112 func (x interface{}) { if x == nil ...
- sql server case when 判断为空
代码如下 select distinct G.* ,(select BUSINESS_NAME from BusinessInfo where BusinessInfo.BUSINESS_BID=G. ...
- javascript判断非空
/* *判断非空 * */ function isEmpty(val){ if(val == null)return true; if(val == undefined || val == 'unde ...
- js判断为空Null与字符串为空简写方法
下面就是有关判断为空的简写方法. 代码如下: if (variable1 !== null || variable1 !== undefined || variable1 !== '') { v ...
- m_Orchestrate learning system---三十二、数据库字段判断为空时容易出现问题,如何从根本上解决这个问题
m_Orchestrate learning system---三十二.数据库字段判断为空时容易出现问题,如何从根本上解决这个问题 一.总结 一句话总结:字段禁止为空,设置默认值0即可 禁止 空 默认 ...
- Golang并行判断素数
## Golang多核判断素数方式 package main import ( "bufio" "fmt" "os" "runti ...
- mybatis传入0但判断为空
当是数字类型时,传入0会判断为空,当值为空,显示在页面上的将会是0:
- Java中判断非空对象.
Java中经常会遇到判断非空的时候. 有的时候判断了非空但是还是报空指针,为什么.? 判断的时候一般都会判断两次.类似于: Org o = new Org(); if ( o.getId()!=nul ...
随机推荐
- ansible暂停模块
pause 在playbook执行的过程中暂停一定时间或者提示用户进行某些操作 常用参数: minutes:暂停多少分钟 seconds:暂停多少秒 prompt:打印一串信息提示用户操作 示例: - ...
- CRM工具简介
pacemaker是高可用集群中的CRM(Cluster Resource Manager)资源管理层,他是一个服务,可以作为一个单独的服务启动,不过在如果使用corosync1.4中,我们可以设置c ...
- React-native-camera error with Expo: undefined is not an object (evaluating 'CameraManager.Aspect')
React-native-camera error with Expo: undefined is not an object (evaluating 'CameraManager.Aspect') ...
- PHP 设计模式系列 —— 工厂方法模式(Factory Method)(转)
1.模式定义 定义一个创建对象的接口,但是让子类去实例化具体类.工厂方法模式让类的实例化延迟到子类中. 2.问题引出 框架需要为多个应用提供标准化的架构模型,同时也要允许独立应用定义自己的域对象并对其 ...
- C#线程、前后台线程
C#线程.前后台线程 本文提供全流程,中文翻译. Chinar 坚持将简单的生活方式,带给世人!(拥有更好的阅读体验 -- 高分辨率用户请根据需求调整网页缩放比例) Chinar -- 心分享.心创新 ...
- css3的calc()
计算大小宽度距离的一个计算函数 使用方法 再括号中进行加减乘除的运算 例如: width : calc(100% - 75px) 注意 :符号左右两边要有空格
- NYOJ 6:喷水装置(一)(贪心)
6-喷水装置(一) 内存限制:64MB 时间限制:3000ms 特判: No 通过数:68 提交数:111 难度:3 题目描述: 现有一块草坪,长为20米,宽为2米,要在横中心线上放置半径为Ri的喷水 ...
- BFS模板
bool visit[maxn];///访问标记 ,,,,-,,-,}; ///向左上右下,左下,右上,右下,左上 ,,,-,-,,,-}; struct node { int r; int c; i ...
- Linux常用命令详解-目录文件操作命令
来源:https://www.linuxidc.com/Linux/2018-04/151801.htm 现实中,服务器(包含Linux,Unix,Windows Server)一般都摆放在机房里,因 ...
- 【BZOJ3894】文理分科
最小割劲啊 原题: 文理分科是一件很纠结的事情!(虽然看到这个题目的人肯定都没有纠 结过) 小P所在的班级要进行文理分科.他的班级可以用一个n*m的矩阵进行 描述,每个格子代表一个同学的座位.每位 ...