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.

use std::env;

fn main() {
    // To set a key/value pair, use `env::set_var`. To get a
    // value for a key, use `env::var`. This will return
    // a Result<String, VarError> which you can unwrap or handle the error.
    env::set_var("FOO", "1");
    println!("FOO: {}", env::var("FOO").unwrap_or_default());
    println!("BAR: {}", env::var("BAR").unwrap_or_default());

    // Use `env::vars` to list all key/value pairs in the
    // environment. This returns an iterator of (String, String) tuples.
    // Here we print all the keys.
    println!();
    for (key, _) in env::vars() {
        println!("{}", key);
    }
}

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is empty.

$ cargo run
FOO: 1
BAR: 

TERM_PROGRAM
PATH
SHELL
...
FOO

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.

$ BAR=2 cargo run
FOO: 1
BAR: 2
...

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.