Maps Diff Added Removed Changed

Walk the old map for removals and value changes, the new map for additions, then sort the key slices so diff reports stay reproducible.

GoConfig Management

Code

snippet
package main

import (
	"fmt"
	"sort"
)

func diff(old, new map[string]string) (added, removed, changed []string) {
	for k, v := range old {
		want, ok := new[k]
		if !ok {
			removed = append(removed, k)
		} else if want != v {
			changed = append(changed, k)
		}
	}
	for k := range new {
		if _, ok := old[k]; !ok {
			added = append(added, k)
		}
	}
	return added, removed, changed
}

func main() {
	before := map[string]string{"region": "eu", "replicas": "3", "owner": "ada"}
	after := map[string]string{"region": "us", "replicas": "3", "tier": "gold"}

	added, removed, changed := diff(before, after)

	// map 遍历无序:输出前先排序,报告才可复现
	sort.Strings(added)
	sort.Strings(removed)
	sort.Strings(changed)
	fmt.Println("added:", added)
	fmt.Println("removed:", removed)
	fmt.Println("changed:", changed)
}

Inside the snippet

Maps Diff Added Removed Changed is built around the functions diff and main.

Iteration happens inside for k, v := range old — everything outside it runs once.

Points of care

  • No package manager runs in the flow — every call lands on a built-in API.

Putting it to use

Signature: func diff(old, new map[string]string) (added, removed, changed []string)

Output lines are prefixed (added:, removed:, changed:), making the effect of each step easy to see.

The demo flow inside main is diff — run the file to see it end to end.

The core lines of the flow

for k, v := range old {
	want, ok := new[k]
	if !ok {
		removed = append(removed, k)
	} else if want != v {
		changed = append(changed, k)
	}
}
for k := range new {
	if _, ok := old[k]; !ok {
		added = append(added, k)
	}
}

Interactive Tools for This Topic

FAQ

What does Maps Diff Added Removed Changed print when run?
Running the file directly is enough — expect labeled output lines such as `added:`, `removed:`, `changed:`.