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

toml Cargo.toml serde

Cargo.toml

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

examples/read-and-parse-cargo-toml/Cargo.toml

[package]
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 https://doc.rust-lang.org/cargo/reference/manifest.html

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

Code

This is the code including the definition of the structs.

examples/read-and-parse-cargo-toml/src/main.rs

#![allow(dead_code)]
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: {}", parsed.package.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

Toml

Author

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