returning an array of maps golang


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:

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

    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

Another option is to use a composite literal:

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

Answered By – Zombo

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.