Source file tour/generics/index.go

     1  //go:build OMIT
     2  
     3  package main
     4  
     5  import "fmt"
     6  
     7  // Index returns the index of x in s, or -1 if not found.
     8  func Index[T comparable](s []T, x T) int {
     9  	for i, v := range s {
    10  		// v and x are type T, which has the comparable
    11  		// constraint, so we can use == here.
    12  		if v == x {
    13  			return i
    14  		}
    15  	}
    16  	return -1
    17  }
    18  
    19  func main() {
    20  	// Index works on a slice of ints
    21  	si := []int{10, 20, 15, -10}
    22  	fmt.Println(Index(si, 15))
    23  
    24  	// Index also works on a slice of strings
    25  	ss := []string{"foo", "bar", "baz"}
    26  	fmt.Println(Index(ss, "hello"))
    27  }
    28  

View as plain text