您可以使用进行此操作
reflect,但它比非泛型等效函数要 慢 得多:
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"))}慢多少? 大约慢x50-x60 :对以下形式的非泛型函数进行基准测试:
func ContainsNonGeneic(slice []int, elem int) bool { for _, i := range slice { if i == elem { return true } } return false}我越来越:
- 通用:
N=100000, running time: 73.023214ms 730.23214 ns/op
- 非通用:
N=100000, running time: 1.315262ms 13.15262 ns/op



