Skip to content

Commit e1510d5

Browse files
fix: store env vars as vectors
Now can iterate over tuples inside vectors avoiding duplicate output
1 parent cfab316 commit e1510d5

File tree

2 files changed

+28
-9
lines changed

2 files changed

+28
-9
lines changed

.vscode/launch.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@
2222
"args": [],
2323
"cwd": "${workspaceFolder}",
2424
"env": {
25-
"NAME": "pythoninthegrass"
25+
"NAME": "pythoninthegrass",
26+
"FUBAR": "testofferson"
2627
}
2728
},
2829
{

src/main.rs

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,39 @@
11
use dotenvy::dotenv;
22
use std::env;
33

4+
// TODO: only return specific env vars
5+
46
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
616
match dotenv() {
717
Ok(_) => {
818
// 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);
1121
} 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+
}
1330
}
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 {
1735
if key != "NAME" {
18-
println!("{}: {}", key, value);
36+
println!("{}: {}", key, value);
1937
}
2038
}
2139
},

0 commit comments

Comments
 (0)