Updated November 2026: Updated for the Rust 2024 edition, in which set_var and remove_var are unsafe. Also added .env loading with dotenvy and replaced the unmaintained envy crate with config.

The Rust standard library puts everything you need for environment variables in std::env. In this post I show how to read and set them, why set_var has been unsafe since the Rust 2024 edition, how to load a .env file, and how to deserialize environment variables into a typed configuration struct.

Read an environment variable in Rust

env::var returns a Result<String, VarError>. The error tells you whether the variable is missing (VarError::NotPresent) or holds a value that is not valid Unicode (VarError::NotUnicode):

RUST
use std::env;

fn main() {
    match env::var("USER") {
        Ok(user) => println!("USER is {user}"),
        Err(env::VarError::NotPresent) => eprintln!("USER is not set"),
        Err(env::VarError::NotUnicode(raw)) => eprintln!("USER is not valid Unicode: {raw:?}"),
    }
}

Most of the time I want a typed value with a sensible default. Chaining ok(), parse() and unwrap_or() does the job:

RUST
use std::env;

fn main() {
    let port: u16 = env::var("PORT")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(8080);

    println!("Listening on port {port}");
}

Keep in mind that this silently falls back to 8080 if PORT holds garbage. If you’d rather fail loudly, handle the parse error explicitly.

If a value might not be valid Unicode (paths on Unix, for example), use env::var_os. It returns an Option<OsString> and does not validate anything:

RUST
use std::{env, path::PathBuf};

fn main() {
    let home = env::var_os("HOME")
        .map(PathBuf::from)
        .expect("HOME is not set");

    println!("Home directory: {}", home.display());
}

Read environment variables at compile time

The env! and option_env! macros read an environment variable when the code is compiled, and bake the value into the binary. Changing the variable later at runtime has no effect. Cargo sets a bunch of variables for every build, which makes this handy for version information:

RUST
fn main() {
    // Cargo sets CARGO_PKG_VERSION for every build
    let version = env!("CARGO_PKG_VERSION");

    // None if GIT_SHA was not set during the build
    let commit = option_env!("GIT_SHA").unwrap_or("unknown");

    println!("v{version} ({commit})");
}

If the variable is missing at build time, env! stops the compilation. You can pass a custom error message as the second argument:

RUST
let token = env!("API_TOKEN", "Set API_TOKEN when building this binary");
// error: Set API_TOKEN when building this binary

Read all environment variables

env::vars() returns an iterator over all (String, String) pairs of the current process. I use it mostly to collect everything with an app-specific prefix:

RUST
use std::env;

fn main() {
    let app_vars: Vec<(String, String)> = env::vars()
        .filter(|(key, _)| key.starts_with("MYAPP_"))
        .collect();

    println!("{app_vars:?}");
}

env::vars() panics if any key or value is not valid Unicode. If you can’t rule that out, use env::vars_os(), which yields OsStrings:

RUST
use std::env;

fn main() {
    for (key, value) in env::vars_os() {
        println!("{}={}", key.display(), value.display());
    }
}

Set and remove environment variables (unsafe since Rust 2024)

env::set_var and env::remove_var change the environment of the currently running process. Since the Rust 2024 edition (Rust 1.85), both are unsafe functions. Calling them like before no longer compiles:

TEXT
error[E0133]: call to unsafe function `set_var` is unsafe and requires unsafe block

You have to wrap the call in an unsafe block and, by convention, write down why it is sound:

RUST
use std::env;

fn main() {
    // SAFETY: no other threads have been spawned yet
    unsafe {
        env::set_var("MYAPP_DEBUG", "1");
        env::remove_var("MYAPP_LEGACY_MODE");
    }

    println!("{:?}", env::var("MYAPP_DEBUG"));
}

Both functions still panic if the key is empty or contains = or \0, or if the value contains \0.

Why set_var is unsafe

The process environment is one global block of memory managed by the C library. On Linux, macOS and other Unix systems, reading it with getenv while another thread modifies it with setenv is not thread-safe: the reader may end up with a pointer to freed memory. Rust guards its own std::env functions with a lock, but plenty of code reads the environment directly without that lock. libc does it during DNS lookups (which std::net::ToSocketAddrs relies on) and for time zones, and so do C libraries you link against.

You can’t know which of those functions run on other threads, so the compiler can’t check this for you. The set_var docs are blunt about it: it is sound in single-threaded programs and always on Windows, but in multi-threaded programs on other operating systems the only sound option is not to call set_var or remove_var at all.

How I handle it

  • Don’t mutate your own environment. Read the configuration once at startup into a struct and pass it around. That is easier to test anyway.
  • Configure child processes with Command. Command::env and Command::env_remove only affect the child, and they are safe:
RUST
use std::process::Command;

fn main() {
    let status = Command::new("printenv")
        .arg("MYAPP_DEBUG")
        .env("MYAPP_DEBUG", "1")
        .env_remove("MYAPP_LEGACY_MODE")
        .status()
        .expect("failed to run printenv");

    println!("printenv exited with {status}");
}
  • If you must set a variable, do it first thing in main. Watch out for async runtimes: #[tokio::main] starts the runtime and its worker threads before your code runs. Use a plain main, set the variable, and build the runtime afterwards:
RUST
fn main() {
    // SAFETY: the Tokio runtime and its worker threads do not exist yet
    unsafe { std::env::set_var("MYAPP_MODE", "server") };

    tokio::runtime::Runtime::new()
        .expect("failed to build Tokio runtime")
        .block_on(run());
}

async fn run() {
    println!("mode: {}", std::env::var("MYAPP_MODE").unwrap());
}
  • Don’t call set_var in tests. cargo test runs tests in parallel on multiple threads. Make the code under test take its values as parameters instead.

If you migrate an older crate with cargo fix --edition, it wraps existing calls in unsafe blocks and adds a FIXME: Audit that the environment access only happens in single-threaded code. comment. Take that FIXME seriously.

Load a .env file with dotenvy

For local development I keep variables in a .env file. The original dotenv crate is unmaintained (RUSTSEC-2021-0141 ), so I use its fork dotenvy :

TOML
[dependencies]
dotenvy = "0.15"
RUST
fn main() {
    // Loads .env into the process environment (via set_var).
    // Call it first, before anything spawns threads.
    dotenvy::dotenv().ok();

    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL is not set");
    println!("Connecting to {database_url}");
}

dotenvy::dotenv() does not overwrite variables that are already set. It is a safe function, but it calls set_var internally, so the rules from above apply even though the compiler won’t remind you. If you only need the values, dotenvy::dotenv_iter() reads the file without touching the environment at all:

RUST
use std::collections::HashMap;

fn main() -> Result<(), dotenvy::Error> {
    let vars: HashMap<String, String> = dotenvy::dotenv_iter()?.collect::<Result<_, _>>()?;

    println!("DATABASE_URL from .env: {:?}", vars.get("DATABASE_URL"));
    Ok(())
}

Deserialize environment variables into a struct

Parsing every variable by hand gets tedious quickly. In the original version of this post I used envy, but envy hasn’t had a release since January 2021. Today I use the actively maintained config crate together with serde:

TOML
[dependencies]
config = "0.15"
serde = { version = "1", features = ["derive"] }

Environment::with_prefix("MYAPP") picks up every variable starting with MYAPP_ and strips the prefix, so MYAPP_PORT becomes port and MYAPP_ITEMS_PER_PAGE becomes items_per_page. set_default provides fallback values:

RUST
use config::{Config, ConfigError, Environment};
use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct Settings {
    port: u16,
    items_per_page: u16,
}

fn main() -> Result<(), ConfigError> {
    let settings: Settings = Config::builder()
        .set_default("port", 8080)?
        .set_default("items_per_page", 50)?
        .add_source(Environment::with_prefix("MYAPP"))
        .build()?
        .try_deserialize()?;

    println!("Port {}, {} items per page", settings.port, settings.items_per_page);
    Ok(())
}
BASH
MYAPP_PORT=3000 MYAPP_ITEMS_PER_PAGE=25 cargo run
# Port 3000, 25 items per page

MYAPP_PORT=nope cargo run
# Error: invalid type: string "nope", expected an integer for key `port` in the environment

Invalid values fail with a clear error instead of a silent fallback. And because config can layer sources, you can add a config file later and keep environment variables as overrides.

Conclusion

Reading environment variables in Rust is easy and safe. Setting them is not, and since Rust 2024 the compiler makes you say so. Read your configuration once at startup, load .env files before any thread exists, and use Command::env for child processes.