| Crates.io | env-extractor |
| lib.rs | env-extractor |
| version | 0.0.7 |
| created_at | 2020-08-27 16:05:06.457735+00 |
| updated_at | 2020-09-20 07:36:34.099777+00 |
| description | Modules to extract environment variables. |
| homepage | |
| repository | https://github.com/x7c1/plus/tree/master/libs/env-extractor |
| max_upload_size | |
| id | 281517 |
| size | 7,123 |
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()?;