将非切片追加到切片的映射中

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

appending non slice to map of slices

问题

我的当前代码是这样的:

name := "John"
id := "1234"
c := make(map[string][]string)

c["d"] = make([]string, len(d))
c["l"] = make([]string, len(l))

copy(c["d"], d)
copy(c["l"], l)
c["test"] = name
c["id"] = id

假设d和l都是[]string。Go语言不允许我这样做。有没有一种方法可以实现像这样的JSON:

{
"name": "John",
"id": "1234",
"d": [
123,
456
],
"l": [
123,
456
]
}

英文:

My current code is this:

name := "John"
id := "1234"
c := make(map[string][]string)

c["d"] = make([]string, len(d))
c["l"] = make([]string, len(l))

copy(c["d"], d)
copy(c["l"], l)
c["test"] = name
c["id"] = id

Assuming d & l are both []string. Go does not let me do this. Is there a way where I would be able to achieve a JSON like this:

{
"name": "John",
"id": "1234",
"d": [
123,
456
],
"l": [
123,
456
]
}

答案1

得分: 2

你需要使用map[string]interface{}代替。
另外,你不需要复制你的切片。

使用map[string]interface{}的示例代码:

name := "John"
id := "1234"
l, d := []string{"123", "456"}, []string{"789", "987"}
c := map[string]interface{}{
"d": d,
"l": l,
"test": name,
"id": id,
}

[kbd]playground/kbd

英文:
  1. You need to use map[string]interface{} instead.
  2. Also you don't need to copy your slices.

Example with map[string]interface{}:

name := "John"
id := "1234"
l, d := []string{"123", "456"}, []string{"789", "987"}
c := map[string]interface{}{
	"d":    d,
	"l":    l,
	"test": name,
	"id":   id,
}

<kbd>playground</kbd>

huangapple
  • 本文由 发表于 2015年8月17日 06:18:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/32040488.html
匿名

发表评论

匿名网友

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

确定