/
string_converter.go
112 lines (109 loc) · 2.7 KB
/
string_converter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/*
* @Author: Daniel TAN
* @Description:
* @Date: 2021-08-06 10:11:31
* @LastEditTime: 2021-08-26 10:53:30
* @LastEditors: Daniel TAN
* @FilePath: /fr-price-common-pkg/core/utils/string_converter.go
*/
package utils
import (
"encoding/json"
"fmt"
"reflect"
"strconv"
)
// StringConverter
/*
@word the word need to be converted
@destVal the target value need to convert to
stringConverter will convert to destVal according to
the type of destVal
*/
func StringConverter(word string, destVal *reflect.Value) error {
switch destVal.Type().Kind() {
case reflect.Int64:
paramVal, err := strconv.ParseInt(word, 10, 64)
if err != nil {
return err
}
destVal.Set(reflect.ValueOf(paramVal))
case reflect.Int32:
paramVal, err := strconv.ParseInt(word, 10, 32)
if err != nil {
return err
}
destVal.Set(reflect.ValueOf(int32(paramVal)))
case reflect.Int16:
paramVal, err := strconv.ParseInt(word, 10, 16)
if err != nil {
return err
}
destVal.Set(reflect.ValueOf(int16(paramVal)))
case reflect.Int:
paramVal, err := strconv.Atoi(word)
if err != nil {
return err
}
destVal.Set(reflect.ValueOf(paramVal))
case reflect.Uint:
paramVal, err := strconv.Atoi(word)
if err != nil {
return err
}
destVal.Set(reflect.ValueOf(uint(paramVal)))
case reflect.Uint64:
paramVal, err := strconv.ParseUint(word, 10, 64)
if err != nil {
return err
}
destVal.Set(reflect.ValueOf(paramVal))
case reflect.Uint32:
paramVal, err := strconv.ParseUint(word, 10, 32)
if err != nil {
return err
}
destVal.Set(reflect.ValueOf(int32(paramVal)))
case reflect.Uint16:
paramVal, err := strconv.ParseUint(word, 10, 16)
if err != nil {
return err
}
destVal.Set(reflect.ValueOf(int16(paramVal)))
case reflect.Float32:
paramVal, err := strconv.ParseFloat(word, 32)
if err != nil {
return err
}
destVal.Set(reflect.ValueOf(float32(paramVal)))
case reflect.Float64:
paramVal, err := strconv.ParseFloat(word, 64)
if err != nil {
return err
}
destVal.Set(reflect.ValueOf(paramVal))
case reflect.Bool:
paramVal, _ := strconv.ParseBool(word)
destVal.Set(reflect.ValueOf(paramVal))
case reflect.String:
destVal.Set(reflect.ValueOf(word))
case reflect.Interface:
destVal.Set(reflect.ValueOf(word))
case reflect.Struct:
targetVal := reflect.New(destVal.Type()).Interface()
if err := json.Unmarshal([]byte(word), targetVal); err != nil {
return err
}
destVal.Set(reflect.ValueOf(targetVal).Elem())
case reflect.Ptr:
targetVal := reflect.New(destVal.Type().Elem())
dest := targetVal.Elem()
if err := StringConverter(word, &dest); err != nil {
return err
}
destVal.Set(targetVal)
default:
return fmt.Errorf("unsupported type")
}
return nil
}