英文:
multilevel slices with string indexes
问题
我有一个代码看起来像这样:
var c [][]string
c = append(c, d)
c = append(c, l)
假设d和l都是[]string。这个代码是有效的,但它返回的结果是这样的:
[["0241025570","0241025571","1102182000"],["0241025570","0241025571","1102182000"]]
如何将其结构化为这样的形式:
["d": ["0241025570","0241025571","1102182000"], "l":["0241025570","0241025571","1102182000"]]
英文:
I have a code that looks like this:
var c [][]string
c = append(c, d)
c = append(c, l)
Assuming that both d and l are []strings. This works, however it would return something like this:
[["0241025570","0241025571","1102182000"],["0241025570","0241025571","1102182000"]]
How would it be possible to structure it to look like this:
["d": ["0241025570","0241025571","1102182000"], "l":["0241025570","0241025571","1102182000"]]
答案1
得分: 4
你想要的不再是一个切片,而是一个切片的映射。你可以使用以下代码来获得所需的结果:
c := make(map[string][]string)
c["d"] = d
c["l"] = l
根据你的使用情况,你可能希望对 d
和 l
进行复制,而不是直接在映射中使用它们:
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)
英文:
What you would like to have would no longer be a slice, but a map of slices. You can get the desired results using the following code:
c := make(map[string][]string)
c["d"] = d
c["l"] = l
Depending on your usage, you may want to make copies of d
and l
, instead of using them directly in the map:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论