How to Compare if two Maps are Equal in Golang
Created
Modified
reflect.DeepEqual Function
It first checks if both maps are nil, then it checks if they have the same length before finally checking to see if they have the same set of (key, value) pairs.
package main
import (
"fmt"
"reflect"
)
func main() {
m1 := map[string]int{
"a": 1,
"b": 2,
}
m2 := map[string]int{
"b": 2,
"a": 1,
}
m3 := map[string]int{
"b": 3,
"c": 2,
}
fmt.Println(reflect.DeepEqual(m1, m2)) // true
fmt.Println(reflect.DeepEqual(m1, m3)) // false
}
$ go run main.go true false
Comparison
To test whether two maps contain the same keys and the same associated values, we must write a loop:
package main
import (
"fmt"
)
func main() {
m1 := map[string]int{
"a": 1,
"b": 2,
}
m2 := map[string]int{
"b": 2,
"a": 1,
}
m3 := map[string]int{
"b": 3,
"c": 2,
}
fmt.Println(EqualMap(m1, m2)) // true
fmt.Println(EqualMap(m1, m3)) // false
}
func EqualMap(x, y map[string]int) bool {
if len(x) != len(y) {
return false
}
for k, xv := range x {
if yv, ok := y[k]; !ok || yv != xv {
return false
}
}
return true
}
$ go run main.go true false
Benchmark
After running the benchmark, we receive the following results:
func BenchmarkEqualMap(b *testing.B) {
for i := 0; i < b.N; i++ {
EqualMap(m1, m3) // false
// reflect.DeepEqual(m1, m3)
}
}
$ go test -bench=. --count=1 EqualMap 47.59 ns/op DeepEqual 493.80 ns/op