Fill Missing Keys From A Default Map
Layer an override map on top of defaults so present keys win and absent keys keep their default, a common config merge shape.
Code
package main
import (
"fmt"
"sort"
)
func main() {
defaults := map[string]string{
"timeout": "30s",
"retries": "3",
"region": "us-east",
}
overrides := map[string]string{
"retries": "5",
"region": "eu-west",
}
merged := make(map[string]string, len(defaults))
for k, v := range defaults {
merged[k] = v
}
for k, v := range overrides {
// 覆盖优先:存在即替换,缺失则沿用默认
merged[k] = v
}
keys := make([]string, 0, len(merged))
for k := range merged {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Printf("%s=%s\n", k, merged[k])
}
}The logic, line by line
The working surface is the function main — everything else is wiring.
Iteration happens inside for k, v := range defaults — everything outside it runs once.
Watch out for
- The dependency list is empty; the language runtime covers it all.
Applying it
The primary signature is func main()
Statements that matter
for k, v := range overrides {
// 覆盖优先:存在即替换,缺失则沿用默认
merged[k] = v
}
for k, v := range defaults {
merged[k] = v
}
for _, k := range keys {
fmt.Printf("%s=%s\n", k, merged[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.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
FAQ
- How do you run Fill Missing Keys From A Default Map?
- Run it as a complete program — compile or interpret the file directly; there is nothing to install first.
Report a problem with this exampleOpens a pre-filled issue on GitHub.