Rust - Load a TOML File
Published: 2022-02-23
Software
The following software was used in this post.
- Rust - 1.58.1
Dependencies
Add the toml crate to Cargo.toml.
Cargo.toml
[dependencies]
toml = "0.5.8"
serde = { version = "1.0.136", features = ["derive"] }TOML File
Create a TOML file named test.toml with the following content.
test.toml
[database]
host = "localhost"
port = 5432
username = "admin"
password = "password"
[server]
host = "0.0.0.0"
port = 8080Lets Get Rusty
Create a struct that mirrors the TOML file structure. The Deserialize macro is used to deserialize the TOML file into the struct.
main.rs
use serde::Deserialize;
use std::fs;
#[derive(Debug, Deserialize)]
struct Config {
database: Database,
server: Server,
}
#[derive(Debug, Deserialize)]
struct Database {
host: String,
port: u16,
username: String,
password: String,
}
#[derive(Debug, Deserialize)]
struct Server {
host: String,
port: u16,
}
fn main() {
// Read the TOML file
let config_str = fs::read_to_string("test.toml").expect("Failed to read file");
// Parse the TOML file
let config: Config = toml::from_str(&config_str).expect("Failed to parse TOML");
// Print the config
println!("{:#?}", config);
}Run the program.
cargo run
# output
Config {
database: Database {
host: "localhost",
port: 5432,
username: "admin",
password: "password",
},
server: Server {
host: "0.0.0.0",
port: 8080,
},
}The TOML file has been successfully loaded into a Rust struct.
Outro
In this post, I showed you how to load a TOML file in Rust using the toml crate.
Links
https://docs.rs/toml/0.5.8/toml/
https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html
https://fettblog.eu/rust-error-handling/
https://www.sheshbabu.com/posts/rust-error-handling/
Tags
#rust