Skip to content

๐ŸŒฑ Rust Environment Variables (std::env)

The std::env module allows interacting with the environment at runtime: reading, setting, modifying env vars, accessing CLI args, current dir, etc.


โœ… Get Environment Variable

use std::env;

fn main() {
    // Returns Result<String, VarError>
    match env::var("HOME") {
        Ok(val) => println!("HOME: {}", val),
        Err(e) => println!("Couldn't read HOME: {}", e),
    }
}

โŒ Handle Missing Env Var Gracefully

let path = env::var("MY_CONFIG_PATH").unwrap_or("default/path".to_string());

๐Ÿ”ง Set an Env Var

Only lasts during the current process lifetime

env::set_var("MY_KEY", "my_value");
println!("{}", env::var("MY_KEY").unwrap()); // prints "my_value"

๐Ÿšซ Remove an Env Var

env::remove_var("MY_KEY");

๐Ÿ“œ List All Env Vars

for (key, value) in env::vars() {
    println!("{key} = {value}");
}

๐Ÿงพ Read CLI Args

fn main() {
    for arg in env::args() {
        println!("{}", arg);
    }
}

๐Ÿ“‚ Get Current Directory

let path = env::current_dir().unwrap();
println!("Current dir: {}", path.display());

๐Ÿ” Set Current Directory

env::set_current_dir("/tmp").expect("Failed to change directory");