1 回答

TA貢獻1830條經驗 獲得超3個贊
問題是您正在迭代地圖并同時更改它,但期望迭代不會看到您所做的事情。代碼的相關部分是:
for k, v := range a {
title := strings.Title(k)
a[title] = a[k]
delete(a, k)
}
因此,如果映射有{"hello":2, "world":3},并假設鍵按該順序迭代。第一次迭代后,您現在擁有:
{"world":3, "Hello":2}
下一次迭代:
{"World":3, "Hello":2}
下一次迭代查看“Hello”,它已經大寫,因此您再次將其大寫,然后刪除它,最終得到:
{"World":3}
您可能想要生成一個新的映射,而不是覆蓋現有的映射,然后返回該映射,以便調用者可以使用它。
func main() {
a := make(map[string]interface{})
a["start"] = map[string]interface{}{
"hello": 2,
"world": 3,
"here": map[string]interface{}{
"baam": 123,
"boom": "dsd",
},
}
a=printMap(a)
fmt.Println(a)
}
func printMap(a map[string]interface{}) map[string]interface{} {
newMap:=map[string]interface{}{}
for k, v := range a {
switch v.(type) {
case map[string]interface{}:
newMap[k]=printMap(v.(map[string]interface{}))
default:
title := strings.Title(k)
newMap[title] = a[k]
}
}
return newMap
}
- 1 回答
- 0 關注
- 131 瀏覽
添加回答
舉報