2016-08-18 89 views
1

我寫在轉到接受一個可迭代的數據結構(即陣列,切片,或字符串),然後計數器功能的任意可迭代數據結構計算該結構的元件:遍歷在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中遍歷任意數據結構?

回答

1

您鏈接的答案頂部註釋是

增加將是s.Index(i)返回一個reflect.Value所以在我的情況下,我需要s.Index(我的唯一).Interface()來引用實際值。 - 核子

如果我正確理解你的問題,我相信這是你的解決方案。而不是使用來定義您的地圖中的鍵,請嘗試i.Index(j).Interface()。你的地圖需要是map[interface{}]int。這樣,您可以使用原始iterable中的數據作爲訪問地圖中的值的鍵。

這裏的(粗略)改編自你的代碼,我的遊樂場例如:https://play.golang.org/p/Rwtm9EOmyN

根據你的數據,你可能需要使用CanInterface()在某一點,以避免恐慌。