Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created April 3, 2025 12:10
Show Gist options
  • Save rust-play/dd0a7ed343876a9620b0b040b2e23d82 to your computer and use it in GitHub Desktop.
Save rust-play/dd0a7ed343876a9620b0b040b2e23d82 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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");
}
}
use std::fs;
use std::io;
use std::path::Path;
fn cat_cargo_toml() -> Result<(), io::Error> {
let path = Path::new("Cargo.toml"); // Define the path to Cargo.toml
if !path.exists() {
eprintln!("Error: Cargo.toml not found.");
return Err(io::Error::new(io::ErrorKind::NotFound, "Cargo.toml not found"));
}
let contents = fs::read_to_string(path)?; // Read the file's content
println!("{}", contents); // Print the content to standard output
Ok(())
}
fn main() {
env_vars();
if let Err(err) = cat_cargo_toml() {
eprintln!("Error: {}", err);
//Handle error accordingly, exit or other logic.
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::File;
use std::io::Write;
use tempfile::tempdir;
#[test]
fn test_cat_cargo_toml_success() {
let dir = tempdir().unwrap();
let file_path = dir.path().join("Cargo.toml");
let mut file = File::create(&file_path).unwrap();
writeln!(file, "[package]\nname = \"test_package\"\nversion = \"0.1.0\"").unwrap();
let result = cat_cargo_toml();
assert!(result.is_ok());
dir.close().unwrap(); // Clean up the temporary directory
}
#[test]
fn test_cat_cargo_toml_not_found() {
let result = cat_cargo_toml();
assert!(result.is_err());
match result {
Err(e) => assert_eq!(e.kind(), io::ErrorKind::NotFound),
Ok(_) => panic!("Expected error, but got Ok"),
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment