Environment variables

RecipeCratesCategories
dotenvydotenvycat-config
std::envstdcat-config
envyenvycat-config

dotenvy

dotenvy dotenvy-crates.io dotenvy-github dotenvy-lib.rs

dotenvy⮳ forks and supersedes dotenv⮳.

use std::env;

use anyhow::Result;

fn main() -> Result<()> {
    // Load environment variables from .env file.
    // Fails if .env file not found, not readable or invalid.
    // If variables with the same names already exist in the environment,
    // their values will be preserved. If multiple declarations for the
    // same environment variable exist in your .env file, the first one is
    // applied.
    dotenvy::dotenv()?;
    // OR: dotenvy::dotenv().ok();

    for (key, value) in env::vars() {
        println!("{key}: {value}");
    }

    Ok(())
}

std::env

std cat-config

To retrieve a single environment variable,

use std::env;

fn env_extract() -> String {
    let log_env_var = env::var("RUST_LOG").unwrap_or_else(|_| "debug".into());
    println!("RUST_LOG: {log_env_var}");

    let user_env_var = env::var("USER").expect("$USER is not set");
    println!("USER: {user_env_var}");

    // Inspect an environment variable at compile-time.
    // Uncomment to test.
    // let shell = env!("SHELL", "$SHELL is not set");

    let optional_value = option_env!("SHELL");

    optional_value.unwrap_or("no shell set").to_string()
}

fn main() {
    println!("SHELL: {}", env_extract());
}

Working with environment variables in Rust

envy

envy envy-crates.io envy-github envy-lib.rs cat-config

envy can deserialize environment variables into type-safe structs.

[dependencies]
envy = "0.4"
serde = { version = "1.0.216", features = ["derive"] }
use serde::Deserialize;

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

fn main() {
    let c = envy::from_env::<Configuration>()
        .expect("Please provide the PORT env variable");

    let c2 = envy::prefixed("MY_APP__")
        .from_env::<Configuration>()
        .expect("Please provide MY_APP__PORT env variable");

    println!("c: {:?} c2: {:?}", c, c2);
}

See Also

dotenv