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 most important trait for conversion is From. Implementing it means defining how to obtain a type from another.

We present this on the example of DoubleVec[6]. Its concept is simple, when you construct it out of a Vec, it doubles all its elements. For this purpose, we implement From<Vec<T>> [11] with a where clause specifying T: MulAssign<i32>[13], which means that the trait will be implemented for all types that can be assigned to the result of a multiplication with an integer. Or, in terms of code, all types that allow the following, assuming the t variable is of the T type:

t *= 2;

The actual implementation should be self-explanatory, we simply multiply every element in the vector by two and wrap it in our DoubleVec[19]. Afterwards, we implement From as well for slices of the same type [25].

It is considered good practice to extend all of your trait definitions that work with vectors ( Vec<T> ) to also work with...