In Go, you can check if two maps are equal by comparing each key-value pair of the maps. Here is an example of how you can do it:
func mapsAreEqual(map1, map2 map[string]int) bool {
// Check if the maps have the same length
if len(map1) != len(map2) {
return false
}
// Iterate over each key-value pair in map1
for key, value := range map1 {
// Check if the key exists in map2 and has the same value
if v, ok := map2[key]; !ok || v != value {
return false
}
}
return true
}
func main() {
map1 := map[string]int{
"a": 1,
"b": 2,
"c": 3,
}
map2 := map[string]int{
"a": 1,
"b": 2,
"c": 3,
}
if mapsAreEqual(map1, map2) {
fmt.Println("Maps are equal")
} else {
fmt.Println("Maps are not equal")
}
}
In the example above, the mapsAreEqual
function checks if the length of the maps is the same, and then iterates over each key-value pair in map1
. It checks if each key exists in map2
and if the corresponding values are equal. If at any point a mismatch is found, it returns false
. Finally, in the main
function, it calls mapsAreEqual
and prints the appropriate message.