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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Date Difference CalculatorCalculate the number of days, weeks, whole months, and years between two ISO dates, computed in UTC.Diff Ignoring WhitespaceCompare two blocks of text line by line and separate true differences from lines that differ only in spacing, indentation, or line endings.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.