How to Compare Maps in Go

1. Introduction

Comparing maps is a common necessity in programming. In Go, you might need to check if two maps are equal - that is, they have the same keys and corresponding values. Go doesn't provide a built-in method for this, so it must be done manually. This blog post demonstrates how to compare two maps for equality in Go.

2. Program Steps

1. Create two maps to compare.

2. Write a function to determine if two maps are equal.

3. Use the function to compare the maps and print the result.

3. Code Program

package main

import "fmt"

// isEqual compares two maps for equality
func isEqual(map1, map2 map[string]int) bool {
	if len(map1) != len(map2) {
		return false
	}
	for k, v := range map1 {
		if value, ok := map2[k]; !ok || value != v {
			return false
		}
	}
	return true
}

func main() {
	// Step 1: Create two maps
	mapA := map[string]int{"a": 1, "b": 2, "c": 3}
	mapB := map[string]int{"a": 1, "b": 2, "c": 3}
	mapC := map[string]int{"a": 1, "b": 2, "c": 4} // Different value for key "c"

	// Step 2 and 3: Use the isEqual function to compare the maps
	fmt.Println("mapA == mapB:", isEqual(mapA, mapB))
	fmt.Println("mapA == mapC:", isEqual(mapA, mapC))
}

Output:

mapA == mapB: true
mapA == mapC: false

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" - Imports the Format package for input and output operations.

3. isEqual - A function that takes two maps as parameters and compares them for equality. It checks if they are the same length and if all corresponding key-value pairs are equal.

4. mapA and mapB are declared with identical key-value pairs, while mapC has a different value for one of the keys.

5. isEqual is called with mapA and mapB, and then with mapA and mapC, to determine if the maps are equal.

6. fmt.Println prints the results of the comparisons to the console.

7. The output indicates that mapA and mapB are equal, while mapA and mapC are not, due to the different value associated with the key "c".


Comments