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

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

1  fn main() {
2 // There's a default value for nearly every primitive type
3 let foo: i32 = Default::default();
4 println!("foo: {}", foo); // Prints "foo: 0"
5
6
7 // A struct that derives from Default can be initialized like
this
8 let pizza: PizzaConfig = Default::default();
9 // Prints "wants_cheese: false
10 println!("wants_cheese: {}", pizza.wants_cheese);
11
12 // Prints "number_of_olives: 0"
13 println!("number_of_olives: {}", pizza.number_of_olives);
14
15 // Prints "special_message: "
16 println!("special message: {}", pizza.special_message);
17
18 let crust_type = match pizza.crust_type {
19 CrustType::Thin => "Nice and thin",
20 CrustType::Thick => "Extra thick and extra filling",
21 };
22 // Prints "crust_type: Nice and thin"
23 println!("crust_type: {}", crust_type);
24
25
26 // You can also configure only certain values
27 let custom_pizza = PizzaConfig {
28 number_of_olives: 12,
29 ..Default::default()
30 };
31
32 // You can define as many values as you want
33 let deluxe_custom_pizza = PizzaConfig {
34 number_of_olives: 12,
35 wants_cheese: true,
36 special_message: "Will you marry me?".to_string(),
37 ..Default::default()
38 };
39
40 }
41
42 #[derive(Default)]
43 struct PizzaConfig {
44 wants_cheese: bool,
45 number_of_olives: i32,
46 special_message: String,
47 crust_type: CrustType,
48 }
49
50 // You can implement default easily for your own types
51 enum CrustType {
52 Thin,
53 Thick,
54 }
55 impl Default for CrustType {
56 fn default() -> CrustType {
57 CrustType::Thin
58 }
59 }