dongza3124 2015-03-03 09:40
浏览 302
已采纳

有没有一种方法可以编写通用代码来确定切片是否包含Go中的特定元素?

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 judge whether specific elem is already in a slice and then decide what to do next. But there seemed not a built-in method for that(For God's sake, why?)

I try to use interface{} to do that like:

func sliceContains(slice []interface{}, elem interface{}) bool {
    for _, item := range slice {
       if item == elem {
          return true
       }
    }
    return false
}

I thought interface{} is sort of like Object of Java, but apparently, I was wrong. Should I write this every time meet with a new struct of slice? Isn't there a generic way to do this?

  • 写回答

4条回答 默认 最新

  • duanlu1922 2015-03-03 10:18
    关注

    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
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改