VarError::NotPresent
RustERRORCommonEnvironment

Environment variable not set

Quick Answer

Provide a default with unwrap_or, or fail fast with a clear error message.

What this means

std::env::var() returned NotPresent because the named environment variable is not defined in the current process environment.

Why it happens
  1. 1Variable not exported in the shell
  2. 2Running in a minimal CI/container environment
  3. 3Typo in variable name

Fix

Default value

Default value
let host = std::env::var("HOST").unwrap_or_else(|_| "localhost".to_string());

Why this works

unwrap_or_else provides a fallback without panicking on NotPresent.

Code examples
Triggerrust
std::env::var("MISSING_VAR")?; // VarError::NotPresent
Required varrust
let key = std::env::var("API_KEY").expect("API_KEY must be set");
Same error in other languages
Sources

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Rust errors