英文:
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
英文:
- You need to use
map[string]interface{}
instead. - 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,
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论