GO:从列表中输入断言

标签 go

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

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

Cannot use e.Value (type interface {}) as type string in function argument: need type assertion

代码如下:

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

        }
    }

最佳答案

由于 Go 的链表实现使用空的接口(interface){} 来存储列表中的值,因此您必须使用 type assertion如错误指示访问您的值。

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

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

关于GO:从列表中输入断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28184251/

相关文章:

Cgo 可以调用在另一个目录中声明的 C 函数吗?

memory - 如果字段顺序不同,则结构具有不同的大小

api - 如何在golang中通过重定向发送cookie?

Go包依赖布局

go - 将数组解码为结构

Go 如何在我的 html 页面上使用 JavaScript 代码

go - time.After 在指定时间后没有被触发

c - C/Go 中的 LDAP : Error code 53 "Server is unwilling to perfom" when trying to set unicodePwd

reflection - 是否可以使用反射来做类似于类型切换的事情?

go - 从 stdin 读取空格分隔的整数到 int slice