icz*_*cza 9
简单合并
map[string][]string
要进行合并,只需对要合并的映射进行范围划分,然后将源映射中的每个值附加到结果映射中与相同键关联的切片。
需要注意的一件事是,一旦执行了追加操作,就必须将结果切片分配回结果映射中的相同键。
这是一个简单的实现:
func merge(ms ...map[string]string) map[string][]string {
res := map[string][]string{}
for _, m := range ms {
for k, v := range m {
res[k] = append(res[k], v)
}
}
return res
}
Run Code Online (Sandbox Code Playgroud)
merge()
nilnilappend()
测试它:
m1 := map[string]string{"id_1": "val_1"}
m2 := map[string]string{"id_2": "val_2"}
m3 := map[string]string{"id_1": "val_3"}
res := merge(m1, m2, m3)
fmt.Println(res)
Run Code Online (Sandbox Code Playgroud)
输出(在Go Playground上试试):
map[id_1:[val_1 val_3] id_2:[val_2]]
Run Code Online (Sandbox Code Playgroud)
避免重复
merge()"id_1": "val_1""id_1": ["val_1", "val_1", "val_x"]
这是如何做到的:
func merge(ms ...map[string]string) map[string][]string {
res := map[string][]string{}
for _, m := range ms {
srcMap:
for k, v := range m {
// Check if (k,v) was added before:
for _, v2 := range res[k] {
if v == v2 {
continue srcMap
}
}
res[k] = append(res[k], v)
}
}
return res
}
Run Code Online (Sandbox Code Playgroud)
测试它:
m1 := map[string]string{"id_1": "val_1"}
m2 := map[string]string{"id_2": "val_2", "id_1": "val_1"}
m3 := map[string]string{"id_1": "val_3"}
res := merge(m1, m2, m3)
fmt.Println(res)
Run Code Online (Sandbox Code Playgroud)
输出(在Go Playground上试试):
map[id_1:[val_1 val_3] id_2:[val_2]]
Run Code Online (Sandbox Code Playgroud)
"id_1": "val_1"m1m2"val_1""id_1"