Runtime configuration often reaches a Rust program through the process environment rather than command-line arguments or checked-in files. Reading a variable with the standard library keeps deployment-specific values outside the binary while still letting the program choose a fallback when the variable is absent.
std::env::var fetches one key from the current process and returns Result<String, VarError>. Match on that result when a missing value should mean default configuration but invalid data should stop the program.
APP_ENV is a neutral application mode name for the runtime check. Replace it with the variable your application reads, and use command-scoped values while testing so the host shell profile and long-lived session environment stay unchanged.
The directory should contain the Cargo.toml file for the package. Create a package first if needed.
Related: How to create a Rust project with Cargo
use std::env; fn main() { match env::var("APP_ENV") { Ok(value) => println!("APP_ENV={value}"), Err(env::VarError::NotPresent) => { println!("APP_ENV is not set; using development") } Err(env::VarError::NotUnicode(_)) => { eprintln!("APP_ENV is not valid Unicode"); std::process::exit(1); } } }
std::env::var reads runtime values. Use std::env::var_os when the value may contain non-Unicode data, and use env! or option_env! only for values read while compiling the binary.
$ cargo check
Checking demo-cli v0.1.0 (/work/demo-cli)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.06s
Related: How to check Rust code with Cargo
$ APP_ENV=production cargo run
Compiling demo-cli v0.1.0 (/work/demo-cli)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.13s
Running `target/debug/demo-cli`
APP_ENV=production
The prefix assignment sets APP_ENV only for this cargo run command in POSIX shells. In PowerShell, set $Env:APP_ENV = 'production' before running Cargo and remove it after testing.
$ env -u APP_ENV cargo run
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
Running `target/debug/demo-cli`
APP_ENV is not set; using development
env -u removes APP_ENV only from the child process. The fallback output comes from the VarError::NotPresent branch.