Arrays 在Go中迭代任意iterable数据结构
我在Go中编写了一个计数器函数,它接受一个iterable数据结构(即数组、切片或字符串),然后对该结构的元素进行计数:Arrays 在Go中迭代任意iterable数据结构,arrays,string,function,dictionary,go,Arrays,String,Function,Dictionary,Go,我在Go中编写了一个计数器函数,它接受一个iterable数据结构(即数组、切片或字符串),然后对该结构的元素进行计数: func NewFreqDist(iterable interface{}) *FreqDist { fd := FreqDist{make(map[reflect.Value]int)} switch reflect.TypeOf(iterable).Kind() { case reflect.Array, reflect.Slice, reflect.St
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
}
使用键访问映射中的值无法正常工作。
建议对此问题使用reflect
包的答案是。
那么,如何在go中遍历任意数据结构呢?您链接到的答案的顶部注释是 唯一需要添加的是s.Index(i)返回一个reflect.Value,因此在我的例子中,我需要s.Index(i).Interface()来引用实际值核子 如果我正确理解了你的问题,我相信这就是你的解决方案。不要使用
i.Index(j)
在地图中定义键,请尝试i.Index(j).Interface()
。您的映射需要是map[interface{}]int
。这样,在访问地图中的值时,可以使用原始iterable
中的数据作为键
下面是一个操场示例I(粗略地)根据您的代码改编:
根据您的数据,您可能希望在某个时候使用以避免恐慌
map[<uint8 Value>:1 <uint8 Value>:1]