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

蹲街弑〆低调 提交于 2019-12-01 16:28:27

问题


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()

Edit - Solution reflect.DeepEqual

var v ArbitratyType
zero := reflect.Zero(reflect.TypeOf(v)).Interface()
isZero := reflect.DeepEqual(v, zero)

Go documentation about reflect.DeepEqual

DeepEqual tests for deep equality. It uses normal == equality where possible but will scan elements of arrays, slices, maps, and fields of structs.


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/33115946/how-to-know-if-a-variable-of-arbitrary-type-is-zero-in-golang

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