How to get zero value of a field type

后端 未结 3 681
孤街浪徒
孤街浪徒 2021-02-04 04:47

I have a struct containing many fields - I\'ve figured out how to extract the field name, value, and tag information using reflection. What I also want to do is to determine if

3条回答
  •  北海茫月
    2021-02-04 05:31

    For types that support the equality operation, you can just compare interface{} variables holding the zero value and field value. Something like this:

    v.Interface() == reflect.Zero(v.Type()).Interface()
    

    For functions, maps and slices though, this comparison will fail, so we still need to include some special casing. Further more, while arrays and structs are comparable, the comparison will fail if they contain non-comparable types. So you probably need something like:

    func isZero(v reflect.Value) bool {
        switch v.Kind() {
        case reflect.Func, reflect.Map, reflect.Slice:
            return v.IsNil()
        case reflect.Array:
            z := true
            for i := 0; i < v.Len(); i++ {
                z = z && isZero(v.Index(i))
            }
            return z
        case reflect.Struct:
            z := true
            for i := 0; i < v.NumField(); i++ {
                z = z && isZero(v.Field(i))
            }
            return z
        }
        // Compare other types directly:
        z := reflect.Zero(v.Type())
        return v.Interface() == z.Interface()
    }
    

提交回复
热议问题