❮ TOML
❯
Reading a TOML file
examples/toml/toml-read/Cargo.toml
[package] name = "toml-read" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] toml = "0.7.6" serde = { version = '1.0', features = ['derive'] }
examples/toml/toml-read/src/main.rs
use serde::Deserialize; use toml::Table; #[derive(Deserialize)] #[allow(dead_code)] struct Config { name: String, year: u16, input: Input, output: Output, dependencies: Table, } #[derive(Deserialize)] #[allow(dead_code)] struct Input { name: String, year: Option<u16>, } #[derive(Deserialize)] #[allow(dead_code)] struct Output { name: String, year: Option<u16>, } fn main() { parse_toml(); } fn parse_toml() { let text = String::from( " name = 'bar' year = 2023 [input] name = \"some input\" year = 1024 [output] name = 'other thing' [dependencies] toml = '0.5' yaml = '0.9' serde = { version = '1.0', features = ['derive'] } ", ); let config: Config = toml::from_str(&text).unwrap(); println!("{}", config.name); println!("{}", config.year); println!("{}", config.input.name); match config.input.year { Some(value) => println!("input.year: {}", value), None => println!("input.year is missing"), }; println!("{}", config.output.name); match config.output.year { Some(value) => println!("output.year: {}", value), None => println!("output.year is missing"), }; //println!("{}", config.dependencies); for (k, v) in config.dependencies.iter() { println!("{} -> {}", k, v); } println!("{}", config.dependencies["serde"]["features"][0]); println!("{}", config.dependencies["serde"]["version"]); }