-
-
Save RandyMcMillan/b6a596bd8920b32cb509b11653b979ca to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::env; | |
fn env_vars() { | |
// Iterate over all environment variables. | |
for (key, value) in env::vars() { | |
println!("{}: {}", key, value); | |
} | |
// You can also filter the environment variables. | |
println!("\nFiltered environment variables:"); | |
for (key, value) in env::vars().filter(|(key, _)| key.starts_with("PATH")) { | |
println!("{}: {}", key, value); | |
} | |
// Get a specific environment variable. | |
if let Ok(path) = env::var("PATH") { | |
println!("\nPATH: {}", path); | |
} else { | |
println!("\nPATH environment variable not found."); | |
} | |
// Get an environment variable, handle missing value gracefully. | |
let user = env::var("USER").unwrap_or_else(|_| String::from("unknown")); | |
println!("\nUser: {}", user); | |
// Using env::vars_os() to get os specific strings. | |
println!("\nOS Specific environment variables:"); | |
for (key_os, value_os) in env::vars_os() { | |
if let (Ok(key_str), Ok(value_str)) = (key_os.into_string(), value_os.into_string()) { | |
println!("{}: {}", key_str, value_str); | |
} else { | |
println!("Non-UTF8 env var"); | |
} | |
} | |
// Using env::var_os for os specific strings | |
if let Some(path_os) = env::var_os("PATH") { | |
if let Ok(path_string) = path_os.into_string() { | |
println!("\nOS PATH: {}", path_string); | |
} else { | |
println!("\nOS PATH env var is not valid UTF-8"); | |
} | |
} else { | |
println!("\nOS PATH env var not found"); | |
} | |
} | |
fn main() { | |
env_vars(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment