-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathany_to_str.go
130 lines (114 loc) · 2.61 KB
/
any_to_str.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
/*
-------------------------------------------------
Author : Zhang Fan
date: 2020/7/17
Description :
-------------------------------------------------
*/
package zstr
import (
"fmt"
"reflect"
"strconv"
"strings"
)
// 任何值转字符串
func AnyToStr(a interface{}, nilToEmpty ...bool) string {
return anyToString(a, nilToEmpty...)
}
// 任何值转字符串
func anyToString(a interface{}, nilToEmpty ...bool) string {
switch v := a.(type) {
case nil:
if len(nilToEmpty) > 0 && nilToEmpty[0] {
return ""
}
return "nil"
case string:
return v
case []byte:
return *BytesToString(v)
case bool:
if v {
return "true"
}
return "false"
case int:
return strconv.FormatInt(int64(v), 10)
case int8:
return strconv.FormatInt(int64(v), 10)
case int16:
return strconv.FormatInt(int64(v), 10)
case int32:
return strconv.FormatInt(int64(v), 10)
case int64:
return strconv.FormatInt(v, 10)
case uint:
return strconv.FormatUint(uint64(v), 10)
case uint8:
return strconv.FormatUint(uint64(v), 10)
case uint16:
return strconv.FormatUint(uint64(v), 10)
case uint32:
return strconv.FormatUint(uint64(v), 10)
case uint64:
return strconv.FormatUint(v, 10)
}
return fmt.Sprint(a)
}
// 任何值转sql需要的字符串
func AnyToSqlStr(a interface{}, str_crust ...bool) string {
return anyToSqlString(a, len(str_crust) > 0 && str_crust[0])
}
// 任何值转sql需要的字符串
func anyToSqlString(a interface{}, str_crust bool) string {
switch v := a.(type) {
case nil:
return "null"
case string:
if str_crust {
return `'` + v + `'`
}
return v
case []byte:
if str_crust {
return `'` + *BytesToString(v) + `'`
}
return *BytesToString(v)
case bool:
if v {
return "true"
}
return "false"
case int:
return strconv.FormatInt(int64(v), 10)
case int8:
return strconv.FormatInt(int64(v), 10)
case int16:
return strconv.FormatInt(int64(v), 10)
case int32:
return strconv.FormatInt(int64(v), 10)
case int64:
return strconv.FormatInt(v, 10)
case uint:
return strconv.FormatUint(uint64(v), 10)
case uint8:
return strconv.FormatUint(uint64(v), 10)
case uint16:
return strconv.FormatUint(uint64(v), 10)
case uint32:
return strconv.FormatUint(uint64(v), 10)
case uint64:
return strconv.FormatUint(v, 10)
}
r_v := reflect.Indirect(reflect.ValueOf(a))
if r_v.Kind() != reflect.Slice && r_v.Kind() != reflect.Array {
return fmt.Sprint(a)
}
l := r_v.Len()
ss := make([]string, l)
for i := 0; i < l; i++ {
ss[i] = anyToSqlString(reflect.Indirect(r_v.Index(i)).Interface(), str_crust)
}
return `(` + strings.Join(ss, ", ") + `)`
}