strings.go 909 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package utils
  2. import (
  3. "encoding/json"
  4. "strconv"
  5. )
  6. // S 字符串类型转换
  7. type S string
  8. func (s S) String() string {
  9. return string(s)
  10. }
  11. // Bytes 转换为[]byte
  12. func (s S) Bytes() []byte {
  13. return []byte(s)
  14. }
  15. // Int64 转换为int64
  16. func (s S) Int64() int64 {
  17. i, err := strconv.ParseInt(s.String(), 10, 64)
  18. if err != nil {
  19. return 0
  20. }
  21. return i
  22. }
  23. // Int 转换为int
  24. func (s S) Int() int {
  25. return int(s.Int64())
  26. }
  27. // Uint 转换为uint
  28. func (s S) Uint() uint {
  29. return uint(s.Uint64())
  30. }
  31. // Uint64 转换为uint64
  32. func (s S) Uint64() uint64 {
  33. i, err := strconv.ParseUint(s.String(), 10, 64)
  34. if err != nil {
  35. return 0
  36. }
  37. return i
  38. }
  39. // Float64 转换为float64
  40. func (s S) Float64() float64 {
  41. f, err := strconv.ParseFloat(s.String(), 64)
  42. if err != nil {
  43. return 0
  44. }
  45. return f
  46. }
  47. // ToJSON 转换为JSON
  48. func (s S) ToJSON(v interface{}) error {
  49. return json.Unmarshal(s.Bytes(), v)
  50. }