返回一组地图 golang

returning an array of maps golang

我正在尝试创建一个 return 地图数组的函数。或者在 python 中,我会 return 例如一个字典列表。我想我缺少一些简单的东西,我不知道如何定义一个数组变量,其中的类型是映射。

这是我注释掉无效部分的工作代码:

https://go.dev/play/p/msPRp0WiaB1

我把它留在 main 中作为 ^ 示例,但我真正想做的是有另一个函数 returns 地图列表所以代码的另一部分并迭代它们:

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
}

使用内置 append 函数将项目添加到切片:

var theFarm []map[string]string
theFarm = append(theFarm, inventory1)
theFarm = append(theFarm, inventory2)
return theFarm

https://go.dev/play/p/4-588WdQ6mf

另一种选择是使用 composite literal:

theFram := []map[string]string{inventory1, inventory2}
return theFarm

https://go.dev/play/p/a7WZJOthwYt