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 missing.
use std::env;
fn main() {
let key = "MY_VAR";
match env::var(key) {
Ok(val) => println!("Value: {}", val),
Err(_) => println!("Variable not set"),
}
}
Environment variables are settings stored outside your code that your program can read to change its behavior. Think of them like sticky notes on your computer screen that tell your app where to find files or which mode to run in. You use them to configure your software without rewriting the code every time you move it to a new computer.