Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Rust Standard Library Cookbook

You're reading from   Rust Standard Library Cookbook Over 75 recipes to leverage the power of Rust

Arrow left icon
Product type Paperback
Published in Mar 2018
Publisher Packt
ISBN-13 9781788623926
Length 360 pages
Edition 1st Edition
Languages
Arrow right icon
Authors (2):
Arrow left icon
Jan Hohenheim Jan Hohenheim
Author Profile Icon Jan Hohenheim
Jan Hohenheim
Daniel Durante Daniel Durante
Author Profile Icon Daniel Durante
Daniel Durante
Arrow right icon
View More author details
Toc

Table of Contents (17) Chapters Close

Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
1. Learning the Basics FREE CHAPTER 2. Working with Collections 3. Handling Files and the Filesystem 4. Serialization 5. Advanced Data Structures 6. Handling Errors 7. Parallelism and Rayon 8. Working with Futures 9. Networking 10. Using Experimental Nightly Features 1. Other Books You May Enjoy Index

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...

  1. In the bin folder, create a file called env_vars.rs

  2. 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.

You have been reading a chapter from
Rust Standard Library Cookbook
Published in: Mar 2018
Publisher: Packt
ISBN-13: 9781788623926
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime
Visually different images