Go 1.21 added a package to the standard library called maps that contains helper functions for working with maps. Two functions in the package are useful for comparing if two maps are equal, maps.Equal and maps.EqualFunc. They are analogous to the slices.Equal and slices.EqualFunc functions. Use maps.Equal when the values in the map are comparable (as previously mentioned, the keys in a map are required to be comparable):
m := map[string]int{
"hello": 5,
"world": 10,
}
n := map[string]int{
"world": 10,
"hello": 5,
}
fmt.Println(maps.Equal(m, n)) // prints true
If the values are not comparable, use maps.EqualFunc to provide a function that determines equality. Try out this example on The Go Playground:
m := map[string][]int{
"team_a": []int{8, 6, 7},
"team_b": []int{5, 3, 0, 9},
}
n := map[string][]int{
"team_a": []int{8, 6, 7},
"team_b": []int{5, 3, 0, 9},
}
fmt.Println(maps.EqualFunc(m, n, slices.Equal)) // prints true
If you want a different definition of equality than what Go provides by default, you can use maps.EqualFunc (or slices.EqualFunc) with a comparable type. For example, you could implement a case-insensitive comparison of map values. Try it out on The Go Playground:
m := map[int]string{
10: "hello",
20: "goodbye",
30: "peace",
}
n := map[int]string{
10: "HELLO",
20: "GOODBYE",
30: "PEACE",
}
fmt.Println(maps.EqualFunc(m, n, strings.EqualFold)) // prints true