Equal
Do two maps have the exact same keys and values? This can be discovered with a for
-loop, but the maps.Equal
func
from the "maps" package can check in a more concise way.
Part of the generics implementation in Go, the "maps" package provides some helpful methods for handling maps with any key and value types. Equal
, and EqualFunc
, are some of the most useful.
This program creates 3 maps (all with string
keys and int
values) and tests them with Equal
and EqualFunc
. The first 2 maps are exactly equal.
string
keys and "test" and "bird."maps.Equal
which accesses the "maps" package method. We pass 2 arguments (the 2 maps) and it tells us the maps are in fact equal.maps.EqualFunc
, we must pass a function that tells whether two values of different maps (at the same key) are equal.package main
import (
"fmt"
"maps"
)
func main() {
// Part 1: create 2 maps that have the same keys and values.
map1 := map[string]int{}
map1["test"] = 100
map1["bird"] = 200
map2 := map[string]int{}
map2["test"] = 100
map2["bird"] = 200
// Part 2: use maps.Equal to test if the 2 maps are equal.
if maps.Equal(map1, map2) {
fmt.Println("Maps are equal!")
}
// Part 3: create a map with the same keys, but a different value.
map3 := map[string]int{}
map3["test"] = 0
map3["bird"] = 200
// Part 4: use maps.EqualFunc to add special logic to consider maps equal.
if maps.EqualFunc(map2, map3, func(v1 int, v2 int) bool {
// Consider a 0 value to always be equal.
return v2 == 0 || v1 == v2;
}) {
fmt.Println("Maps are equal with EqualFunc")
}
}Maps are equal!
Maps are equal with EqualFunc
With the maps package, we can access useful methods like Equal
and EqualFunc
, which make it easier to test maps for equivalence. Custom logic can be added with EqualFunc
.