我想創建一個函數,它可以接受映射或任何其他數組,並遍歷它調用每個項目上的函數,該函數知道如何處理遇到的任何類型。遍歷接口
這是我第一次失敗的嘗試。目前,當我在我的真實使用案例中運行它時,它總是說「呃哦!」。
func DoTheThingToAllTheThings(data_interface interface{}) int {
var numThings int
switch data := data_interface.(type) {
case map[interface{}]interface{}:
numThings = len(data)
for index, item := range data {
DoTheThing(index, item)
}
case []interface{}:
numThings = len(data)
for index, item := range data {
DoTheThing(index, item)
}
default:
fmt.Println("uh oh!")
}
return numThings
}
數組或地圖可以包含很多不同的東西,所以它不是嘗試所有可能的輸入匹配的選項。
另有說明,有沒有辦法在Go中迭代數組或地圖而不知道它是什麼?
下面的「基於反射」的解決方案將起作用,但是地道的東西只是在可能的情況下在callsite處寫出循環。 – twotwotwo 2014-09-13 22:00:46