How to get intersection of two slice in golang?

前端 未结 5 1505
不思量自难忘°
不思量自难忘° 2021-02-18 22:24

Is there any efficient way to get intersection of two slices in Go?

I want to avoid nested for loop like solution
slice1 := []string{\"foo\", \"bar\",\"hello\"}         


        
5条回答
  •  天涯浪人
    2021-02-18 23:08

    if there exists no blank in your []string, maybe you need this simple code:

    func filter(src []string) (res []string) {
        for _, s := range src {
            newStr := strings.Join(res, " ")
            if !strings.Contains(newStr, s) {
                res = append(res, s)
            }
        }
        return
    }
    
    func intersections(section1, section2 []string) (intersection []string) {
        str1 := strings.Join(filter(section1), " ")
        for _, s := range filter(section2) {
            if strings.Contains(str1, s) {
                intersection = append(intersection, s)
            }
        }
        return
    }
    

提交回复
热议问题