执行顺序、断言问题、map复制
执行顺序
import -> const -> var -> init -> main -> exit
断言?:
Json数据:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
{
"extras":{
"template_id":"2nuGz1AciMcJp9GyAmsebWB7EAlqTbhr6Wp2d7QXZ2A",
"url":"",
"data":{
"first":{
"value":"asd465465",
"color":"#17317"
},
"keyword1":{
"value":"$(Member.ID)",
"color":"#17317"
},
"keyword2":{
"value":"asdad"
},
"remark":{
"value":"$(Member.Nick)",
"color":"#17317"
}
}
}
}
|
解析代码:
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
|
// map[string]interface{} map[string]map[string]map[string]string
// 正常
extras = map[string]interface{}
for key, val := range Extras {
if key == handler_push.TPL_KEY_DATA {
for keyWord, valMap := range val.(map[string]interface{}) {
// fmt.Printf("%v, %v\n", keyWord, valMap)
v := valMap.(map[string]interface{})
// fmt.Printf("%v, %v\n", keyWord, v)
vStr := v[handler_push.TPL_DATA_VALUE].(string)
colorStr := v[handler_push.TPL_DATA_COLOR].(string)
}
}
}
// 错误
extras = map[string]interface{}
for key, val := range Extras {
if key == handler_push.TPL_KEY_DATA {
for keyWord, valMap := range val.(map[string]map[string]string) {
// fmt.Printf("%v, %v\n", keyWord, valMap)
vStr := valMap[handler_push.TPL_DATA_VALUE].(string)
colorStr := valMap[handler_push.TPL_DATA_COLOR].(string)
}
}
}
|
断言问题:
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
|
if val, ok := Extras[TPL_KEY_DATA]; ok {
for _, data := range val.([]map[string]string) {
tdv := &WxPushTemplateDataValue{}
tdv.Value = data[TPL_DATA_VALUE]
if color, ok := data[TPL_DATA_COLOR]; ok {
tdv.Color = color
}
mp[data[TPL_DATA_KEY]] = tdv
}
}
//interface conversion: interface {} is []interface {}, not []map[string]string
// 两次访问会出错
if datas, ok := Extras[TPL_KEY_DATA]; ok {
fmt.Printf("ssss %v", datas)
for _, data := range datas.([]interface{}) {
_data := data.(map[string]interface{})
d := make(map[string]string, 0)
d[TPL_DATA_KEY] = _data[TPL_DATA_KEY].(string)
d[TPL_DATA_VALUE] = replaceParam(member, _data[TPL_DATA_VALUE].(string))
if color, ok := _data[TPL_DATA_COLOR]; ok {
d[TPL_DATA_COLOR] = color.(string)
}
}
}
//interface {} is []map[string]string, not []interface {}
|
两个map复制
1
2
3
4
5
6
|
// 仅仅传递了指针,容易出现问题
map1 = map2
// 真正的值复制
for key, val := range map2 {
map1[key] = val
}
|