Merge Layered TOML Configs
Recursively merge TOML tables so environment overlays change only the keys they declare while preserving sibling settings.
Code
use toml::Value;
fn merge(base: &mut Value, overlay: &Value) {
match (base, overlay) {
(Value::Table(base_map), Value::Table(overlay_map)) => {
for (key, value) in overlay_map {
match base_map.get_mut(key) {
Some(existing) => merge(existing, value),
None => {
base_map.insert(key.clone(), value.clone());
}
}
}
}
(base_slot, _) => {
*base_slot = overlay.clone();
}
}
}
fn main() -> Result<(), toml::de::Error> {
let base: Value = r#"
[server]
port = 8080
host = "127.0.0.1"
[server.tls]
enabled = false
"#
.parse()?;
let overlay: Value = r#"
[server]
port = 9090
[server.tls]
enabled = true
"#
.parse()?;
let mut merged = base;
merge(&mut merged, &overlay);
let rendered = toml::to_string(&merged).expect("serialize merged config");
println!("{rendered}");
Ok(())
}
What the code does
Merge Layered TOML Configs reduces to the functions merge and main.
Repetition is confined to for (key, value) in overlay_map — the rest of the file is straight-line. Fallible operations return Result, and the ? operator short-circuits errors up to the caller. Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.
Watch out for
toml::Valuemust be installed first — the snippet imports it directly.- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Using it
The entry-point signature is fn merge(base: &mut Value, overlay: &Value)
Launch the file; main takes over and steps through merge.
Key statements
(Value::Table(base_map), Value::Table(overlay_map)) => {
for (key, value) in overlay_map {
match base_map.get_mut(key) {
Some(existing) => merge(existing, value),
None => {
base_map.insert(key.clone(), value.clone());
}
}
}
}
(base_slot, _) => {
*base_slot = overlay.clone();
}
Interactive Tools for This Topic
JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.TOML to JSON ConverterParse TOML configuration into JSON, supporting tables, arrays of tables, inline tables, and basic or literal strings.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.Gitignore Template BuilderCompose clean .gitignore files by combining Node, Python, Go, Rust, Java, OS, IDE, and Docker presets with deduplication and custom rules.
FAQ
- What is the error handling style?
- Through the type system: failures are `Result` variants the caller must consume.
- What does this need from the package registry?
- These are real dependencies: `toml::Value`. Without it the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.