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 src/bin folder, create a file called constructor.rs

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

1  fn main() {
2 // We don't need to care about
3 // the internal structure of NameLength
4 // Instead, we can just call it's constructor
5 let name_length = NameLength::new("John");
6
7 // Prints "The name 'John' is '4' characters long"
8 name_length.print();
9 }
10
11 struct NameLength {
12 name: String,
13 length: usize,
14 }
15
16 impl NameLength {
17 // The user doesn't need to setup length
18 // We do it for him!
19 fn new(name: &str) -> Self {
20 NameLength {
21 length: name.len(),
22 name,
23 }
24 }
25
26 fn print(&self) {
27 println!(
28 "The name '{}' is '{}' characters long",
29 self.name,
30 self.length
31 );
32 }
33 }