-
envcast
Runtime crate providing helper utilities for:- reading environment variables,
- loading values from
.envfiles, - parsing string values into target Rust types.
-
envcast_derive
Procedural macro crate that provides theFromEnvderive macro. It generates aget()method that builds a configuration struct using a prioritized resolution strategy.
Environment-based configuration is a common pattern, but it often leads to repetitive and error-prone code:
- reading environment variables,
- supporting
.envfiles, - defining fallback defaults,
- parsing string values into typed fields.
envcast removes this boilerplate by letting you describe your configuration
as a struct and generating the resolution logic at compile time.
- Environment variable lookup
.envfile support- Custom
.envpath viaDOTENV_CONFIG_FILE - Deterministic value resolution order
- Field-level default values
- Zero runtime reflection
- Works with
OnceLock,lazy_static, andonce_cell - MSRV: Rust 1.70.0
For each struct field, the value is resolved in the following order:
-
Environment variables
- field name as-is (
my_field) - field name uppercased (
MY_FIELD)
- field name as-is (
-
.envfiles- default
.env - custom file specified by
DOTENV_CONFIG_FILE - for each file, both lowercase and uppercase keys are tried
- default
-
#[default = "..."]attribute- the value is converted to a string and parsed via
FromStr
- the value is converted to a string and parsed via
-
Default::default()- final fallback if no value was resolved
use envcast::FromEnv;
#[derive(FromEnv)]
pub struct Config {
#[default = 50]
pub int_field: i32,
#[default = 50.0]
pub float_field: f32,
#[default = "Rust"]
pub string_field: String,
#[default = true]
pub bool_field: bool,
}The macro generates a get() method:
impl Config {
pub fn get() -> Self {
/* generated */
}
}use std::sync::OnceLock;
static CONFIG: OnceLock<Config> = OnceLock::new();
pub fn get_config() -> &'static Config {
CONFIG.get_or_init(Config::get)
}Each field type must implement:
std::str::FromStrDefault
Supported types include:
- integers:
i8,i16,i32,i64,u8,u16,u32,u64 - floats:
f32,f64 boolString- custom types implementing
FromStr
The #[default = "..."] attribute:
- accepts a literal value,
- converts it to a string internally,
- parses it using the field’s
FromStrimplementation.
Example:
#[default = 8080]
port: u16,
#[default = "127.0.0.1"]
host: String,By default, .env is loaded from the project root.
You can override it with:
export DOTENV_CONFIG_FILE=/etc/myapp/config.envIf a value is found but cannot be parsed, the generated code falls back to:
- the field’s
#[default]value, if provided, - otherwise
Default::default().
The code does not panic and does not abort application startup.
See CHANGELOG.md for release notes and version history.
MIT