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.

Reply via email to