interface.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package services
  2. import (
  3. pkg "goiot-pkg/models"
  4. "reflect"
  5. )
  6. // 把结构体转换为Int
  7. func InterfaceToInt(data interface{}) int {
  8. if p, ok := data.(float64); ok {
  9. return int(p)
  10. }
  11. return 0
  12. }
  13. // 把结构体转换为Bool
  14. func InterfaceToBool(data interface{}) bool {
  15. if p, ok := data.(bool); ok {
  16. return p
  17. }
  18. return false
  19. }
  20. // 把结构体转换为Float32
  21. func InterfaceToFloat32(data interface{}) float32 {
  22. if p, ok := data.(float64); ok {
  23. return float32(p)
  24. }
  25. return 0.
  26. }
  27. // 把结构体转换为IntDic
  28. func InterfaceToIntDic(data interface{}) pkg.IntDic {
  29. value := reflect.ValueOf(data)
  30. if value.Kind() != reflect.Slice {
  31. return nil
  32. }
  33. var intDic = make(pkg.IntDic, 0)
  34. for i := 0; i < value.Len(); i++ {
  35. em := reflect.ValueOf(data).Index(i).Elem()
  36. if em.Kind() != reflect.Map {
  37. continue
  38. }
  39. intP := pkg.IntP{}
  40. for _, key := range em.MapKeys() {
  41. if p, ok := em.MapIndex(key).Interface().(string); ok {
  42. intP.Key = p
  43. } else if p, ok := em.MapIndex(key).Interface().(float64); ok {
  44. intP.Value = int(p)
  45. }
  46. }
  47. intDic = append(intDic, intP)
  48. }
  49. return intDic
  50. }
  51. // 把结构体转换为BoolDic
  52. func InterfaceToBoolDic(data interface{}) pkg.BoolDic {
  53. value := reflect.ValueOf(data)
  54. if value.Kind() != reflect.Slice {
  55. return nil
  56. }
  57. var boolDic = make(pkg.BoolDic, 0)
  58. for i := 0; i < value.Len(); i++ {
  59. em := reflect.ValueOf(data).Index(i).Elem()
  60. if em.Kind() != reflect.Map {
  61. continue
  62. }
  63. boolP := pkg.BoolP{}
  64. for _, key := range em.MapKeys() {
  65. if p, ok := em.MapIndex(key).Interface().(string); ok {
  66. boolP.Key = p
  67. } else if p, ok := em.MapIndex(key).Interface().(bool); ok {
  68. boolP.Value = p
  69. }
  70. }
  71. boolDic = append(boolDic, boolP)
  72. }
  73. return boolDic
  74. }
  75. // 把结构体转换为StringDic
  76. func InterfaceToStringDic(data interface{}) pkg.StringDic {
  77. value := reflect.ValueOf(data)
  78. if value.Kind() != reflect.Slice {
  79. return nil
  80. }
  81. var stringDic = make(pkg.StringDic, 0)
  82. for i := 0; i < value.Len(); i++ {
  83. em := reflect.ValueOf(data).Index(i).Elem()
  84. if em.Kind() != reflect.Map {
  85. continue
  86. }
  87. stringP := pkg.StringP{}
  88. for _, key := range em.MapKeys() {
  89. if p, ok := em.MapIndex(key).Interface().(string); ok {
  90. stringP.Key = p
  91. } else if p, ok := em.MapIndex(key).Interface().(string); ok {
  92. stringP.Value = p
  93. }
  94. }
  95. stringDic = append(stringDic, stringP)
  96. }
  97. return stringDic
  98. }