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

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

提交回复
热议问题