forked from zlyuancn/zstr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalues_to_map.go
78 lines (71 loc) · 1.82 KB
/
values_to_map.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
/*
-------------------------------------------------
Author : Zhang Fan
date: 2020/7/17
Description :
-------------------------------------------------
*/
package zstr
import (
"reflect"
"strconv"
)
// 构建map, 支持 map[string]string,map[string]interface{}, KV, KVs
// 其它值按顺序转为 map[string]interface{}{"*[0]": 值0, "*[1]", 值1...}
func MakeMapOfValues(values ...interface{}) map[string]interface{} {
return makeMapOfValues(values)
}
// 构建map, 支持 map[string]string,map[string]interface{}, KV, KVs
// 其它值按顺序转为 map[string]interface{}{"*[0]": 值0, "*[1]", 值1...}
func makeMapOfValues(values []interface{}) map[string]interface{} {
if len(values) == 0 {
return make(map[string]interface{})
}
// map, kvs, kv
switch v := values[0].(type) {
case map[string]interface{}:
return v
case KVs:
data := make(map[string]interface{}, len(v))
for _, kv := range v {
data[kv.K] = kv.V
}
return data
case KV:
data := make(map[string]interface{}, len(values))
for _, value := range values {
kv, ok := value.(KV)
if !ok {
panic("所有值必须都是 zstr.KV")
}
data[kv.K] = kv.V
}
return data
case *KV:
data := make(map[string]interface{}, len(values))
for _, value := range values {
kv, ok := value.(*KV)
if !ok {
panic("所有值必须都是 *zstr.KV")
}
data[kv.K] = kv.V
}
return data
}
// 其他map
rv := reflect.Indirect(reflect.ValueOf(values[0]))
switch rv.Kind() {
case reflect.Map:
data := make(map[string]interface{}, rv.Len())
for iter := rv.MapRange(); iter.Next(); {
data[anyToString(iter.Key().Interface())] = iter.Value().Interface()
}
return data
}
// values
data := make(map[string]interface{}, len(values))
for i, v := range values {
data[`*[`+strconv.Itoa(i)+`]`] = v
}
return data
}