Environment Variables in Rust
Environment variables are a universal mechanism for conveying configuration information to Unix programs. Let’s look at how to set, get, and list environment variables in Rust.
Running the program shows that we pick up the value for FOO
that we set in the program, but that BAR
is empty.
The list of keys in the environment will depend on your particular machine.
If we set BAR
in the environment first, the running program picks that value up.
In Rust, we use the std::env
module to work with environment variables. The env::set_var
function is used to set environment variables, while env::var
is used to retrieve them. The env::vars
function returns an iterator over all environment variables.
Note that in Rust, getting an environment variable returns a Result
, which we need to handle. In this example, we’re using unwrap_or_default()
to provide a default empty string if the variable doesn’t exist.