Back to Blog

Rust TOML Config Parser Tutorial | Parse Settings Files with Serde | Rust by Examples #8

Sandy LaneSandy Lane

Video: Rust TOML Config Parser Tutorial | Parse Settings Files with Serde | Rust by Examples #8 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Rust TOML Config Parser Tutorial | Parse Settings Files with Serde

This tutorial demonstrates how to parse TOML configuration files in Rust using the toml crate combined with serde for deserialization. You'll learn to define nested Rust structs that mirror the TOML file structure, read the config file as a string, and deserialize it into strongly-typed Rust data for safe and easy access.

Code

use serde::Deserialize;
use std::fs;

// Define the top-level config struct matching the TOML structure
#[derive(Debug, Deserialize)]
pub struct AppConfig {
  pub name: String,
  pub version: String,
  pub debug: bool,
  pub database: DatabaseConfig,
  pub server: ServerConfig,
}

// Nested struct for the [database] section
#[derive(Debug, Deserialize)]
pub struct DatabaseConfig {
  pub host: String,
  pub port: u16,
  pub name: String,
}

// Nested struct for the [server] section
#[derive(Debug, Deserialize)]
pub struct ServerConfig {
  pub host: String,
  pub port: u16,
  pub workers: u8,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
  // Read the entire settings.toml file into a string
  let toml_str = fs::read_to_string("settings.toml")?;

  // Parse the TOML string into the AppConfig struct
  let config: AppConfig = toml::from_str(&toml_str)?;

  // Access and print config values
  println!("App: {} v{}", config.name, config.version);
  println!("Debug mode: {}", config.debug);
  println!("Database host: {}:{}", config.database.host, config.database.port);
  println!("Database name: {}", config.database.name);
  println!("Server running on {}:{} with {} workers",
           config.server.host, config.server.port, config.server.workers);

  Ok(())
}

Key Points

  • TOML is a human-friendly configuration format used by Cargo and others.
  • The toml crate parses TOML strings into Rust data structures using serde.
  • Nested TOML sections map naturally to nested Rust structs with Deserialize derive.
  • Reading the config file as a string and then parsing it allows type-safe access to settings.
  • This approach enables easy, maintainable configuration management in Rust projects.