Home
Go
maps.Equal and EqualFunc Example
Updated Jan 11, 2025
Dot Net Perls
Maps, 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. Equals, and EqualsFunc, are some of the most useful.
Generic
maps.Copy
Example. This program creates 3 maps (all with string keys and int values) and tests them with Equals and EqualsFunc. The first 2 maps are exactly equal.
Part 1 We create the 2 maps with assignment statements. The string keys and "test" and "bird."
Part 2 We call 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.
Part 3 We create another map, but this time it has the value 0 instead of 100 for the value of the "test" key.
Part 4 With 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
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 11, 2025 (edit link).
Home
Changes
© 2007-2025 Sam Allen