Read environment variables in Rust using std::env::var and handle the Result to access system settings dynamically.
Use std::env::var to read an environment variable by name, which returns a Result you can handle with unwrap or match.
use std::env;
fn main() {
let home = env::var("HOME").expect("HOME must be set");
println!("Home directory: {home}");
}
Set the variable in your shell before running the program:
export HOME=/home/user
rustc main.rs && ./main
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 that tell your app where to find files or what settings to use without hardcoding them. You use them to keep your code flexible so it works in different environments like your laptop or a server.