Is there a way to write generic code to find out whether a slice contains specific element in Go?

后端 未结 4 615
离开以前
离开以前 2021-01-20 13:38

I want to know is there a generic way to write code to judge whether a slice contains an element, I find it will frequently useful since there is a lot of logic to fist judg

4条回答
  •  礼貌的吻别
    2021-01-20 14:05

    You can do it with reflect, but it will be MUCH SLOWER than a non-generic equivalent function:

    func Contains(slice, elem interface{}) bool {
    
        sv := reflect.ValueOf(slice)
    
        // Check that slice is actually a slice/array. 
        // you might want to return an error here
        if sv.Kind() != reflect.Slice && sv.Kind() != reflect.Array {
            return false
        }
    
        // iterate the slice
        for i := 0; i < sv.Len(); i++ {
    
            // compare elem to the current slice element
            if elem == sv.Index(i).Interface() {
                return true
            }
        }
    
        // nothing found
        return false
    
    
    }
    
    func main(){
        si := []int {3, 4, 5, 10, 11}
        ss := []string {"hello", "world", "foo", "bar"}
    
        fmt.Println(Contains(si, 3))
        fmt.Println(Contains(si, 100))
        fmt.Println(Contains(ss, "hello"))
        fmt.Println(Contains(ss, "baz"))
    
    }
    

    How much slower? about x50-x60 slower: Benchmarking against a non generic function of the form:

    func ContainsNonGeneic(slice []int, elem int) bool {
        for _, i := range slice {
            if i == elem {
                return true
            }
        }
        return false
    }
    

    I'm getting:

    • Generic: N=100000, running time: 73.023214ms 730.23214 ns/op
    • Non Generic: N=100000, running time: 1.315262ms 13.15262 ns/op

提交回复
热议问题