type.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package reflectutils
  2. import "reflect"
  3. // GroupTypeKind 将反射的Kind值进行聚集
  4. func GroupTypeKind(t reflect.Type) reflect.Kind {
  5. kind := t.Kind()
  6. switch {
  7. case kind >= reflect.Int && kind <= reflect.Int64:
  8. return reflect.Int64
  9. case kind >= reflect.Uint && kind <= reflect.Uint64:
  10. return reflect.Uint64
  11. case kind >= reflect.Float32 && kind <= reflect.Float64:
  12. return reflect.Float64
  13. default:
  14. return kind
  15. }
  16. }
  17. func PointerTypeElem(t reflect.Type) reflect.Type {
  18. elem := t
  19. if t.Kind() == reflect.Ptr {
  20. elem = t.Elem()
  21. }
  22. return elem
  23. }
  24. func SliceTypeElem(t reflect.Type) reflect.Type {
  25. elem := t
  26. if t.Kind() == reflect.Slice {
  27. elem = t.Elem()
  28. }
  29. return elem
  30. }
  31. func IsSliceTypeOf(t reflect.Type, elementKind reflect.Kind) bool {
  32. return t.Kind() == reflect.Slice && t.Elem().Kind() == elementKind
  33. }
  34. func IsTypeInteger(t reflect.Type) bool {
  35. return t.Kind() >= reflect.Int && t.Kind() <= reflect.Int64
  36. }
  37. func IsTypeUnsignedInteger(t reflect.Type) bool {
  38. return t.Kind() >= reflect.Uint && t.Kind() <= reflect.Uint64
  39. }
  40. func IsTypeFloat(t reflect.Type) bool {
  41. return t.Kind() >= reflect.Float32 && t.Kind() <= reflect.Float64
  42. }
  43. func IsTypeStructPointer(t reflect.Type) bool {
  44. return t.Kind() == reflect.Pointer && t.Elem().Kind() == reflect.Struct
  45. }
  46. func IsTypeStructOrStructPointer(t reflect.Type) bool {
  47. return t.Kind() == reflect.Struct || IsTypeStructPointer(t)
  48. }
  49. func IsTypeStructSliceOrStructSlicePointer(t reflect.Type) bool {
  50. return IsSliceTypeOf(t, reflect.Struct) || (t.Kind() == reflect.Pointer && IsSliceTypeOf(t.Elem(), reflect.Struct))
  51. }
  52. func IsTypeTime(t reflect.Type) bool {
  53. return t.Kind() == reflect.Struct && t.String() == "time.Time"
  54. }
  55. func IsTypeTimePointer(t reflect.Type) bool {
  56. return t.Kind() == reflect.Pointer && IsTypeTime(t.Elem())
  57. }