How to know if a variable of arbitrary type is Zero in Golang?

前端 未结 4 1298
我寻月下人不归
我寻月下人不归 2021-01-18 01:35

Because not all types are comparable, e.g. a slice. So we can\'t do this

var v ArbitraryType
v == reflect.Zero(reflect.TypeOf(v)).Interface()
相关标签:
4条回答
  • 2021-01-18 02:11

    Both of the following give me reasonable results (probably because they're the same?)

    reflect.ValueOf(v) == reflect.Zero(reflect.TypeOf(v)))
    
    reflect.DeepEqual(reflect.ValueOf(v), reflect.Zero(reflect.TypeOf(v)))
    

    e.g. various integer 0 flavours and uninitialized structs are "zero"

    Sadly, empty strings and arrays are not. and nil gives an exception.
    You could special case these if you wanted.

    0 讨论(0)
  • 2021-01-18 02:12

    As Peter Noyes points out, you just need to make sure you're not comparing a type which isn't comparable. Luckily, this is very straightforward with the reflect package:

    func IsZero(v interface{}) (bool, error) {
        t := reflect.TypeOf(v)
        if !t.Comparable() {
            return false, fmt.Errorf("type is not comparable: %v", t)
        }
        return v == reflect.Zero(t).Interface(), nil
    }
    

    See an example use here.

    0 讨论(0)
  • 2021-01-18 02:12

    Go 1.13 introduced Value.IsZero method in reflect package. This is how you can check for zero value using it:

    if reflect.ValueOf(v).IsZero() {
        // v is zero, do something
    }
    

    Apart from basic types, it also works for Chan, Func, Array, Interface, Map, Ptr, Slice, UnsafePointer, and Struct.

    0 讨论(0)
  • 2021-01-18 02:20

    See this post:

    Golang: Reflection - How to get zero value of a field type

    Basically you need to have special cases for the non comparable types.

    0 讨论(0)
提交回复
热议问题