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

在Go语言中,判断一个结构体实例是否为空通常指的是判断该实例的所有字段是否都是零值。零值是指一个变量未被显式赋值时的默认值,对于不同的数据类型,零值是不同的,例如,数值类型为0,布尔类型为false,字符串类型为空字符串""。 以下是几种判断结构体是否为空的方法: 1. 遍历结构体的所有字段,逐一判断每个字段的值是否为零值。这种方法虽然准确,但在字段较多的情况下比较繁琐。 2. 利用反射(reflection)包中的API来判断结构体是否为空。可以使用`reflect.DeepEqual`函数来判断一个结构体实例是否等于零值实例。这种方法编写起来相对简单,但需要注意反射的性能开销可能较大。 3. 对于简单的结构体,可以通过逐个字段进行比较的方式来判断,尤其是当结构体中包含非基本类型字段时,反射可能不是最佳选择。 示例代码(使用反射判断结构体是否为空): ```go package main import ( "fmt" "reflect" ) type MyStruct struct { Field1 string Field2 int Field3 bool } func main() { var myStruct MyStruct fmt.Println(isEmptyStruct(myStruct)) // 输出: true myStruct = MyStruct{ Field1: "hello", Field2: 100, Field3: true, } fmt.Println(isEmptyStruct(myStruct)) // 输出: false } func isEmptyStruct(s interface{}) bool { // 判断传入的值是否是nil指针 if s == nil { return true } // 通过反射获取值的类型 val := reflect.ValueOf(s) // 判断是否是一个结构体 if val.Kind() == reflect.Struct { // 遍历结构体的所有字段 for i := 0; i < val.NumField(); i++ { // 获取字段的值 fieldVal := val.Field(i) // 如果字段的值不是零值,则返回false if !fieldVal.IsZero() { return false } } // 所有字段都是零值,返回true return true } return false } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值