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/ file

Add the following code to your src/ file:

use serde::Serialize;

struct Customer {
    name: String,
    email: String,
    order_id: u32,

fn main() {
    let customer = Customer {
        name: "John".to_string(),
        email: "".to_string(),
        order_id: 123

    let file = std::fs::OpenOptions::new()
        .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
order_id: 123