Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "errors"
  5. "fmt"
  6. "os"
  7. "reflect"
  8. "strconv"
  9. "strings"
  10. )
  11.  
  12. type Point struct {
  13. X uint64
  14. Y string
  15. Z int32
  16. }
  17.  
  18. func ToStuct(row string, value interface{}) error {
  19. return toStruct(row, reflect.ValueOf(value).Elem())
  20. }
  21.  
  22. func ToCSV(value interface{}) (string, error) {
  23. return toCSV(reflect.ValueOf(value).Elem())
  24. }
  25.  
  26. func toStruct(row string, v reflect.Value) error {
  27. lexems := strings.Split(row, ",")
  28.  
  29. if len(lexems) != v.NumField() {
  30. return errors.New("invalid amount of fields")
  31. }
  32.  
  33. for i := 0; i < v.NumField(); i++ {
  34. fx := v.Field(i)
  35. switch fx.Kind() {
  36. case reflect.String:
  37. s, _ := strconv.Unquote(lexems[i])
  38. fx.SetString(s)
  39. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  40. s, _ := strconv.ParseUint(lexems[i], 10, 64)
  41. fx.SetUint(s)
  42. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  43. s, _ := strconv.ParseInt(lexems[i], 10, 64)
  44. fx.SetInt(s)
  45. }
  46. }
  47.  
  48. return nil
  49. }
  50.  
  51. func toCSV(v reflect.Value) (string, error) {
  52. str := strings.Builder{}
  53.  
  54. for i := 0; i < v.NumField(); i++ {
  55. fx := v.Field(i)
  56. switch fx.Kind() {
  57. case reflect.String:
  58. s, _ := strconv.Unquote(strconv.Quote(fx.String()))
  59. str.WriteString(s)
  60. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  61. str.WriteString(strconv.FormatUint(fx.Uint(), 10))
  62. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  63. str.WriteString(strconv.FormatInt(fx.Int(), 10))
  64. }
  65. if i != v.NumField()-1 {
  66. str.WriteString(", ")
  67. }
  68. }
  69.  
  70. return str.String(), nil
  71. }
  72.  
  73. func main() {
  74. p := new(Point)
  75. err := ToStuct("1,\"hello\",112", p)
  76. if err != nil {
  77. fmt.Println(err)
  78. os.Exit(1)
  79. }
  80.  
  81. fmt.Println(*p)
  82.  
  83. res, err := ToCSV(p)
  84. if err != nil {
  85. fmt.Println(err)
  86. os.Exit(1)
  87. }
  88.  
  89. fmt.Println(res)
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement