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

The format! macro combines strings by accepting a format string filled with formatting parameters (example, {}, {0}, or {foo}) and a list of arguments, which are then inserted into the placeholders.
We are now going to show this on the example in line [16]:

format!("My favourite number is {}", 42);

Let's break down the preceding line of code:

  • "My favourite number is {}" is the format string
  • {} is the formatting parameter
  • 42 is the argument

As demonstrated, format! works not only with strings, but also with numbers. In fact, it works with all structs that implement the Display trait. This means that, by providing such an implementation by yourself, you can easily make your own data structures printable however you want.

By default, format! replaces one parameter after another. If you want to override this behavior, you can use positional parameters like {0} [21]. With the knowledge that the positions are zero-indexed, the behavior here is pretty straightforward, {0} gets replaced by the first argument, {1} gets replaced by the second, and so on.

At times, this can become a bit unwieldy when using a lot of parameters. For this purpose, you can use named arguments [26], just like in Python. Keep in mind that all of your unnamed arguments have to be placed before your named ones. For example, the following is invalid:

format!("{message} {}", message="Hello there,", "friendo")

It should be rewritten as:

format!("{message} {}", "friendo", message="Hello there,")
// Returns "hello there, friendo"