Configuration
Use case
You need to load settings from files (e.g. TOML) and from the environment (e.g. .env for secrets). Use serde to deserialize config structs and dotenvy to load .env into std::env before reading.
In C#: Like appsettings.json and IConfiguration; .env is like user secrets or env vars in production.
TOML config files
Define a struct with Deserialize and use the toml crate to parse a file into it.
use serde::Deserialize;
use std::fs;
#[derive(Deserialize)]
struct Config {
server: ServerConfig,
}
#[derive(Deserialize)]
struct ServerConfig {
host: String,
port: u16,
}
let content = fs::read_to_string("config.toml")?;
let config: Config = toml::from_str(&content)?;
println!("{}:{}", config.server.host, config.server.port);In C#: Like binding a section to a class with Configuration.GetSection("Server").Get<ServerConfig>().
Loading .env
Call dotenvy::dotenv() at startup (e.g. in main). It loads .env from the current directory into environment variables. Then use std::env::var("KEY") to read them.
dotenvy::dotenv().ok(); // .ok() ignores missing .env
let db_url = std::env::var("DATABASE_URL")?;In C#: Like reading from environment or User Secrets; no built-in .env file in .NET (libraries exist).
Combining TOML and env
Common pattern: load defaults from TOML, override secrets or environment-specific values from env (e.g. DATABASE_URL). Read env after dotenvy::dotenv().
Key takeaway
Use toml::from_str(&fs::read_to_string(path)?)? for TOML config; use dotenvy::dotenv().ok() then std::env::var("KEY") for secrets. Derive Deserialize for config structs.