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
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
}