|
1 | 1 | use dotenvy::dotenv; |
2 | 2 | use std::env; |
3 | 3 |
|
| 4 | +// TODO: only return specific env vars |
| 5 | + |
4 | 6 | fn main() { |
5 | | - // Load .env file |
| 7 | + // Store environment variables in a vector |
| 8 | + let env_vars: Vec<_> = env::vars().collect(); |
| 9 | + |
| 10 | + // dotenvy iterator returns result, unwrap to get the value, map |
| 11 | + // extracts the value from the result, and collect key/value |
| 12 | + // pairs into a vector |
| 13 | + let dotenv_vars: Vec<_> = dotenvy::dotenv_iter().unwrap().map(|x| x.unwrap()).collect(); |
| 14 | + |
| 15 | + // Print env vars to stdout |
6 | 16 | match dotenv() { |
7 | 17 | Ok(_) => { |
8 | 18 | // If .env file loaded successfully, greet the user |
9 | | - if let Some(name) = env::var("NAME").ok() { |
10 | | - println!("Hello, {}!", name); |
| 19 | + if let Some((_, value)) = env_vars.iter().find(|(key, _)| key == "NAME") { |
| 20 | + println!("Hello, {}!\n", value); |
11 | 21 | } else { |
12 | | - println!("Hello, world!"); |
| 22 | + println!("Hello, world!\n"); |
| 23 | + } |
| 24 | + // read env vars from env::vars() |
| 25 | + println!("env vars:"); |
| 26 | + for (key, value) in &env_vars { |
| 27 | + if key != "NAME" { |
| 28 | + println!("{}: {}", key, value); |
| 29 | + } |
13 | 30 | } |
14 | | - // read remaining env vars other than NAME |
15 | | - for item in dotenvy::dotenv_iter().unwrap() { |
16 | | - let (key, value) = item.unwrap(); |
| 31 | + println!(); |
| 32 | + // read env vars from dotenvy::dotenv_iter() |
| 33 | + println!("dotenv vars:"); |
| 34 | + for (key, value) in &dotenv_vars { |
17 | 35 | if key != "NAME" { |
18 | | - println!("{}: {}", key, value); |
| 36 | + println!("{}: {}", key, value); |
19 | 37 | } |
20 | 38 | } |
21 | 39 | }, |
|
0 commit comments