Standard library / slices

slices.IndexFunc()

Returns the first index satisfying the predicate or -1 when no element matches. Expected stdout: '2\n'.

Formal Syntax & Structure

go syntaxgo
func IndexFunc[S ~[]E, E any](s S, f func(E) bool) int

Parameters & Attributes

NameTypeDescription
sSInput slice; may share its backing array.
ffunc(E) boolPredicate callback, true for a matching element.

Return Value

int

Returns the first index satisfying the predicate or -1 when no element matches.

Working Example

Example Snippetgo
package main
import (  "fmt"  "slices")
func main() {  fmt.Println(slices.IndexFunc([]int{2, 4, 7}, func(n int) bool { return n%2 != 0 }))}
Go Reference