Merge Layered TOML Configs

Recursively merge TOML tables so environment overlays change only the keys they declare while preserving sibling settings.

RustConfig Management

Code

rustsnippet
47 lines
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::Value must be installed first — the snippet imports it directly.
  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

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

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.