Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "errors"
- "fmt"
- "os"
- "reflect"
- "strconv"
- "strings"
- )
- type Point struct {
- X uint64
- Y string
- Z int32
- }
- func ToStuct(row string, value interface{}) error {
- return toStruct(row, reflect.ValueOf(value).Elem())
- }
- func ToCSV(value interface{}) (string, error) {
- return toCSV(reflect.ValueOf(value).Elem())
- }
- func toStruct(row string, v reflect.Value) error {
- lexems := strings.Split(row, ",")
- if len(lexems) != v.NumField() {
- return errors.New("invalid amount of fields")
- }
- for i := 0; i < v.NumField(); i++ {
- fx := v.Field(i)
- switch fx.Kind() {
- case reflect.String:
- s, _ := strconv.Unquote(lexems[i])
- fx.SetString(s)
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- s, _ := strconv.ParseUint(lexems[i], 10, 64)
- fx.SetUint(s)
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- s, _ := strconv.ParseInt(lexems[i], 10, 64)
- fx.SetInt(s)
- }
- }
- return nil
- }
- func toCSV(v reflect.Value) (string, error) {
- str := strings.Builder{}
- for i := 0; i < v.NumField(); i++ {
- fx := v.Field(i)
- switch fx.Kind() {
- case reflect.String:
- s, _ := strconv.Unquote(strconv.Quote(fx.String()))
- str.WriteString(s)
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- str.WriteString(strconv.FormatUint(fx.Uint(), 10))
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- str.WriteString(strconv.FormatInt(fx.Int(), 10))
- }
- if i != v.NumField()-1 {
- str.WriteString(", ")
- }
- }
- return str.String(), nil
- }
- func main() {
- p := new(Point)
- err := ToStuct("1,\"hello\",112", p)
- if err != nil {
- fmt.Println(err)
- os.Exit(1)
- }
- fmt.Println(*p)
- res, err := ToCSV(p)
- if err != nil {
- fmt.Println(err)
- os.Exit(1)
- }
- fmt.Println(res)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement