#[derive(FromEnv)]
{
// Attributes available to this derive:
#[default]
}
Expand description
Procedural macro that generates a get method for a struct, resolving each field’s value
based on a prioritized lookup strategy:
- First, it checks for an environment variable matching the field name.
- If not found, it tries again with the field name converted to uppercase.
- If still not found, it attempts to load the variable from a
.envfile or from a custom file specified via theDOTENV_CONFIG_FILEenvironment variable, again trying both the original and uppercase field names. - If the value is still unresolved, it looks for a
#[default = "..."]attribute on the field. - Finally, if none of the above yields a value, it falls back to the type’s default
(
Default::default()).
Each field’s type must implement the following traits:
std::str::FromStr: to parse the string from env/.env.Default: to provide a fallback value.
The generated get method returns a new instance of the struct with all fields populated
according to this resolution order.
§Example
// file config.rs
use std::sync::OnceLock;
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,
}
static CONFIG: OnceLock<Config> = OnceLock::new();
pub fn get_config() -> &'static Config {
CONFIG.get_or_init(Config::get)
}