Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Rust Standard Library Cookbook

You're reading from   Rust Standard Library Cookbook Over 75 recipes to leverage the power of Rust

Arrow left icon
Product type Paperback
Published in Mar 2018
Publisher Packt
ISBN-13 9781788623926
Length 360 pages
Edition 1st Edition
Languages
Arrow right icon
Authors (2):
Arrow left icon
Jan Hohenheim Jan Hohenheim
Author Profile Icon Jan Hohenheim
Jan Hohenheim
Daniel Durante Daniel Durante
Author Profile Icon Daniel Durante
Daniel Durante
Arrow right icon
View More author details
Toc

Table of Contents (17) Chapters Close

Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
1. Learning the Basics FREE CHAPTER 2. Working with Collections 3. Handling Files and the Filesystem 4. Serialization 5. Advanced Data Structures 6. Handling Errors 7. Parallelism and Rayon 8. Working with Futures 9. Networking 10. Using Experimental Nightly Features 1. Other Books You May Enjoy Index

Providing a default implementation


Often, when dealing with structures that represent configurations, you don't care about certain values and just want to silently assign them a standard value.

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  }

How it works...

Nearly every type in Rust has a Default implementation. When you define your own struct that only contains elements that already have a Default, you have the option to derive from Default as well [42]. In the case of enums or complex structs, you can easily write your own implementation of Default instead [55], as there's only one method you have to provide. After this, the struct returned by Default::default() is implicitly inferrable as yours, if you tell the compiler what your type actually is. This is why in line [3] we have to write foo: i32, or else Rust wouldn't know what type the default object actually should become.

If you only want to specify some elements and leave the others at the default, you can use the syntax in line [29]. Keep in mind that you can configure and skip as many values as you want, as shown in lines [33 to 37].

You have been reading a chapter from
Rust Standard Library Cookbook
Published in: Mar 2018
Publisher: Packt
ISBN-13: 9781788623926
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime
Visually different images