find the difference of two maps in go

To find the difference between two maps in go, you need to compare their keys and/or values. Here is one way to do it:

main.go
package main

import (
    "fmt"
)

func main() {
    map1 := map[string]int{"a": 1, "b": 2, "c": 3}
    map2 := map[string]int{"b": 2, "c": 3, "d": 4}

    // Find keys in map1 that are not in map2
    for key := range map1 {
        if _, ok := map2[key]; !ok {
            fmt.Printf("key %s in map1 is not in map2\n", key)
        }
    }

    // Find keys in map2 that are not in map1
    for key := range map2 {
        if _, ok := map1[key]; !ok {
            fmt.Printf("key %s in map2 is not in map1\n", key)
        }
    }

    // Find values in map1 that are not in map2
    for key, value := range map1 {
        if v, ok := map2[key]; ok && v != value {
            fmt.Printf("value %d in map1 is different from value %d in map2\n", value, v)
        }
    }

    // Find values in map2 that are not in map1
    for key, value := range map2 {
        if v, ok := map1[key]; ok && v != value {
            fmt.Printf("value %d in map2 is different from value %d in map1\n", value, v)
        }
    }
}
1016 chars
39 lines

In this example, we have two maps map1 and map2. We first loop through the keys of map1, and for each key, we check if it is present in map2. If it is not present, we print a message saying so. We then do the same for the keys of map2 that are not in map1.

Next, we loop through the keys and values of map1 and compare the values with the corresponding keys in map2. If the key exists in both maps and the values are different, we print a message saying so. We do the same for map2 keys and values that are not in map1.

This should give you a good idea of how to find the difference between two maps in go.

related categories

gistlibby LogSnag