Read environment variables in Rust using std::env::var to retrieve values or handle missing keys.
Use std::env::var to read an environment variable by name, which returns a Result containing the value or an error if it is missing.
use std::env;
fn main() {
let key = "MY_VAR";
match env::var(key) {
Ok(val) => println!("Value: {}", val),
Err(_) => println!("Variable not found"),
}
}
Environment variables are settings stored outside your code that your program can read to change its behavior. Think of them like a configuration file that the operating system manages for you. You use them to switch between modes, like development and production, without rewriting your code.