Read and parse Cargo.toml using the toml crate defining our own structs

toml Cargo.toml serde


This is the real Cargo.toml of this project that we are going to parse


name = "read-and-parse-cargo-toml"
version = "0.1.0"
edition = "2021"
rust_version = "1.76"
rust-version = "1.75"

# See more keys and their definitions at

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


This is the code including the definition of the structs.


use serde::Deserialize;
use toml::Value;

#[derive(Deserialize, Debug)]
struct Package {
    name: String,
    version: String,
    edition: Option<String>,

    rust_version: Option<String>,

    #[serde(alias = "rust-version")]
    rust_dash_version: Option<String>,

#[derive(Deserialize, Debug)]
struct Cargo {
    package: Package,
    dependencies: Value

fn main() {
    let filename = "Cargo.toml";
    let content = std::fs::read_to_string(filename).unwrap();
    let parsed: Cargo = toml::from_str(&content).unwrap();
    println!("{:#?}", parsed);
    println!("name: {}",;
    println!("version: {}", parsed.package.version);
    println!("edition: {:?}", parsed.package.edition);
    println!("rust_version: {:?}", parsed.package.rust_version);
    println!("rust-version: {:?}", parsed.package.rust_dash_version);

    println!("dependencies: {:?}", parsed.dependencies);

Related Pages



Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo