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.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
Switch with `fallthrough`Breaking from Nested LoopsContinuing a Specific LoopThe `goto` StatementRecap - Advanced Loop Control4Project: Simple Task List
Project SetupAdding a Task2Structs and Methods
Defining Methods on StructsValue ReceiversPointer ReceiversChoosing ReceiversMethods vs FunctionsRecap - Struct Behavior5Maps In-Depth
Maps of StructsPointers as Map ValuesTesting for Nil MapsComparing MapsRecap - Word Frequency Counter3Interfaces (The Basics)
What is an Interface?Defining an InterfaceImplementing an InterfaceUsing Interface TypesEmpty InterfaceType AssertionsType SwitchRecap - Shapes and Behaviors