How to Parse YAML in Rust

Parse YAML in Rust using the serde_yaml crate and the from_str function to deserialize text into structs.

Use the serde_yaml crate to deserialize YAML strings into Rust structs by deriving Deserialize and calling serde_yaml::from_str.

use serde::Deserialize;

#[derive(Deserialize)]
struct Config {
    name: String,
    port: u16,
}

fn main() {
    let yaml = r#"
name: myapp
port: 8080
"#;

    let config: Config = serde_yaml::from_str(yaml).unwrap();
    println!("{}:{}", config.name, config.port);
}

Add serde = { version = "1.0", features = ["derive"] } and serde_yaml = "0.8" to your Cargo.toml dependencies.