【问题标题】:GO: Type assertion from listGO:从列表中键入断言
【发布时间】:2015-01-28 16:18:24
【问题描述】:

我在一个列表中存储了一组字符串。我遍历列表以与字符串"[the]" 进行比较。

当我使用函数strings.EqualFold时,它会出现这个错误:

不能在函数参数中使用 e.Value (type interface {}) 作为类型字符串:需要类型断言

代码如下:

for e := l.Front(); e != nil; e = e.Next() {
        if(strings.EqualFold("[the]", e.Value)){
            count++

        }
    }

【问题讨论】:

  • 不使用链表?有什么理由不能使用切片?

标签: go


【解决方案1】:

由于 Go 的链表实现使用空的 interface{} 来存储列表中的值,因此您必须使用 type assertion 就像错误指示的那样访问您的值。

因此,如果您在列表中存储string,当您从列表中检索值时,您必须键入断言该值是一个字符串。

for e := l.Front(); e != nil; e = e.Next() {
    if(strings.EqualFold("[the]", e.Value.(string))){
        count++
    }
}

【讨论】:

    【解决方案2】:

    从“e.Value”中交换一个“e.Value.(string)”。

    【讨论】:

      猜你喜欢
      • 2017-02-09
      • 1970-01-01
      • 2016-05-26
      • 2021-06-22
      • 2021-02-10
      • 1970-01-01
      • 2016-12-13
      • 1970-01-01
      • 2017-10-30
      相关资源
      最近更新 更多