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

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

    I'm not sure what your specific context is, but you'll probably want to use a map to check if something already exists.

    package main
    
    import "fmt"
    
    type PublicClassObjectBuilderFactoryStructure struct {
        Tee string
        Hee string
    }
    
    func main() {
        // Empty structs occupy zero bytes.
        mymap := map[interface{}]struct{}{}
    
        one := PublicClassObjectBuilderFactoryStructure{Tee: "hi", Hee: "hey"}
        two := PublicClassObjectBuilderFactoryStructure{Tee: "hola", Hee: "oye"}
    
        three := PublicClassObjectBuilderFactoryStructure{Tee: "hi", Hee: "again"}
    
        mymap[one] = struct{}{}
        mymap[two] = struct{}{}
    
        // The underscore is ignoring the value, which is an empty struct.
        if _, exists := mymap[one]; exists {
            fmt.Println("one exists")
        }
    
        if _, exists := mymap[two]; exists {
            fmt.Println("two exists")
        }
    
        if _, exists := mymap[three]; exists {
            fmt.Println("three exists")
        }
    }
    

    Another advantage of using maps instead of a slice is that there is a built-in delete function for maps. https://play.golang.org/p/dmSyyryyS8

提交回复
热议问题