FromEnv

Derive Macro FromEnv 

Source
#[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:

  1. First, it checks for an environment variable matching the field name.
    • If not found, it tries again with the field name converted to uppercase.
  2. If still not found, it attempts to load the variable from a .env file or from a custom file specified via the DOTENV_CONFIG_FILE environment variable, again trying both the original and uppercase field names.
  3. If the value is still unresolved, it looks for a #[default = "..."] attribute on the field.
  4. 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:

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)
 }