Rust, Software Development

Rust Environment Variables – Set, Update, List And Delete

This short post shows how to use Rust to work with environment variables in Rust codes. We could retrieve, list, update, and even delete environment variables. All this is possible using functions from the std::env module.

List Environment Variables

The following codes list all environment variables available in the current host machine. First, we need to import the std::env module using the use keyword on line 1. Then, retrieve the environment variables using the vars() function which returns an instance of Vars.

The struct Vars implements the Iterator trait. Therefore, we can loop through its content and display the key-value data in line 6. The codes generate the following output.

Get Environment Variable

Sometimes, we want to retrieve a particular environment variable. If Rust has the vars() function to retrieve a list of environment variables, it also has the var(key) function to retrieve the value of a specific environment variable. Consider the following example.

The environment variable is defined because we had installed Rust in our host machine. If we run the codes, we get the following output.

The var(key) function returns a Result<String, VarError>. Therefore, we can also validate if the environment variable is available using an if-else statement. In line 6, we can either use the is_ok or is_error function. If CARGO_HOME  was undefined and we did not have the if-else  statement, we would have this run-time error:

Set Environment Variable

We can also define with a value or update an environment variable in Rust using the set_var(key, value) function. Consider the following sample codes.

The codes output the following.

Delete a Variable

We can also delete an environment variable in Rust using the remove_var(key) function. This function does not return anything, therefore, no way to check whether the deletion was successful or not.

The codes generate the following output.

In summary, we can use Rust codes to work in environment variables using the std::env module. The module has functions our codes can use to define, update or delete environment variables from our applications.

We used Rust 1.52.1 to test all the codes in this post.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like