arrays - 遍历 Go 中的任意可迭代数据结构

标签 arrays string function dictionary go

我正在 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/

相关文章:

c - 在 C 中操作字符串时,仅在发布配置中出现段错误

Python计算器编程错误

linux - 影响启动它的交互式 shell 的脚本

python - Python 中只将一个变量传递给函数

c++ - 在 C++ 的二进制文件中发出读/写结构数组

arrays - 在 Bash 中迭代字符串数组并删除其部分值?

android - 如何获得微调值以发布表单

python - 用逗号分割字符串,这样每个句子都是一个单独的字符串

python - bool numpy 数组的子矩阵求和

ruby-on-rails - 在数组中使用 'order' 的替代方法