Book Image

Rust Standard Library Cookbook

By : Jan Hohenheim, Daniel Durante
Book Image

Rust Standard Library Cookbook

By: Jan Hohenheim, Daniel Durante

Overview of this book

Mozilla’s Rust is gaining much attention with amazing features and a powerful library. This book will take you through varied recipes to teach you how to leverage the Standard library to implement efficient solutions. The book begins with a brief look at the basic modules of the Standard library and collections. From here, the recipes will cover packages that support file/directory handling and interaction through parsing. You will learn about packages related to advanced data structures, error handling, and networking. You will also learn to work with futures and experimental nightly features. The book also covers the most relevant external crates in Rust. By the end of the book, you will be proficient at using the Rust Standard library.
Table of Contents (12 chapters)

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.