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