gpt4 book ai didi

go - Concat在Golang中的两个 map

转载 作者:行者123 更新时间:2023-12-01 20:27:05 25 4
gpt4 key购买 nike

我知道golang中的append函数,但是有类似的函数可以追加两个 map 。

slice1 := []string{"hello"}
slice2 := []string{"world"}

combined := append(slice1, slice2...)

我试图对 map 做同样的事情,但是它给了我这个错误:

first argument to append must be slice; have map[string]string



therea是在go中附加两个 map 的方法吗?

最佳答案

只需编写一个或两个循环。

map1 := map[string]int{
"one": 1,
"two": 2,
}
map2 := map[string]int{
"uno": 1,
"dos": 2,
}

combined := map[string]int{}
for k, v := range map1 {
combined[k] = v
}
for k, v := range map2 {
combined[k] = v
}

fmt.Println(combined) // map[dos:2 one:1 two:2 uno:1]

Try it on the playground

当然,如果两个 map 的键集重叠,则顺序很重要。

关于go - Concat在Golang中的两个 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60141127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com