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

不羁岁月 提交于 2019-12-01 17:16:16
Peter Noyes

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!