-
Notifications
You must be signed in to change notification settings - Fork 0
/
cast_string.go
64 lines (54 loc) · 1.47 KB
/
cast_string.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
package pick
import (
"encoding/json"
"strconv"
)
func (c DefaultCaster) AsString(input any) (string, error) {
switch origin := input.(type) {
case int:
return strconv.FormatInt(int64(origin), 10), nil
case int8:
return strconv.FormatInt(int64(origin), 10), nil
case int16:
return strconv.FormatInt(int64(origin), 10), nil
case int32:
return strconv.FormatInt(int64(origin), 10), nil
case int64:
return strconv.FormatInt(origin, 10), nil
case uint:
return strconv.FormatUint(uint64(origin), 10), nil
case uint8:
return strconv.FormatUint(uint64(origin), 10), nil
case uint16:
return strconv.FormatUint(uint64(origin), 10), nil
case uint32:
return strconv.FormatUint(uint64(origin), 10), nil
case uint64:
return strconv.FormatUint(origin, 10), nil
case float32:
return strconv.FormatFloat(float64(origin), 'G', 5, 32), nil
case float64:
return strconv.FormatFloat(origin, 'G', 5, 64), nil
case string:
return origin, nil
case json.Number:
return string(origin), nil
case json.RawMessage:
return string(origin), nil
case []byte:
return string(origin), nil
case bool:
return strconv.FormatBool(origin), nil
case nil:
return "", nil
default:
// try to cast to basic (in case input is ~basic)
if basic, err := tryCastToBasicType(input); err == nil {
return c.AsString(basic)
}
return tryReflectConvert[string](input)
}
}
func (c DefaultCaster) AsStringSlice(input any) ([]string, error) {
return mapTo(input, mapOpFn(c.AsString))
}