英文:
how to append string to the map of string to interface type
问题
我有一个创建的字符串到interface{}的映射。
x := make(map[string]interface{})
最终我需要以下输出。
x["key1"] = ["value1","value2","value3", ......]
有人可以帮忙吗?如何将字符串值追加到这个映射中?
英文:
I have a map of string to interface{} created
x := make(map[string]interface{})
ultimately i need the following output
x["key1"] = ["value1","value2","value3", ......]
can anyone help , how to append string values to this map ?
答案1
得分: 4
你只能向切片(slices)追加元素,而不能向映射(maps)追加元素。
要添加你列出的值,请使用以下代码:
x["key"] = []string{"value1", "value2", "value3"}
fmt.Println(x)
如果"key"
已经存在,你可以使用类型断言(type assertion)来追加元素:
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 {
// 要么缺失,要么不是 []string 类型
x["key"] = []string{"value4", "value5"}
}
在Go Playground上尝试这个示例。
英文:
You can only append to slices, not to maps.
To add the value you listed, use:
x["key"] = []string{"value1","value2","value3"}
fmt.Println(x)
If "key"
already exists, you may use type assertion to append to it:
x["key"] = append(x["key"].([]string), "value4", "value5")
fmt.Println(x)
Output (try the examples on the Go Playground):
map[key:[value1 value2 value3]]
map[key:[value1 value2 value3 value4 value5]]
Note: you have to reassign the new slice (returned by append()
).
Also note that if "key"
is not yet in the map or is not of type []string
, the above code will panic. To protect against such panic, only append if the value exists and is of type []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"}
}
Try this one on the Go Playground.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论