How to get zero value of a field type

后端 未结 3 680
孤街浪徒
孤街浪徒 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:41

    I couldn't post a comment, but the accepted answer panics if you provide a struct with any unexported fields. The trick I've found is to check if the field can be set - essentially ignoring any unexported fields.

    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++ {
                if v.Field(i).CanSet() {
                    z = z && isZero(v.Field(i))
                }
            }
            return z
        case reflect.Ptr:
            return isZero(reflect.Indirect(v))
        }
        // Compare other types directly:
        z := reflect.Zero(v.Type())
        result := v.Interface() == z.Interface()
    
        return result
    }
    

提交回复
热议问题