我寫在轉到接受一個可迭代的數據結構(即陣列,切片,或字符串),然後計數器功能的任意可迭代數據結構計算該結構的元件:遍歷在Go
func NewFreqDist(iterable interface{}) *FreqDist {
fd := FreqDist{make(map[reflect.Value]int)}
switch reflect.TypeOf(iterable).Kind() {
case reflect.Array, reflect.Slice, reflect.String:
i := reflect.ValueOf(iterable)
for j := 0; j < i.Len(); j++ {
fd.Samples[i.Index(j)]++
}
default:
Code to handle if the structure is not iterable...
}
return &fd
}
FreqDist
對象包含一個包含計數的地圖(Samples
)。但是,當我在功能外打印地圖時,它看起來像這樣:
map[<uint8 Value>:1 <uint8 Value>:1]
使用鍵訪問映射中的值無法正常工作。 建議使用reflect
程序包解決此問題的答案是here。 那麼,如何在Go中遍歷任意數據結構?