福哥答案2020-11-10:
reflect.ValueOf(接口变量).IsNil(),用这个即可判断。对于值类型,会panic。两种方法如下:
1.异常判断:recover捕获。
2.类型判断:reflect.ValueOf(接口变量).Kind()获取类型。
golang代码如下:
package main import ( "fmt" "reflect" ) type Person struct { Name string } func (*Person) GetName() { } type ITester interface { GetName() } func main() { var i interface{} = nil //空值 fmt.Println("空值") fmt.Println("==判断:", i == nil) fmt.Println("异常判断:", InterfaceIsNil1(i)) fmt.Println("类型判断:", InterfaceIsNil2(i)) fmt.Println("-----------") i = []int(nil) //切片 fmt.Println("切片") fmt.Println("==判断:", i == nil) fmt.Println("异常判断:", InterfaceIsNil1(i)) fmt.Println("类型判断:", InterfaceIsNil2(i)) fmt.Println("-----------") i = map[int]int(nil) //映射 fmt.Println("映射") fmt.Println("==判断:", i == nil) fmt.Println("异常判断:", InterfaceIsNil1(i)) fmt.Println("类型判断:", InterfaceIsNil2(i)) fmt.Println("-----------") i = chan int(nil) //通道 fmt.Println("通道") fmt.Println("==判断:", i == nil) fmt.Println("异常判断:", InterfaceIsNil1(i)) fmt.Println("类型判断:", InterfaceIsNil2(i)) fmt.Println("-----------") i = (func())(nil) //函数 fmt.Println("函数") fmt.Println("==判断:", i == nil) fmt.Println("异常判断:", InterfaceIsNil1(i)) fmt.Println("类型判断:", InterfaceIsNil2(i)) fmt.Println("-----------") i = (*int)(nil) //指针 fmt.Println("指针") fmt.Println("==判断:", i == nil) fmt.Println("异常判断:", InterfaceIsNil1(i)) fmt.Println("类型判断:", InterfaceIsNil2(i)) } //异常判断 func InterfaceIsNil1(i interface{}) bool { ret := i == nil if !ret { //需要进一步做判断 defer func() { recover() }() ret = reflect.ValueOf(i).IsNil() //值类型做异常判断,会panic的 } return ret } //类型判断 func InterfaceIsNil2(i interface{}) bool { ret := i == nil if !ret { //需要进一步做判断 vi := reflect.ValueOf(i) kind := reflect.ValueOf(i).Kind() if kind == reflect.Slice || kind == reflect.Map || kind == reflect.Chan || kind == reflect.Interface || kind == reflect.Func || kind == reflect.Ptr { return vi.IsNil() } } return ret }
执行结果如下: