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 to do it...

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

  2. Add the following code and run it with cargo run --bin conversion:

1    use std::ops::MulAssign; 
2 use std::fmt::Display;
3
4 // This structure doubles all elements it stores
5 #[derive(Debug)]
6 struct DoubleVec<T>(Vec<T>);
7
8
9 // Allowing conversion from a Vec<T>,
10 // where T is multipliable with an integer
11 impl<T> From<Vec<T>> for DoubleVec<T>
12 where
13 T: MulAssign<i32>,
14 {
15 fn from(mut vec: Vec<T>) -> Self {
16 for elem in &mut vec {
17 *elem *= 2;
18 }
19 DoubleVec(vec)
20 }
21 }
22
23 // Allowing conversion from a slice of Ts
24 // where T is again multipliable with an integer
25 impl<'a, T> From<&'a [T]> for DoubleVec<T>
26 where
27 T: MulAssign<i32> + Clone,
28 {
29 fn from(slice: &[T]) -> Self {
30 // Vec<T: MulAssign...