env-extractor

Crates.ioenv-extractor
lib.rsenv-extractor
version0.0.7
sourcesrc
created_at2020-08-27 16:05:06.457735
updated_at2020-09-20 07:36:34.099777
descriptionModules to extract environment variables.
homepage
repositoryhttps://github.com/x7c1/plus/tree/master/libs/env-extractor
max_upload_size
id281517
size7,123
Aida.t (x7c1)

documentation

README

env-extractor

Usage

Basic example to extract an environment variable as String :

use env_extractor::{env_var, required};

fn load_path() -> required::Result<String> {
    env_var("PATH").as_required()
}

Another example to use custom type :

fn load_my_path() -> required::Result<MyPath> {
    // Note that this is exactly the same as load_path()
    env_var("PATH").as_required()
}

How to convert is represented using built-in std::str::FromStr :

struct MyPath {
    inner: String,
}
impl FromStr for MyPath {
    type Err = <String as FromStr>::Err;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(MyPath {
            inner: s.to_string(),
        })
    }
}

Of course, required::Result can tell us the key when it's not present (std::env::VarError cannot).

match load_my_path() {
    Ok(path) => println!("path: {}", path.inner),
    Err(NotPresent(key)) => println!("not present: {}", key),
    Err(e) => println!("unexpected error: {:?}", e),
}

Use as_optional() instead when handling optional value :

let sample: Option<MyPath> = env_var("foooooo").as_optional()?;
Commit count: 0

cargo fmt