How to Use Serde with TOML Files in Rust

Use the toml crate with serde to parse TOML configuration files into Rust structs by deriving Deserialize.

Add the toml crate to your Cargo.toml dependencies and use toml::from_str to deserialize TOML strings into Rust structs annotated with #[derive(serde::Deserialize)]. The toml crate is already used in the provided context (version 0.8.12) and relies on serde for serialization logic.

use serde::Deserialize;

#[derive(Deserialize, Debug)]
struct Config {
    title: String,
    edition: String,
}

fn main() {
    let toml_str = r#"
        title = "The Rust Programming Language"
        edition = "2024"
    "#;
    let config: Config = toml::from_str(toml_str).unwrap();
    println!("{:#?}", config);
}

To use this, ensure your Cargo.toml includes:

[dependencies]
toml = "0.8.12"
serde = { version = "1.0", features = ["derive"] }

Then run cargo run to execute the code.