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

huangapple go评论85阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2021年6月23日 17:25:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/68097106.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定