1

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

Simon Fox
  • 5,465
  • 14
  • 20
djdick
  • 179
  • 1
  • 2
  • 8

2 Answers2

1

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.

Community
  • 1
  • 1
VonC
  • 1,129,465
  • 480
  • 4,036
  • 4,755
0

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)

David Budworth
  • 10,611
  • 1
  • 32
  • 44