Comparing Maps in Golang
Last Updated :
06 Nov, 2020
In Go language, a map is a powerful, ingenious, and versatile data structure. Golang Maps is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update, or delete with the help of keys.
In Go language, you are allowed to compare two maps with each other using DeepEqual() function provided by the reflect package. This function returns true if both the maps satisfy the following conditions:
- Both maps are nil or non-nil.
- Both maps have the same length.
- Both maps are the same map object or their corresponding keys map to deeply equal values.
Otherwise, this function returns false.
Syntax:
reflect.DeepEqual(a, b)
Here, a and b are maps, and this function checks whether a and b are deeply equal or not, then return boolean type result.
Example:
Go
package main
import (
"fmt"
"reflect"
)
func main() {
map_1 := map [int] string {
200 : "Anita" ,
201 : "Neha" ,
203 : "Suman" ,
204 : "Robin" ,
205 : "Rohit" ,
}
map_2 := map [int] string {
200 : "Anita" ,
201 : "Neha" ,
203 : "Suman" ,
204 : "Robin" ,
205 : "Rohit" ,
206 : "Sumit" ,
}
map_3 := map [int] string {
200 : "Anita" ,
201 : "Neha" ,
203 : "Suman" ,
204 : "Robin" ,
205 : "Rohit" ,
}
map_4 := map [ string ]int{
"Anita" : 200 ,
"Neha" : 201 ,
"Suman" : 203 ,
"Robin" : 204 ,
"Rohit" : 205 ,
}
res1 := reflect.DeepEqual(map_1, map_2)
res2 := reflect.DeepEqual(map_1, map_3)
res3 := reflect.DeepEqual(map_1, map_4)
res4 := reflect.DeepEqual(map_2, map_3)
res5 := reflect.DeepEqual(map_3, map_4)
res6 := reflect.DeepEqual(map_4, map_4)
res7 := reflect.DeepEqual(map_2, map_4)
fmt.Println( "Is Map 1 is equal to Map 2: " , res1)
fmt.Println( "Is Map 1 is equal to Map 3: " , res2)
fmt.Println( "Is Map 1 is equal to Map 4: " , res3)
fmt.Println( "Is Map 2 is equal to Map 3: " , res4)
fmt.Println( "Is Map 3 is equal to Map 4: " , res5)
fmt.Println( "Is Map 4 is equal to Map 4: " , res6)
fmt.Println( "Is Map 2 is equal to Map 4: " , res7)
}
|
Output:
Is Map 1 is equal to Map 2: false
Is Map 1 is equal to Map 3: true
Is Map 1 is equal to Map 4: false
Is Map 2 is equal to Map 3: false
Is Map 3 is equal to Map 4: false
Is Map 4 is equal to Map 4: true
Is Map 2 is equal to Map 4: false
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...