lxutils.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package lxUtil
  2. import (
  3. "reflect"
  4. "strings"
  5. )
  6. // IsZeroOfUnderlyingType 判断是否零值对象, 考虑到了model是指针的情况
  7. func IsZeroOfUnderlyingType(model interface{}) bool {
  8. // ref: https://www.coder.work/article/200965
  9. rawType := reflect.TypeOf(model)
  10. if rawType.Kind() == reflect.Ptr { // 指针
  11. rawType = rawType.Elem()
  12. return reflect.DeepEqual(model, reflect.New(rawType).Interface())
  13. }
  14. return reflect.DeepEqual(model, reflect.Zero(rawType).Interface())
  15. }
  16. // ToSlice 为什么不能被 cast.ToSlice 替代?
  17. func ToSlice1(v interface{}) []interface{} {
  18. var out []interface{}
  19. rv := reflect.ValueOf(v)
  20. if rv.Kind() == reflect.Slice {
  21. for i := 0; i < rv.Len(); i++ {
  22. out = append(out, rv.Index(i).Interface())
  23. }
  24. } else {
  25. out = append(out, v)
  26. }
  27. return out
  28. }
  29. // FieldToColumn inAmt -> in_amt 结构体属性转成库表字段
  30. func FieldToColumn(s string) string {
  31. return CamelCaseToSnakeCase(s)
  32. }
  33. // CamelCaseToSnakeCase 小驼峰转下划线
  34. // mesLine -> mes_line
  35. // mesLine-lineCode-lineDesc -> mes_line-line_code-line_desc
  36. func CamelCaseToSnakeCase(s string) string {
  37. if s = strings.TrimSpace(s); s == "" {
  38. return ""
  39. }
  40. var (
  41. buf strings.Builder
  42. prevUpper, nextUpper, nextNumber bool
  43. curUpper = s[0] <= 'Z' && s[0] >= 'A'
  44. )
  45. for i, r := range s[:len(s)-1] {
  46. nextUpper = 'A' <= s[i+1] && s[i+1] <= 'Z'
  47. nextNumber = '0' <= s[i+1] && s[i+1] <= '9'
  48. if curUpper {
  49. if prevUpper && (nextUpper || nextNumber) {
  50. buf.WriteRune(r + 32)
  51. } else {
  52. if i > 0 && s[i-1] != '_' && s[i+1] != '_' {
  53. buf.WriteByte('_')
  54. }
  55. buf.WriteRune(r + 32)
  56. }
  57. } else {
  58. buf.WriteRune(r)
  59. }
  60. prevUpper = curUpper
  61. curUpper = nextUpper
  62. }
  63. if curUpper {
  64. if !prevUpper && len(s) > 1 {
  65. buf.WriteByte('_')
  66. }
  67. buf.WriteByte(s[len(s)-1] + 32)
  68. } else {
  69. buf.WriteByte(s[len(s)-1])
  70. }
  71. return buf.String()
  72. }