typeutil.go 995 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package typeutil
  2. import (
  3. "log"
  4. "strconv"
  5. )
  6. func ToBool(v interface{}) (rv bool) {
  7. switch v.(type) {
  8. case bool:
  9. rv = v.(bool)
  10. case string:
  11. str := v.(string)
  12. switch str {
  13. case "true":
  14. rv = true
  15. case "1":
  16. rv = true
  17. }
  18. case float64:
  19. if v.(float64) > 0 {
  20. rv = true
  21. }
  22. default:
  23. log.Println("Can't convert", v, "to bool")
  24. panic("Can't convert value")
  25. }
  26. return rv
  27. }
  28. func ToString(v interface{}) (rv string) {
  29. switch v.(type) {
  30. case string:
  31. rv = v.(string)
  32. case float64:
  33. rv = strconv.FormatFloat(v.(float64), 'f', -1, 64)
  34. default:
  35. log.Println("Can't convert", v, "to string")
  36. panic("Can't convert value")
  37. }
  38. return rv
  39. }
  40. func ToInt(v interface{}) (rv int) {
  41. switch v.(type) {
  42. case string:
  43. i, err := strconv.Atoi(v.(string))
  44. if err != nil {
  45. panic("Error converting weight to integer")
  46. }
  47. rv = i
  48. case float64:
  49. rv = int(v.(float64))
  50. default:
  51. log.Println("Can't convert", v, "to integer")
  52. panic("Can't convert value")
  53. }
  54. return rv
  55. }