lang="en-US"> Playing with env in Rust
Knoldus Blogs

Playing with env in Rust

Reading Time: 3 minutes

Environment variables plays a vital role in setting up a large scale project in real time environment. Environment variables are needed to use the application according to your use case.

Rust also depends on environment variables for application personalization. Using environment variables can be a tricky task, though.

Firstly, we will see how do we set up a environment variable in Rust. There are many ways of using environment variables in Rust. Some are temporary while some are permanent while others reside in the code itself.

We will start with the temporary method first. The first method is to export the variable in a form of key value pair in the terminal itself, like this.

export env_variable=value

This method is a temporary way to do so, as the environment variables vanishes just as the terminal is re-opened.

The permanent way of setting the environment variables is to edit the /etc/environment file and the environment variable key and value.

sudo gedit /etc/environment
ENVIRONMENT_VARIABLE="value"

Getting env variables from a file

We can also get the environment variables from a file saved into the current or parent directory of the project.

use dotenv;
dotenv().expect(".env file not found");
println!("KEY", env::var("VALUE").unwrap());

dotenv function from the crate of the same name helps to load the file with all the environment variables into the current scope.

Setting up the environment variables within Rust Code

The environment variables can be put in the Rust code as well by using env module of std crate. For instance let’s see this example.

env::set_var("KEY", "VALUE");

Inspecting environment variables

Now, how would you check if the environment variables you are using in the application in a way like this resides in the system or not.

use std::env;
fn main() {
let my_env_var: &str = env::var("KEY").unwrap().as_str();
}

When you try to build this code, it will not give you any error. But as soon as you try to run the code by using cargo run, it will panic because the environment variable you want to use will not be present in the system. But, how can you find that at compile time?

This code panics!

The answer to this question is the env! macro.

env! macro

The env! macro helps us to debug the code at the compile time itself.

The difference can be understood by the following code snippet.

fn main() {
let image_path: &'static str = env!("IMAGE_PATH","You forgot to export IMAGE path");
println!("{}",image_path)
}

When you try to run this code, the compiler will not allow you to build the code properly – It will show you an error.

error: You forgot to export IMAGE path
This code does not compile!

The env! macro not only help us to back trace the error at the time of compilation but we can throw our custom Error message.

So, this was all about the env! macro and its usage in RustLang.