Home > Software design >  returning an array of maps golang
returning an array of maps golang

Time:03-31

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
}

CodePudding user response:

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

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

  • Related