多级切片与字符串索引

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

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

根据你的使用情况,你可能希望对 dl 进行复制,而不是直接在映射中使用它们:

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)

huangapple
  • 本文由 发表于 2015年8月16日 23:45:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/32036992.html
匿名

发表评论

匿名网友

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

确定