Environment variables with std::env for configuration
Marcus Chen
Jan 2026
1 tab
use std::env;
fn main() {
let port: u16 = env::var("PORT")
.unwrap_or_else(|_| "8080".to_string())
.parse()
.expect("PORT must be a number");
println!("Server will run on port {}", port);
}
1 file · rust
Explain with highlit
Reading environment variables is a common way to configure applications. std::env::var("KEY") returns Result<String, VarError>, which you handle with ? or .unwrap_or_else(). I use env vars for secrets, runtime config, and feature flags. For parsing into types, use .parse() with ?. For optional vars, match on Ok/Err. I centralize env reading in a config struct at startup to catch missing vars early. For complex config, combine env vars with files (using dotenv or envy crates). Environment variables are simple, portable, and well-supported in deployment environments like Docker and Kubernetes.