Build a configuration hierarchy by defining defaults in code, loading overrides from a file, checking environment variables, and finally applying CLI flags in that specific order of precedence.
use std::env;
use std::fs;
fn main() {
// 1. Defaults
let mut config = Config { port: 8080, debug: false };
// 2. File (e.g., config.toml)
if let Ok(content) = fs::read_to_string("config.toml") {
// Parse content and update config.port, config.debug
// config.port = parsed_port;
}
// 3. Environment Variables
if let Ok(port_str) = env::var("APP_PORT") {
config.port = port_str.parse().unwrap_or(config.port);
}
if let Ok(debug_str) = env::var("APP_DEBUG") {
config.debug = debug_str == "true";
}
// 4. CLI Flags (Highest Precedence)
let args: Vec<String> = env::args().collect();
for arg in args.iter().skip(1) {
if arg.starts_with("--port=") {
config.port = arg.trim_start_matches("--port=").parse().unwrap();
} else if arg == "--debug" {
config.debug = true;
}
}
println!("Final Config: port={}, debug={}", config.port, config.debug);
}
struct Config {
port: u16,
debug: bool,
}