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:

  1. 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

  2. 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.

  3. 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.06s
  4. 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=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.

  5. 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 development

    env -u removes APP_ENV only from the child process. The fallback output comes from the VarError::NotPresent branch.