【发布时间】:2016-12-25 21:37:23
【问题描述】:
我正在用 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 中遍历任意数据结构呢?
【问题讨论】:
标签: arrays string function dictionary go