forfor
for
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
[]int[]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.
interface{}for
for
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.