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;
/// Load environment variables from a `.env` file in the current directory.
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; /// Extracts the value of the `RUST_LOG` environment variable. /// If the variable is not set, it defaults to "debug". /// It also demonstrates how to handle optional environment variables /// and how to inspect them at compile-time. 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.217", features = ["derive"] }
use serde::Deserialize;
// Define a Configuration struct that can be deserialized from environment
// variables.
#[derive(Deserialize, Debug)]
struct Configuration {
port: u16,
}
fn main() {
// Deserialize the Configuration struct from environment variables.
// It expects a PORT environment variable to be set.
let c = envy::from_env::<Configuration>()
.expect("Please provide the PORT env variable");
// Deserialize the Configuration struct from environment variables with a
// prefix. It expects a MY_APP__PORT environment variable to be set.
let c2 = envy::prefixed("MY_APP__")
.from_env::<Configuration>()
.expect("Please provide MY_APP__PORT env variable");
println!("c: {:?} c2: {:?}", c, c2);
}