Pass Settings::new().merge_keys(true) to read inherited << fields into your struct.
cargo add oneyaml cargo add serde --features derive
use oneyaml::Settings; #[derive(serde::Deserialize)] struct Config { workers: u32, port: u16, } fn main() -> Result<(), oneyaml::Error> { let yaml = "<<: {workers: 4, port: 8080} port: 9000"; let settings = Settings::new().merge_keys(true); let cfg: Config = oneyaml::from_str_with(yaml, &settings)?; println!("{} workers on port {}", cfg.workers, cfg.port); Ok(()) }
Paste the code above into src/main.rs of a new cargo new example project and cargo run, or unzip the example and cargo run.
Requires Rust 1.85 or later. The example prints:
4 workers on port 9000The merged workers field reads as the integer 4, while the local port overrides the inherited 8080. If a required field is still missing after the merge, deserialization returns an error.
Variations
Merge an anchored defaults mapping
Replace let yaml in main with this input. &base names the defaults and *base refers to them. The output stays the same.
let yaml = "defaults: &base {workers: 4, port: 8080} <<: *base port: 9000";
Related recipes
The short answer
Derive serde::Deserialize for your final struct, then call oneyaml::from_str_with and pass Settings::new().merge_keys(true). The struct declares the fields you want after the merge, not a field named <<. In the example, Serde reads workers from the merged mapping and port from the local mapping. There’s no intermediate YAML Value to edit or convert.
How do YAML merge keys work?
The << merge key copies entries from another mapping into the current mapping where keys aren’t already present. You can write the defaults inline, as the first example does, or reuse a mapping elsewhere in the document by giving it an anchor and referring to it with an alias. Local keys win: port: 9000 remains the port no matter where that local entry appears relative to <<.
Merge keys are an extension, not part of YAML 1.2. If << looks like it’s being ignored, check the reader’s settings before changing the struct. Without merge_keys(true), fields supplied only by << aren’t read: required fields give a missing-field error, and Option fields come out None for structs like this one that ignore unknown keys. Enable just the merge setting when the other YAML 1.2 defaults are what you want.
How do I deserialize merged YAML fields with Serde?
Match your Rust fields to the keys and types you want after expansion. In this example, Serde reads the inherited workers: 4 as a u32, just as it would read a local workers: 4 entry.
An inherited field still has to match its destination type. The merge doesn’t make a missing field optional or turn an invalid port into a valid u16. And if you need to keep the defaults and overrides intact in the source file, use Document to edit the YAML without rewriting its layout. The typed result models the effective settings, not the layout that produced them.