How to Use Serde with YAML Files in Rust

Use the serde_yaml crate with serde derive macros to serialize and deserialize Rust structs to and from YAML strings.

Add the serde_yaml crate to your dependencies and use serde_yaml::from_str to deserialize or serde_yaml::to_string to serialize your structs.

[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_yaml = "0.8"
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct Config {
    name: String,
    count: u32,
}

fn main() {
    let yaml = r#"name: my_config
count: 42"#;
    let config: Config = serde_yaml::from_str(yaml).unwrap();
    println!("{}", config.name);
    
    let output = serde_yaml::to_string(&config).unwrap();
    println!("{}", output);
}