find the symmetric difference of two maps in go

In Go, we can find the symmetric difference of two maps by performing a set operation between their keys. Here's an example implementation of this:

main.go
func symmetricDifference(m1 map[string]bool, m2 map[string]bool) map[string]bool {
    result := make(map[string]bool)

    for k1 := range m1 {
        _, exists := m2[k1]
        if !exists {
            result[k1] = true
        }
    }

    for k2 := range m2 {
        _, exists := m1[k2]
        if !exists {
            result[k2] = true
        }
    }

    return result
}
382 chars
20 lines

This function takes in two maps, m1 and m2, and returns a map containing the keys that are present in one map but not the other. We can apply this function to find the symmetric difference of two maps:

main.go
map1 := map[string]bool{"a": true, "b": true, "c": true}
map2 := map[string]bool{"b": true, "c": true, "d": true}

result := symmetricDifference(map1, map2)

fmt.Println(result) // Output: map[a:true d:true]
208 chars
7 lines

In the example above, result will contain the keys "a" and "d", which are the keys present in map1 but not map2, and the keys present in map2 but not map1, respectively.

gistlibby LogSnag