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.
Steps to read environment variables in Rust:
- Open a terminal in the Rust binary package root.
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 - Add an environment-variable reader to src/main.rs.
- src/main.rs
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.
- Check that the source compiles.
$ cargo check Checking demo-cli v0.1.0 (/work/demo-cli) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.06sRelated: How to check Rust code with Cargo
- Run the package with the variable set for this command.
$ 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=productionThe 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.
- Run the package with the variable unset.
$ 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 developmentenv -u removes APP_ENV only from the child process. The fallback output comes from the VarError::NotPresent branch.
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.