GO:从列表中进行类型断言

huangapple go评论74阅读模式
英文:

GO: Type assertion from list

问题

我在一个列表中存储了一组字符串。我通过迭代列表与字符串"[the]"进行比较。

当我使用strings.EqualFold函数时,出现以下错误:

无法将e.Value(类型为interface {})作为函数参数中的字符串类型使用:需要类型断言

代码如下:

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

    }
}
英文:

I have stored a set of strings in a list. I iterate through the list to compare with the string "[the]".

When I use the function strings.EqualFold, it presents this error:

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

The code is as follows:

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

		}
	}

答案1

得分: 5

由于Go语言的链表实现使用空的interface{}来存储列表中的值,所以你必须使用类型断言,就像错误提示所示,来访问你的值。

所以,如果你在列表中存储了一个string,当你从列表中检索值时,你必须进行类型断言,确保值是一个字符串。

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

Since Go's linked list implementation uses an empty interface{} to store the values in the list, you have to you use type assertion like the error indicates to access your value.

So if you store a string in the list, when you retrieve the value from the list you have to type assert that the value is a string.

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

答案2

得分: 2

将 "e.Value" 中的 "e.Value.(string)" 替换为 "e.Value"。

英文:

Swap a "e.Value.(string)" from "e.Value".

huangapple
  • 本文由 发表于 2015年1月28日 11:42:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/28184251.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定