Accessing envrionment variables


We can access the environment variables from Rust using the std::env::var function. It returns a Result.


examples/other/get-environment-variable/src/main.rs
use std::env;

fn main() {
    for name in ["PATH", "RUST"] {
        println!("Checking {name}");
        match env::var(name) {
            Ok(val) => println!("{name}={val}"),
            Err(err) => println!("Environment variable {name} does not exist.\n{err}"),
        }
    }
}

Run as


cargo run
RUST=42 cargo run