如何将字符串附加到字符串到接口类型的映射

how to append string to the map of string to interface type

提问人:Abhishek D K 提问时间:6/23/2021 最后编辑:iczaAbhishek D K 更新时间:6/23/2021 访问量:1385

问:

我创建了一个字符串到 interface{} 的映射

x := make(map[string]interface{})  

最终,我需要以下输出

x["key1"] = ["value1","value2","value3", ......]

谁能帮忙,如何将字符串值附加到这张地图?

字典 切片

评论


答:

4赞 icza 6/23/2021 #1

您只能追加到切片,而不能追加到地图。

若要添加您列出的值,请使用:

x["key"] = []string{"value1","value2","value3"}
fmt.Println(x)

如果已经存在,您可以使用类型断言来附加到它:"key"

x["key"] = append(x["key"].([]string), "value4", "value5")
fmt.Println(x)

输出(尝试 Go Playground 上的示例):

map[key:[value1 value2 value3]]
map[key:[value1 value2 value3 value4 value5]]

注意:您必须重新分配新切片(返回者)。append()

另请注意,如果尚未在地图中或不是类型,则上述代码将崩溃。为了防止这种恐慌,仅当该值存在且类型为:"key"[]string[]string

if s, ok := x["key"].([]string); ok {
    x["key"] = append(s, "value4", "value5")
} else {
    // Either missing or not []string
    x["key"] = []string{"value4", "value5"}
}

Go Playground 上试试这个。

评论

0赞 Abhishek D K 6/23/2021
panic:接口转换:接口 {} 为 nil,而不是 []string [已恢复] panic:接口转换:接口 {} 为 nil,而不是 []string
0赞 icza 6/23/2021
@AbhishekDK 是的,请阅读答案的后半部分,其中解释了它并处理了它。