How to serialize to TOML with serde

Serialize Rust structs to TOML strings using the toml crate and serde Serialize derive macro.

Use toml::to_string() or toml::to_string_pretty() from the toml crate to serialize a struct into a TOML string. Ensure your struct derives serde::Serialize.

use serde::Serialize;

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

fn main() {
    let config = Config { name: "test".to_string(), value: 42 };
    let toml_str = toml::to_string(&config).unwrap();
    println!("{}", toml_str);
}

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