env_init 0.1.2

Small crate to help initializing environment structs
Documentation
  • Coverage
  • 71.43%
    15 out of 21 items documented1 out of 18 items with examples
  • Size
  • Source code size: 15.49 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 2.43 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 19s Average build duration of successful builds.
  • all releases: 17s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • LunarParfait/env_init
    0 0 1
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • gaqt

EnvInit

This is a small crate to help initializing environment variable structs, accepting any environment provider and by default automatically parsing the strings into their corresponding types in the struct.

Example Usage with dotenvy

.env

SOME_INT=42
SOME_STR=Hello
SOME_OTHER_STR=World

main.rs

use env_init::{Env, EnvGetter, EnvOnce};

#[derive(Debug)]
pub struct MyEnv {
    some_int: i32,
    some_other_int: i32,
    opt_int: Option<i32>,
    some_str: &'static str,
    owned_str: String
}

impl Env for MyEnv {
    fn new() -> Self {
        // Defining a getter that calls dotenvy::var
        let g = EnvGetter::new(|x| dotenvy::var(x));

        Self {
            some_int: g.owned_var("SOME_INT"),
            some_other_int: g.owned_var_or("SOME_OTHER_INT", 100),
            opt_int: g.owned_var_try("SOME_OPTIONAL_INT").ok(),
            some_str: g.var::<String>("SOME_STR").as_str(),
            owned_str: g.owned_var("SOME_OTHER_STR"),
        }
    }
}

// Our global environment object
pub static ENV: EnvOnce<MyEnv> = EnvOnce::new();

fn main() {
    dotenvy::dotenv().unwrap();
    ENV.init();

    assert_eq!(ENV.some_int, 42);
    assert_eq!(ENV.some_other_int, 100);
    assert_eq!(ENV.opt_int, None);
    assert_eq!(ENV.some_str, "Hello");
    assert_eq!(ENV.owned_str, "World");
}