你可以用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
非常感謝您的基準測試。 – armnotstrong 2015-03-03 10:52:49