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

前端 未结 4 1375
我寻月下人不归
我寻月下人不归 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.

提交回复
热议问题