Using Command Line Arguments and Environment Variables
The standard library package for working with the environment is std::env
.
Access the process's environment variables
rust
let env_var = std::env::var("VARIABLE");
let env_var = std::env::var("VARIABLE");
Or check the presence of an environment variable
rust
let env_var_exists: bool = env::var("VARIABLE").is_err();
let env_var_exists: bool = env::var("VARIABLE").is_err();
Method 1: Manual
To read arguments from the command line using Rust's standard library use the std::env::args
function.
rust
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
let option = &args[1];
let flag = &args[2];
// -- rest of program --
}
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
let option = &args[1];
let flag = &args[2];
// -- rest of program --
}
Note: The call to args()
returns an iterator which can be converted into a collection using the .collect()
method.
TODO: add section on Clap for CLI programs and then reference this in Essential Crates