![]() |
VOOZH | about |
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.
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)
}
reflect.DeepEqual(a, b)
Table of Content
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.
reflect.DeepEqual(a, b)
Now, let’s explore different scenarios for comparing maps using the same basic example.
In this case, we are comparing map1 and map2, which are identical.
Are map1 and map2 equal? : true
Let’s create a third map with an additional entry to see how the comparison behaves.
Example
Are map1 and map3 equal? : false Are map1 and map2 equal? : true
Here, we will compare map1 with a map that has different key-value pairs.
Example
Are map1 and map4 equal? : false
In this scenario, we will compare map1 with a map that has different keys.
Example
Are map1 and map5 equal? : false