如何删除Golang上切片之间的重复元素

As a title, how to delete duplicate elements between slices on golang

ex.

a_array := {"1","2","3","4,"}
b_array := {"3","4"}

hope of result

"1","2"

With the assumption, a_array elements definitely has b_array elements. Please tell me how to do it. Thank you!

If you need to strictly compare one slice against the other you may do something along the lines of

func diff(a []string, b []string) []string {
    // Turn b into a map
    var m map[string]bool
    m = make(map[string]bool, len(b))
    for _, s := range b {
        m[s] = false
    }
    // Append values from the longest slice that don't exist in the map
    var diff []string
    for _, s := range a {
        if _, ok := m[s]; !ok {
            diff = append(diff, s)
            continue
        }
        m[s] = true
    }
    // Sort the resulting slice
    sort.Strings(diff)
    return diff
}

Go Playground


Alternatively if you want to get all values from both slices that are not present in both of them you can do

func diff(a []string, b []string) []string {
    var shortest, longest *[]string
    if len(a) < len(b) {
        shortest = &a
        longest = &b
    } else {
        shortest = &b
        longest = &a
    }
    // Turn the shortest slice into a map
    var m map[string]bool
    m = make(map[string]bool, len(*shortest))
    for _, s := range *shortest {
        m[s] = false
    }
    // Append values from the longest slice that don't exist in the map
    var diff []string
    for _, s := range *longest {
        if _, ok := m[s]; !ok {
            diff = append(diff, s)
            continue
        }
        m[s] = true
    }
    // Append values from map that were not in the longest slice
    for s, ok := range m {
        if ok {
            continue
        }
        diff = append(diff, s)
    }
    // Sort the resulting slice
    sort.Strings(diff)
    return diff
}

Then

fmt.Println(diff(a_array, b_array))

will give you

[1 2]

Go playground