Interacting with environment variables
According to the Twelve-Factor App (https://12factor.net/), you should store your configuration in the environment (https://12factor.net/config). This means that you should pass values that could change between deployments, such as ports, domains, or database handles, as environment variables. Many programs also use environment variables to communicate with each other.
How to do it...
In the
bin
folder, create a file calledenv_vars.rs
Add the following code and run it with
cargo run --bin env_vars
:
1 use std::env; 2 3 fn main() { 4 // We can iterate over all the env vars for the current process 5 println!("Listing all env vars:"); 6 for (key, val) in env::vars() { 7 println!("{}: {}", key, val); 8 } 9 10 let key = "PORT"; 11 println!("Setting env var {}", key); 12 // Setting an env var for the current process 13 env::set_var(key, "8080"); 14 15 print_env_var(key); 16 17 // Removing an env var for the current process 18 println!("Removing env var {}", key); 19 env::remove_var(key); 20 21 print_env_var(key); 22 } 23 24 fn print_env_var(key: &str) { 25 // Accessing an env var 26 match env::var(key) { 27 Ok(val) => println!("{}: {}", key, val), 28 Err(e) => println!("Couldn't print env var {}: {}", key, e), 29 } 30 }
How it works...
With env::vars()
, we can access an iterator over all the env var
that were set for the current process at the time of execution [6]. This list is pretty huge though, as you'll see when running the code, and for the most part, irrelevant for us.
It's more practical to access a single env var
with env::var()
[26], which returns an Err
if the requested var is either not present or doesn't contain valid Unicode. We can see this in action in line [21], where we try to print a variable that we just deleted.
Because your env::var
returns a Result
, you can easily set up default values for them by using unwrap_or_default
. One real-life example of this, involving the address of a running instance of the popular Redis (https://redis.io/) key-value storage, looks like this:
redis_addr = env::var("REDIS_ADDR") .unwrap_or_default("localhost:6379".to_string());
Keep in mind that creating an env var
with env::set_var()
[13] and deleting it with env::remove_var()
[19] both only change the env var
for our current process. This means that the created env var
are not going to be readable by other programs. It also means that if we accidentally remove an important env var
, the rest of the operating system is not going to care, as it can still access it.
There's more...
At the beginning of this recipe, I wrote about storing your configuration in the environment. The industry standard way to do this is by creating a file called .env
that contains said config in the form of key-value-pairs, and loading it into the process at some point during the build. One easy way to do this in Rust is by using the dotenv (https://crates.io/crates/dotenv) third-party crate.