我正在嘗試創建一個回傳地圖陣列的函式。或者在 python 中,例如我會回傳一個字典串列。我想我錯過了一些簡單的東西,我不知道如何定義一個陣列變數,其中的型別是映射。
這是我注釋掉不起作用的部分的作業代碼:
https://go.dev/play/p/msPRp0WiaB1
我將它留在 main 中作為 ^ 示例,但我真正想做的是有另一個函式回傳映射串列,以便代碼的另一部分并迭代它們:
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
}
uj5u.com熱心網友回復:
使用內置的append函式將專案添加到切片中:
var theFarm []map[string]string
theFarm = append(theFarm, inventory1)
theFarm = append(theFarm, inventory2)
return theFarm
https://go.dev/play/p/4-588WdQ6mf
另一種選擇是使用復合文字:
theFram := []map[string]string{inventory1, inventory2}
return theFarm
https://go.dev/play/p/a7WZJOthwYt
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/453313.html
上一篇:在Golang中撰寫INT_MAX最簡單的方法是什么?
下一篇:在Golang中回傳聯合型別
