在期望一个空接口切片的地方使用了字符串切片。

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

Using a string slice where a slice of empty interface is expected

问题

我正在尝试使用在网上找到的一个集合库与一个字符串切片。这个集合库应该能够接受泛型类型,但是当我尝试传入一个字符串切片时,出现了以下错误:

无法将 group_users (类型 []string) 作为参数传递给 mapset.NewSetFromSlice 的类型 []interface{}

有没有办法在不创建一个元素类型为 interface{} 的新切片的情况下使用这个函数?

可以在这里找到这个集合库:

我知道这可能是我做错了一些简单的事情,但是我找不到答案。

英文:

I'm trying to use a set library I found on the web with a slice of strings. The set is meant to be able to take generic types however when I try to pass in a slice of strings I get:

cannot use group_users (type []string) as type []interface{} in argument to mapset.NewSetFromSlice

Is there a way to use the function without creating a new slice with the elements being type interface{} ?

The set library can be found here:

I know this is probably something simple that I'm doing wrong but I can't seem find the answer

答案1

得分: 1

有没有一种方法可以在不创建一个元素类型为interface{}的新切片的情况下使用该函数?

实际上没有:你可能需要将字符串切片转换为接口切片,如“InterfaceSlice”中所解释的(该文章解释了为什么不能直接从[]Type转换为[]interface{}):

var dataSlice []string = foo()
var interfaceSlice []interface{} = make([]interface{}, len(dataSlice))
for i, d := range dataSlice {
    interfaceSlice[i] = d
}

考虑到interface{}的结构,你不能快速地将一个切片转换为另一个切片。

这是一个常见问题。

英文:

> Is there a way to use the function without creating a new slice with the elements being type interface{}?

Not really: You probably need to convert your slice of string into a slice of interface, as explained in "InterfaceSlice" (which is about why you can't go from []Type directly to []interface{}):

var dataSlice []string = foo()
var interfaceSlice []interface{} = make([]interface{}, len(dataSlice))
for i, d := range dataSlice {
    interfaceSlice[i] = d
}

Considering how an interface{} is structured, you cannot quickly convert one slice to the other.

This is a FAQ.

答案2

得分: 0

VonC是正确的,但如果你只是想要一个字符串切片,实现起来相当简单。

这里是一个简单版本的StringSet on play

基本思路是创建一个类型到布尔值的映射(或者我想一个空结构体可能更节省空间,但布尔值更容易使用/类型化)。

关键部分包括:

type StringSet map[string]bool
func (s StringSet) Add(val string) {
    s[val] = true
}

然后,检查是否存在可以像这样简单地进行:s["key"],因为如果存在,它将返回布尔值true,如果不存在,则返回false(因为false是布尔值的默认值)。

英文:

VonC is correct, but if you actually just want a string slice, it is fairly simple to implement

here is a simple version of a StringSet on play

The basic idea is to make a map of Type -> bool (Or I suppose an empty struct would be more space efficient, but bool is easier to use / type)

Key parts being:

type StringSet map[string]bool
func (s StringSet) Add(val string) {
    s[val] = true
}

Then, checking for presence can be as easy as s["key"] since it will return the bool true if it is present and false if it isn't (due to false being the default value for bool)

huangapple
  • 本文由 发表于 2014年9月24日 04:24:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/26004126.html
匿名

发表评论

匿名网友

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

确定