Without a for
loop, no* (see How to search for an element in a golang slice), but... what do you have against for
loops? Why can't you use loops for this? This question is like "can I do it without coding"?
* Actually you could do it without a for
loop using a recursive function, but that is good only for educational purposes, and is worthless for practical purposes. See solution at the end of the answer.
There is no ready function for this in the standard library, but this is how easy it is to create one yourself:
func find(what interface{}, where []interface{}) (idx int) {
for i, v := range where {
if v == what {
return i
}
}
return -1
}
And using it:
what := 10
where := []interface{}{1, 2, 3, 10, 5}
fmt.Println(find(what, where))
Output (try it on the Go Playground):
3
Also note that it would be faster and more convenient to use []int
slice type instead of []interface{}
:
func find(what int, where []int) (idx int) {
for i, v := range where {
if v == what {
return i
}
}
return -1
}
And then using it:
what := 10
where := []int{1, 2, 3, 10, 5}
fmt.Println(find(what, where))
Output is the same. Try this one on the Go Playground.
You could create a function that accepts slices of any type using the interface{}
type, but that would require reflection to implement it, which would be slower and not worthy to be used. Instead just create a function with concrete slice types if you need, or just use the for
loop in place.
For completeness, here's the solution that uses no for
loops but a recursive function. This is here only for educational purposes, the solutions above are superior to this:
func find(what int, where []int) (idx int) {
if len(where) == 0 {
return -1
}
if what == where[0] {
return 0
}
if idx = find(what, where[1:]); idx < 0 {
return -1 // Not found in the rest of the slice
}
return 1 + idx
}
Try this one on the Go Playground.