empty_value.go 837 B

123456789101112131415161718192021222324252627282930313233
  1. package missinggo
  2. import "reflect"
  3. func IsZeroValue(i interface{}) bool {
  4. return IsEmptyValue(reflect.ValueOf(i))
  5. }
  6. // Returns whether the value represents the empty value for its type. Used for
  7. // example to determine if complex types satisfy the common "omitempty" tag
  8. // option for marshalling. Taken from
  9. // http://stackoverflow.com/a/23555352/149482.
  10. func IsEmptyValue(v reflect.Value) bool {
  11. switch v.Kind() {
  12. case reflect.Func, reflect.Map, reflect.Slice:
  13. return v.IsNil()
  14. case reflect.Array:
  15. z := true
  16. for i := 0; i < v.Len(); i++ {
  17. z = z && IsEmptyValue(v.Index(i))
  18. }
  19. return z
  20. case reflect.Struct:
  21. z := true
  22. for i := 0; i < v.NumField(); i++ {
  23. z = z && IsEmptyValue(v.Field(i))
  24. }
  25. return z
  26. }
  27. // Compare other types directly:
  28. z := reflect.Zero(v.Type())
  29. return v.Interface() == z.Interface()
  30. }