英文:
How to create a Map<String, List<SomeClass>> in Go?
问题
在Go语言中,你可以使用以下方式创建一个Map<String, List<SomeClass>>
:
var m map[string][]SomeClass
m = make(map[string][]SomeClass)
这里的[]SomeClass
表示一个SomeClass
类型的切片。你可以根据需要将SomeClass
替换为你实际使用的类型。
英文:
How do I create a Map<String, List<SomeClass>>
in Go? Something like:
var m map[string]list
m = make(map[string]list)
答案1
得分: 4
你正在寻找map[string][]SomeClass
。
然而,你使用make的方式行不通。我个人建议使用复合字面量语法进行初始化,代码如下:
m := map[string][]SomeClass{
"a": []SomeClass{SomeClass{SomeProperty: SomeValue}},
}
如果你想使用make,你需要遍历map,并为每个键调用make,否则该键对应的[]SomeClass
数组将为nil。我的语法如下:外层大括号表示map,内部我声明了一个键"a",并初始化了一个SomeClass的切片,在切片内部,我初始化了一个SomeClass的实例,并将SomeProperty设置为SomeValue。
如果你非常喜欢使用make,出于某种原因,我可以提供另一个使用make进行初始化的示例,但我个人认为这种方式更加复杂。
编辑:
以下是一个更接近你所寻找的示例:
var m map[string][]Model
m = make(map[string][]Model)
for i, _ := range Cars {
m[Cars[i].Make] = append(m[Cars[i].Make], Cars[i].Model)
}
在这个示例中,我首先初始化了map,然后开始遍历"cars"数组。对于每辆车,我检查是否存在其"Make"对应的键,如果存在,则将该"Model"追加到该键对应的切片中,否则,我会实例化一个包含该"Model"的新切片。当然,这不是实际可运行的代码,但应该能给你一个大致的思路。如果你提供一个更完整的示例(比如要放入map中的Cars数据的样本),我可以更具体地为你定制代码,但我希望这能给你一个大致的概念。
英文:
You're looking for; map[string][]SomeClass
However, the way you're using make won't cut it. I would personally recommend using composite literal syntax for initialization, it would look like this;
m := map[string][]SomeClass {
"a": []SomeClass{SomeClass{SomeProperty: SomeValue}}
}
If you want to use make, you'll have to iterate over the map and call make for every key or the []SomeClass
array for that key is gonna be nil. My syntax initializes as follows; outer most braces is for the map, inside it I declare a single key "a" and initialize a slice of SomeClass, inside the slice I initialize an instance of SomceClass setting SomeProperty to SomeValue.
If you highly prefer using make for whatever reason I can add another example which initializes the collection that way, I just find it to be more complicated personally.
EDIT:
Here's some sample closer to what you might be looking for
var m map[string][]Model
m = make(map[string][]Model)
for i, _ := range Cars {
m[Cars[i].Make] = append(m[Cars[i].Make], Cars[i].Model)
}
In this example I'm initialize the map, then I start iterating over the "cars" array. For each car I check to see if there is a key for it's Make
if there is, then I append the Model
to the slice with that key, otherwise, I instantiate a new slice with the model. Of course, that isn't actual working code but it should give you some idea. If you provide a more complete example (like a sample of the Cars data you want to put in the map) then I could tailor this more to your needs but I'm hoping that will give you the general idea.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论