Create a yaml file from a struct in rust

Let's create a yaml file from a struct in rust programming language.

Create a new rust project

cargo new my-yaml-generator

Add serde dependencies to your project

Add the following lines in Cargo.toml file under [dependencies] group

serde = { version = "1", features = ["derive"] }
serde_yaml = "0.8"

Create src/main.rs file

Add the following code to your src/main.rs file:

use serde::Serialize;

#[derive(Serialize)]
struct Customer {
    name: String,
    email: String,
    order_id: u32,
}

fn main() {
    let customer = Customer {
        name: "John".to_string(),
        email: "john@doe.com".to_string(),
        order_id: 123
    };

    let file = std::fs::OpenOptions::new()
        .write(true)
        .create(true)
        .open("customer.yaml")
        .expect("Couldn't open file");

    serde_yaml::to_writer(file, &customer).unwrap();
}

Run the following command to run the project:

cargo run

If everything goes well and you don't have any error in the code, then you should see a new customer.yaml file generated with the following content:

---
name: John
email: john@doe.com
order_id: 123