Ian, thanks for the "generic" function. I appreciate.
I think such a function would provide beautiful symmetry to the already existing "append" function Go has. Martin On Wednesday, August 9, 2017 at 5:53:45 PM UTC+2, Ian Lance Taylor wrote: > > Here is a generic Find function that works for all types, using the > language defined == operator. It will panic if invoked incorrectly. > > package main > > import ( > "fmt" > "math" > "reflect" > ) > > // Find returns the index of val in the slice s, or -1 if not found. > func Find(s, val interface{}) int { > sv := reflect.ValueOf(s) > l := sv.Len() > for i := 0; i < l; i++ { > if sv.Index(i).Interface() == val { > return i > } > } > return -1 > } > > var tests = []struct { > s, v interface{} > want int > }{ > {[]int{1, 2, 3}, 2, 1}, > {[]int{1, 2, 3}, 4, -1}, > {[]string{"a", "b"}, "a", 0}, > {[]float64{0, 1, math.NaN(), 2}, 2.0, 3}, > {[]float64{0, 1, math.NaN(), 2}, math.NaN(), -1}, > } > > func main() { > for _, t := range tests { > if got := Find(t.s, t.v); got != t.want { > fmt.Printf("Find(%v, %v) = %d, want %d\n", > t.s, t.v, got, t.want) > } > } > } > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.