Go 优雅判断 interface 是否为 nil

TimLiuDream · · 1637 次点击
```go IsNil reports whether its argument v is nil. The argument must be a chan, func, interface, map, pointer, or slice value; if it is not, IsNil panics. Note that IsNil is not always equivalent to a regular comparison with nil in Go. For example, if v was created by calling ValueOf with an uninitialized interface variable i, i==nil will be true but v.IsNil will panic as v will be the zero Value. func (reflect.Value).IsNil() bool ```
#1
更多评论
你这map和slice不是nil?这倒是让我长见识了,将空指针转为interface之后居然会被封装一层,导致nil的判断失效了。slice和map是独立的数据类型,不能只用Ptr ```go func IsNil(x interface{}) bool { if x == nil { return true } rv := reflect.ValueOf(x) switch rv.Kind() { case reflect.Ptr, reflect.Slice, reflect.Map, reflect.Chan, reflect.Func: return rv.IsNil() default: return false } } ```
#2
是的,你这个是没有毛病的。
#3