Environment Variables
dotenvy
dotenvy
⮳ forks and supersedes dotenv
⮳.
dotenvy
⮳ is a Rust crate that loads environment variables from a .env file. It's commonly used during development to manage configuration settings without hardcoding them into the application. dotenvy
⮳ parses the .env file, sets the environment variables, and makes them accessible to the application through the standard std::env module. It's a simple but effective way to separate configuration from code and manage different environments (development, testing, production) with different .env files. It's important to note that .env files are typically not used in production environments, where environment variables are usually set directly.
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
Use 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}"); // You may also choose to panic if the env. variable is not set: // Uncomment to test. // let user_env_var = env::var("USER").expect("$USER is not set"); // println!("USER: {user_env_var}"); // Inspect an environment variable at compile-time. // 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
⮳ 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);
}