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

后端 未结 4 613
离开以前
离开以前 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:09

    You can make it using the reflect package like that:

    func In(s, e interface{}) bool {
        slice, elem := reflect.ValueOf(s), reflect.ValueOf(e)
        for i := 0; i < slice.Len(); i++ {
            if reflect.DeepEqual(slice.Index(i).Interface(), elem.Interface()) {
                return true
            }
        }
        return false
    }
    

    Playground examples: http://play.golang.org/p/TQrmwIk6B4

    Alternatively, you can:

    • define an interface and make your slices implement it
    • use maps instead of slices
    • just write a simple for loop

    What way to choose depends on the problem you are solving.

提交回复
热议问题