๐ฑ 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
๐ง 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"