Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 在Go中迭代任意iterable数据结构_Arrays_String_Function_Dictionary_Go - Fatal编程技术网

Arrays 在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

我在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.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]