英文:
returning an array of maps golang
问题
我正在尝试创建一个返回数组映射的函数。在Python中,我会返回一个字典列表。我觉得我可能漏掉了一些简单的东西,我不知道如何定义一个包含映射类型的数组变量。
以下是你提供的代码链接,我已经注释掉了不起作用的部分:
https://go.dev/play/p/msPRp0WiaB1
我将其保留在main
函数中作为示例,但我真正想做的是创建另一个函数,该函数返回映射列表,以便在代码的其他部分进行迭代:
func theFarmInventory() []map[string]string {
// 动物列表,这通常是在API调用中的循环中获取的
animalList1 := []byte(`[{"Type":"Dog","Name":"Rover"},{"Type":"Cat","Name":"Sam"},{"Type":"Bird","Name":"Lucy"}]`)
animalList2 := []byte(`[{"Type":"Hamster","Name":"Potato"},{"Type":"Rat","Name":"Snitch"},{"Type":"Cow","Name":"Moo"}]`)
inventory1 := animalStock(animalList1)
inventory2 := animalStock(animalList2)
fmt.Printf("Inventory1 %v\nInventory2: %v\n", inventory1, inventory2)
// 我想创建一个映射数组
var theFarm []map[string]string
theFarm = append(theFarm, inventory1)
theFarm = append(theFarm, inventory2)
fmt.Printf("%v", theFarm)
return theFarm
}
希望这可以帮助到你!
英文:
I'm trying to create an function that returns an array of maps. Or in python I would return a list of dicts for example. I think im missing something simple, I dont know how to define a variable of array with the type inside of it being maps.
Here's the working code I commented out the section that isn't working:
https://go.dev/play/p/msPRp0WiaB1
I left it in main for ^ example but what I really want to do is have another function that returns the list of maps so another part of the code and iterate over them:
func theFarmInventory()[]map[string]map {
//Lists of animals, this would normally be a loop in an api call for listsN
animalList1 := []byte(`[{"Type":"Dog","Name":"Rover"},{"Type":"Cat","Name":"Sam"},{"Type":"Bird","Name":"Lucy"}]`)
animalList2 := []byte(`[{"Type":"Hamster","Name":"Potato"},{"Type":"Rat","Name":"Snitch"},{"Type":"Cow","Name":"Moo"}]`)
inventory1 := animalStock(animalList1)
inventory2 := animalStock(animalList2)
fmt.Printf("Inventory1 %v\nInventory2: %v\n", inventory1, inventory2)
// I would like to create a array of maps
var theFarm []map[string]string
theFarm.append(theFarm,inventory1)
theFarm.append(theFarm,inventory2)
fmt.Printf("%v",theFarm)
return theFarm
}
答案1
得分: 3
使用内置的append函数将项目添加到切片中:
var theFarm []map[string]string
theFarm = append(theFarm, inventory1)
theFarm = append(theFarm, inventory2)
return theFarm
另一种选择是使用复合字面量:
theFarm := []map[string]string{inventory1, inventory2}
return theFarm
英文:
Use the builtin append function to add items to the slice:
var theFarm []map[string]string
theFarm = append(theFarm, inventory1)
theFarm = append(theFarm, inventory2)
return theFarm
https://go.dev/play/p/4-588WdQ6mf
Another option is to use a composite literal:
theFram := []map[string]string{inventory1, inventory2}
return theFarm
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论