How to Use Environment Variables in Rust

Cli
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