Use to_value to build a YAML value you can inspect before writing a file.
cargo add oneyaml cargo add serde -F derive
use serde::Serialize; #[derive(Serialize)] struct Server { port: u16, } fn main() -> Result<(), oneyaml::Error> { let server = Server { port: 8080 }; let value = oneyaml::to_value(&server)?; let port = value["port"].as_u64(); println!("Numeric port: {port:?}"); Ok(()) }
Prints:
Numeric port: Some(8080)If a custom Serialize implementation fails, to_value returns an error instead of a partial value.
Unzip the example, then cargo run.
Requires Rust 1.85 or later.
Variations
Write the value as YAML text
Add this line just before Ok(()) to also print the YAML mapping:
print!("{}", oneyaml::to_string(&value)?);Additional output:
port: 8080Related recipes
The short answer
Derive Serde’s Serialize on the struct and call to_value(&server). This produces a YAML Value directly, without serializing to text and parsing it back. Passing a reference leaves the typed struct available for later use. The example looks up the port key and checks that its value is a number rather than the string "8080".
How do I serialize a Rust struct to YAML without making a string?
A named-field struct like Server becomes a mapping. Its field types determine the kind of value each key holds; the u16 in the example becomes a number. This lets you pass a typed settings block into code that works on dynamic YAML. For example, a configuration builder can use the result as a section of a larger mapping before emitting the whole tree.
The mapping uses the names provided by Serde. If the Rust and YAML names differ, use Serde’s rename field attribute on the field. A custom field type must also implement Serialize. The conversion records the serialized data, not the original Rust type: the example’s number doesn’t carry a u16 type label in YAML.
How do I serialize a Rust struct to a YAML string instead?
If you only need text, pass the struct straight to to_string; there’s no need for an intermediate value. If you already built and inspected a Value, pass that value to to_string as in the variation.
A Value is useful for building new data, not for keeping the original layout of a hand-edited file. If you need to preserve comments and formatting while changing a field, use the document editing API instead of replacing the file with newly emitted YAML.