Maps in Go

Comparing maps

Contrary to the structs, maps cannot be compaired in Go in a straightforward way. In order to compare them, we can use reflect.DeepEqual() function.

In an illustrative example, we will use a simple type X which will be a struct containing two fields, of type string and int. Maps which we will compare, will have keys of type string and values of type X.

type X struct {
	X1 string
	X2 int
}

a := map[string]X{
	"a1": {X1: "AA1", X2: 1},
	"a2": {X1: "AA2", X2: 2},
}

b := map[string]X{
	"a1": {X1: "AA1", X2: 1},
	"a2": {X1: "AA2", X2: 2},
}

If we try to compare a and b using a simple a==b expression, compiler will complain with an error: invalid operation: cannot compare a == b (map can only be compared to nil). We will use reflect.DeepEqual() function instead:

if reflect.DeepEqual(a, b) {
	fmt.Println("a equal b")
} else {
	fmt.Println("a is not equal b")
}

The comparison in our example will produce: a equal b output.