我正在 Go 中编写一个计数器函数,它接受一个可迭代的数据结构(即数组、 slice 或字符串),然后对该结构的元素进行计数:
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 时,它看起来像这样:
map[<uint8 Value>:1 <uint8 Value>:1]
使用键访问映射中的值无法正常工作。
建议使用 reflect
包解决此问题的答案是 here .
那么,如何在 Go 中遍历任意数据结构?
最佳答案
您链接到的答案的最高评论是
The only thing to add would be that s.Index(i) returns a reflect.Value so in my case I needed s.Index(i).Interface() to reference the actual value. – Nucleon
如果我没有正确理解您的问题,我相信这就是您的解决方案。不要使用 i.Index(j)
来定义 map 中的键,而是尝试使用 i.Index(j).Interface()
。您的 map 需要是 map[interface{}]int
。通过这种方式,您可以在访问 map 中的值时将原始 iterable
中的数据用作键。
这是我(粗略地)改编自您的代码的 Playground 示例:https://play.golang.org/p/Rwtm9EOmyN
根据您的数据,您可能需要使用 CanInterface()
在某些时候避免 panic 。
关于arrays - 遍历 Go 中的任意可迭代数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39026948/