【问题标题】:Iterating over an arbitrary iterable data structure in Go在 Go 中迭代任意可迭代的数据结构
【发布时间】: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


    【解决方案1】:

    您链接到的答案的最高评论是

    唯一要添加的是 s.Index(i) 返回一个 reflect.Value 所以在我的情况下,我需要 s.Index(i).Interface() 来引用实际值。 – 核子

    如果我正确理解您的问题,我相信这是您的解决方案。不要使用i.Index(j) 来定义地图中的键,而是尝试i.Index(j).Interface()。您的地图需要为map[interface{}]int。这样,您可以在访问映射中的值时使用原始 iterable 中的数据作为键。

    这是我(粗略地)改编自您的代码的游乐场示例:https://play.golang.org/p/Rwtm9EOmyN

    根据您的数据,您可能希望在某些时候使用CanInterface() 以避免恐慌。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-15
      • 2023-01-16
      • 2021-03-01
      • 2015-09-23
      • 1970-01-01
      • 1970-01-01
      • 2013-11-28
      • 1970-01-01
      相关资源
      最近更新 更多