Environment variables

Dotenvy

dotenvy cat-config

dotenvy⮳ 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.
    dotenvy::dotenv()?;

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

    Ok(())
}

std::env

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 cat-config

envy can deserialize environment variables into type-safe structs.

[dependencies]
envy = "0.4"
serde = { version = "1.0", 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

cat-config

dotenv