I want to know is there a generic way to write code to judge whether a slice contains an element, I find it will frequently useful since there is a lot of logic to fist judge whether specific elem is already in a slice and then decide what to do next. But there seemed not a built-in method for that(For God's sake, why?)
I try to use interface{}
to do that like:
func sliceContains(slice []interface{}, elem interface{}) bool {
for _, item := range slice {
if item == elem {
return true
}
}
return false
}
I thought interface{}
is sort of like Object
of Java, but apparently, I was wrong. Should I write this every time meet with a new struct of slice? Isn't there a generic way to do this?
I'm not sure what your specific context is, but you'll probably want to use a
map
to check if something already exists.Another advantage of using maps instead of a slice is that there is a built-in
delete
function for maps. https://play.golang.org/p/dmSyyryyS8You can make it using the
reflect
package like that:Playground examples: http://play.golang.org/p/TQrmwIk6B4
Alternatively, you can:
What way to choose depends on the problem you are solving.
If you want a rather different solution, you might try the code-generator approach offered by tools such as Gen. Gen writes source code for each concrete class you want to hold in a slice, so it supports type-safe slices that let you search for the first match of an element.
(Gen also offers a few other kinds of collection and allows you to write your own.)
You can do it with
reflect
, but it will be MUCH SLOWER than a non-generic equivalent function:How much slower? about x50-x60 slower: Benchmarking against a non generic function of the form:
I'm getting:
N=100000, running time: 73.023214ms 730.23214 ns/op
N=100000, running time: 1.315262ms 13.15262 ns/op