Menu
Coddy logo textTech

Comparing Maps

Part of the Logic & Flow section of Coddy's GO journey — lesson 29 of 68.

Unlike many other data types in Go, maps have a unique limitation: they cannot be directly compared using the == operator. The only exception to this rule is when comparing a map to nil.

This means that code like this will not compile:

map1 := map[string]int{"a": 1, "b": 2}
map2 := map[string]int{"a": 1, "b": 2}

// This will cause a compile error!
if map1 == map2 {
    fmt.Println("Maps are equal")
}

However, you can safely compare a map to nil:

var myMap map[string]int
if myMap == nil {
    fmt.Println("Map is nil")
}

When you need to check if two maps contain the same key-value pairs, you must write a custom function that iterates through both maps and compares each element individually. This approach gives you complete control over the comparison logic, allowing you to define exactly what "equal" means for your specific use case.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

Cheat sheet

Maps cannot be directly compared using the == operator, except when comparing to nil:

// This will NOT compile
map1 := map[string]int{"a": 1, "b": 2}
map2 := map[string]int{"a": 1, "b": 2}
if map1 == map2 { // Compile error!
    fmt.Println("Maps are equal")
}

You can compare a map to nil:

var myMap map[string]int
if myMap == nil {
    fmt.Println("Map is nil")
}

To check if two maps are equal, you must write a custom function that iterates through both maps and compares each element individually.

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow