You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
1.0 KiB

  1. package util
  2. import "reflect"
  3. // IsNotEmpty returns true if the given value is not zero or empty.
  4. func IsNotEmpty(given interface{}) bool {
  5. return !IsEmpty(given)
  6. }
  7. // IsEmpty returns true if the given value has the zero value for its type.
  8. func IsEmpty(given interface{}) bool {
  9. g := reflect.ValueOf(given)
  10. if !g.IsValid() {
  11. return true
  12. }
  13. if g.Kind() == reflect.Ptr {
  14. g = g.Elem()
  15. }
  16. // Basically adapted from text/template.isTrue
  17. switch g.Kind() {
  18. case reflect.Array, reflect.Slice, reflect.Map, reflect.String:
  19. return g.Len() == 0
  20. case reflect.Bool:
  21. return !g.Bool()
  22. case reflect.Complex64, reflect.Complex128:
  23. return g.Complex() == 0
  24. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  25. return g.Int() == 0
  26. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  27. return g.Uint() == 0
  28. case reflect.Float32, reflect.Float64:
  29. return g.Float() == 0
  30. case reflect.Struct:
  31. return g.IsZero()
  32. default:
  33. return g.IsNil()
  34. }
  35. }