Skip to main content

How to Read an Environment Variable in Rust

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

Settings that change between computers, such as a database address or an API key, belong in environment variables. Rust reads them with std::env::var, which returns the value as a Result, and unwrap_or_default() turns a missing variable into an empty string.

Syntax​

Syntax
let <value>: String = std::env::var("<NAME>").unwrap_or_default();
let <value>: String = std::env::var("<NAME>").unwrap_or(<default>);
PartWhat it does
std::env::var("<NAME>")Returns Ok with the variable's value as a String, or Err with a VarError when it can't.
.unwrap_or_default()The value, or an empty String on any error.
.unwrap_or(<default>)The value, or the String you pass as <default>.

The standard library's documentation for std::env::var: "Fetches the environment variable key from the current process." It returns VarError::NotPresent when "The variable is not set", and VarError::NotUnicode "if the variable’s value is not valid Unicode".

The Example​

The example reads GREETING with an empty default and prints it with {:?}, which shows the quotes, first with the variable set and then without it.

Prerequisites​

  • Rust, installed with rustup, which comes with Cargo. This guide uses Rust 1.100.0.

Step 1: Create a Project​

Terminal
cargo new demo
cd demo
Output
Creating binary (application) `demo` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

cargo new demo creates a folder named demo with a Cargo.toml file, which describes the project, and src/main.rs, which holds the code. cd demo moves into it.

Step 2: Write the Code​

Replace the contents of src/main.rs with:

src/main.rs, which reads std::env::var("GREETING") with unwrap_or_default into greeting and prints GREETING is: with the value in debug format.

src/main.rs
fn main() {
let greeting = std::env::var("GREETING").unwrap_or_default();
println!("GREETING is: {greeting:?}");
}

Step 3: Set the Variable and Run It​

Set GREETING to Hello and run the program. Then remove the variable and run it again:

Terminal
export GREETING=Hello
cargo run -q
unset GREETING
cargo run -q

A zsh terminal where export GREETING=Hello and cargo run -q print GREETING is: "Hello", and after unset GREETING the same command prints GREETING is: "".

Output
GREETING is: "Hello"
GREETING is: ""

cargo run compiles the program and runs it, and -q hides Cargo's own status lines. With the variable set, var returned "Hello". Without it, var returned an error, and unwrap_or_default() replaced it with "".

What var Returns​

Printing the Result itself, with println!("{:?}", std::env::var("GREETING"));, shows each case:

GREETING isstd::env::var("GREETING") returns
HelloOk("Hello")
set, but emptyOk("")
not setErr(NotPresent)
set to bytes that aren't valid UTF-8Err(NotUnicode("\xFF"))

unwrap_or_default() gives "" for both errors, so use the Result itself when you need to tell "not set" from "empty".

Common Mistakes​

MistakeWhat happensDo this instead
unwrap() on a variable that may be missingthread 'main' (…) panicked at src/main.rs:2:46: then called `Result::unwrap()` on an `Err` value: NotPresentUse unwrap_or_default(), unwrap_or(…) or expect with a clear message
Expecting a numbervar always returns text, a StringConvert it with parse, such as .parse::<u16>()
Setting the variable in one terminal and running the program in anotherThe default: each terminal has its own variablesSet it in the terminal that runs the program

Troubleshooting​

SymptomLikely causeFix
called `Result::unwrap()` on an `Err` value: NotPresentThe variable isn't setSet it, or use a default
The value is always the defaultThe variable isn't set in this terminalSet it as in Step 3

FAQ​

How do I use my own default?​

unwrap_or takes it: std::env::var("PORT").unwrap_or(String::from("8080")) printed 8080 with PORT unset.

Where does cargo run get the variable?​

From the terminal that runs it: Cargo starts your program with the same environment, so a variable you export (or set with $env: in PowerShell) reaches it.

Conclusion​

std::env::var("NAME") returns Ok(value) or an Err that says why there's no value. Add unwrap_or_default() for an empty fallback, or unwrap_or(…) for your own.

Additional Resources​