-
Notifications
You must be signed in to change notification settings - Fork 3
/
string.go
53 lines (50 loc) · 1.27 KB
/
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
package cast
import "strconv"
// AsString to convert as string
func AsString(v interface{}) (string, bool) {
switch d := indirect(v).(type) {
case string:
return d, true
case bool:
return strconv.FormatBool(d), true
case int:
return strconv.FormatInt(int64(d), 10), true
case int64:
return strconv.FormatInt(d, 10), true
case int32:
return strconv.FormatInt(int64(d), 10), true
case int16:
return strconv.FormatInt(int64(d), 10), true
case int8:
return strconv.FormatInt(int64(d), 10), true
case uint:
return strconv.FormatUint(uint64(d), 10), true
case uint64:
return strconv.FormatUint(d, 10), true
case uint32:
return strconv.FormatUint(uint64(d), 10), true
case uint16:
return strconv.FormatUint(uint64(d), 10), true
case uint8:
return strconv.FormatUint(uint64(d), 10), true
case float64:
return strconv.FormatFloat(d, 'f', -1, 64), true
case float32:
return strconv.FormatFloat(float64(d), 'f', -1, 64), true
case []byte:
return string(d), true
default:
return "", false
}
}
// AsStringSlice to convert as a slice of string
func AsStringSlice(values ...interface{}) ([]string, bool) {
arr := make([]string, 0, len(values))
b := true
for _, v := range values {
cv, ok := AsString(v)
b = b && ok
arr = append(arr, cv)
}
return arr, b
}