interface.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package utils
  2. import (
  3. "reflect"
  4. "strconv"
  5. )
  6. func InterfaceToMap(data interface{}) map[string]interface{} {
  7. t := reflect.TypeOf(data)
  8. v := reflect.ValueOf(data)
  9. if v.Kind() != reflect.Struct {
  10. return nil
  11. }
  12. fieldNum := t.NumField()
  13. result := make(map[string]interface{})
  14. for i := 0; i < fieldNum; i++ {
  15. kind := t.Field(i).Type.Kind()
  16. if kind == reflect.Array || kind == reflect.Slice || kind == reflect.Struct {
  17. continue
  18. }
  19. result[t.Field(i).Name] = v.Field(i).Interface()
  20. }
  21. return result
  22. }
  23. // InterfaceToInt 把结构体转换为Int
  24. func InterfaceToInt(data interface{}) int {
  25. if p, ok := data.(string); ok {
  26. intVal, _ := strconv.Atoi(p)
  27. return intVal
  28. } else if p, ok := data.(int64); ok {
  29. return int(p)
  30. } else if p, ok := data.(float64); ok {
  31. return int(p)
  32. }
  33. return 0
  34. }
  35. // InterfaceToFloat64 把结构体转换为Float
  36. func InterfaceToFloat64(data interface{}) float64 {
  37. if p, ok := data.(string); ok {
  38. floatVal, _ := strconv.ParseFloat(p, 10)
  39. return floatVal
  40. } else if p, ok := data.(int64); ok {
  41. return float64(p)
  42. } else if p, ok := data.(float64); ok {
  43. return p
  44. }
  45. return 0.0
  46. }