VOOZH about

URL: https://www.geeksforgeeks.org/go-language/comparing-maps-in-golang/

⇱ Comparing Maps in Golang - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Comparing Maps in Golang

Last Updated : 12 Nov, 2024

In Go, a map is a powerful and versatile data structure that consists of unordered key-value pairs. It offers fast lookups and allows for efficient updates and deletions based on keys. To compare two maps in Go, you can use the DeepEqual() function provided by the reflect package. This function checks if both maps are deeply equal based on certain conditions.

Example

package main
import (
"fmt"
"reflect"
)
func main() {
// Define maps
map1 := map[string]int{
"a": 5,
"b": 3,
"c": 4,
}
map2 := map[string]int{
"a": 5,
"b": 3,
"c": 4,
}
// Using DeepEqual function
result := reflect.DeepEqual(map1, map2)
fmt.Println("Are map1 and map2 equal? :", result)
}

Syntax

reflect.DeepEqual(a, b)

Comparing Maps

In Go language, you are allowed to compare two maps with each other using DeepEqual() function provided by the reflect package as shown in the above example.

Syntax

reflect.DeepEqual(a, b)

Comparison Scenarios

Now, let’s explore different scenarios for comparing maps using the same basic example.

Comparing Two Identical Maps

In this case, we are comparing map1 and map2, which are identical.


Output
Are map1 and map2 equal? : true

Comparing a Map with an Extra Entry

Let’s create a third map with an additional entry to see how the comparison behaves.

Example


Output
Are map1 and map3 equal? : false
Are map1 and map2 equal? : true

Comparing Maps with Different Key-Value Pairs

Here, we will compare map1 with a map that has different key-value pairs.

Example


Output
Are map1 and map4 equal? : false

Comparing Maps with Different Keys

In this scenario, we will compare map1 with a map that has different keys.

Example


Output
Are map1 and map5 equal? : false


Comment
Article Tags:
Article Tags:

Explore