Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Accessing envrionment variables

  • std::env
  • std::env::var

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

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