Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore 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
Rust Standard Library Cookbook
Rust Standard Library Cookbook

Rust Standard Library Cookbook: Over 75 recipes to leverage the power of Rust

Arrow left icon
Profile Icon Jan Hohenheim Profile Icon Daniel Durante
Arrow right icon
Mex$1004.99
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (1 Ratings)
Paperback Mar 2018 360 pages 1st Edition
eBook
Mex$803.99
Paperback
Mex$1004.99
Subscription
Free Trial
Arrow left icon
Profile Icon Jan Hohenheim Profile Icon Daniel Durante
Arrow right icon
Mex$1004.99
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (1 Ratings)
Paperback Mar 2018 360 pages 1st Edition
eBook
Mex$803.99
Paperback
Mex$1004.99
Subscription
Free Trial
eBook
Mex$803.99
Paperback
Mex$1004.99
Subscription
Free Trial

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Rust Standard Library Cookbook

Chapter 2. Working with Collections

In this chapter, we will cover the following recipes:

  • Using a vector
  • Using a string
  • Accessing collections as iterators
  • Using a VecDeque
  • Using a HashMap
  • Using a HashSet
  • Creating an own iterator
  • Using a slab

Introduction


Rust provides a very broad set of collections to use. We will look at most of them, see how they're used, discuss how they're implemented, and when to use and choose them. A big part of this chapter focuses on iterators. Much of Rust's flexibility comes from them, as all collections (and more!) can be used as iterators. Learning how to use them is crucial.

Throughout this chapter, we are going to use the big O notation to show how effective certain algorithms are. In case you don't know it yet, it is a way of telling how much longer an algorithm takes when working with more elements. Let's look at it briefly.

means that an algorithm is going to take the same time, no matter how much data is stored in a collection. It doesn't tell us how fast exactly it is, just that it's not going to slow down with size. This is the realistic ideal for a function. A practical example for this is accessing the first number in an infinite list of numbers: no matter how many numbers there are, you...

Using a vector


The most basic collection is the vector, or Vec for short. It is essentially a variable-length array with a very low overhead. As such, it is the collection that you will use most of the time.

How to do it...

  1. In the command line, jump one folder up with cd .. so you're not in chapter-one anymore. In the next chapters, we are going to assume that you always started with this step.
  2. Create a Rust project to work on during this chapter with cargo new chapter-two.

  3. Navigate into the newly-created chapter-two folder. For the rest of this chapter, we will assume that your command line is currently in this directory.
  4. Inside the folder src, create a new folder called bin.
  5. Delete the generated lib.rs file, as we are not creating a library.
  6. In the folder src/bin, create a file called vector.rs.
  7. Add the following code blocks to the file and run them with cargo run --bin vector:
1  fn main() {
2    // Create a vector with some elements
3    let fruits = vec!["apple", "tomato", "pear"];
4    // A...

Using a string


Rust provides an unusually large functionality for its string. Knowing it can save you quite some headache when dealing with raw user input.

How to do it...

  1. In the folder src/bin, create a file called string.rs.
  2. Add the following code, and run it with cargo run --bin string:
1   fn main() {
2     // As a String is a kind of vector,
3     // you can construct them the same way
4     let mut s = String::new();
5     s.push('H');
6     s.push('i');
7     println!("s: {}", s);
8
9     // The String however can also be constructed
10    // from a string slice (&str)
11    // The next two ways of doing to are equivalent
12    let s = "Hello".to_string();
13    println!("s: {}", s);
14    let s = String::from("Hello");
15    println!("s: {}", s);
16
17    // A String in Rust will always be valid UTF-8
18    let s = "
Þjóðhildur
".to_string(); 19 println!("s: {}", s); 20 21 // Append strings to each other 22 let mut s = "Hello ".to_string(); 23 s.push_str("World"); 24...

Accessing collections as iterators


Welcome to one of the most flexible parts of the Rust standard library. Iterators are, as the name suggests, a way of applying actions of items in a collection. If you come from C#, you will already be familiar with iterators because of Linq. Rust's iterators are kind of similar, but come with a more functional approach to things.

Because they are an extremely fundamental part of the standard library, we are going to dedicate this recipe entirely to a showcase of all the different things you can do with them in isolation. For real-world use cases, you can simply continue reading the book, as a big portion of the other recipes features iterators in some way or another.

How to do it...

  1. In the folder src/bin, create a file called iterator.rs.
  2. Add the following code, and run it with cargo run --bin iterator:
1   fn main() {
2     let names = vec!["Joe", "Miranda", "Alice"];
3     // Iterators can be accessed in many ways.
4     // Nearly all collections implement...

Using a VecDeque


When you need to insert or remove elements regularly into or from the beginning of the vector, your performance might take quite a hit, as it will force the vector to reallocate all data that comes after it. This is especially bothersome when implementing a queue. For this reason, Rust provides you with the VecDeque.

How to do it...

  1. In the folder src/bin, create a file called vecdeque.rs.
  2. Add the following code, and run it with cargo run --bin vecdeque:
1   use std::collections::VecDeque;
2 
3   fn main() {
4     // A VecDeque is best thought of as a
5     // First-In-First-Out (FIFO) queue
6 
7     // Usually, you will use it to push_back data
8     // and then remove it again with pop_front
9     let mut orders = VecDeque::new();
10    println!("A guest ordered oysters!");
11    orders.push_back("oysters");
12 
13    println!("A guest ordered fish and chips!");
14    orders.push_back("fish and chips");
15 
16    let prepared = orders.pop_front();
17    if let Some(prepared...

Using a HashMap


If you imagine a Vec as a collection that assigns an index (0, 1, 2, and so on) to data, the HashMap is a collection that assigns any data to any data. It allows you to map arbitrary, hashable data to other arbitrary data. Hashing and mapping, that's where the name comes from!

How to do it...

  1. In the folder src/bin, create a file called hashmap.rs.
  2. Add the following code, and run it with cargo run --bin hashmap:
1   use std::collections::HashMap; 
2 
3   fn main() {
4     // The HashMap can map any hashable type to any other
5     // The first type is called the "key"
6     // and the second one the "value"
7     let mut tv_ratings = HashMap::new();
8     // Here, we are mapping &str to i32
9     tv_ratings.insert("The IT Crowd", 8);
10    tv_ratings.insert("13 Reasons Why", 7);
11    tv_ratings.insert("House of Cards", 9);
12    tv_ratings.insert("Stranger Things", 8);
13    tv_ratings.insert("Breaking Bad", 10);
14 
15    // Does a key exist?
16    let contains_tv_show ...

Using a HashSet


The best way to describe a HashSet is by describing how it's implemented: HashMap<K, ()>. It's just a HashMap without any values!

The two best reasons to choose a HashSet are:

  • You don't want to deal with duplicate values at all, as it doesn't even include them.
  • You plan on doing a lot (and I mean a lot) of item lookup - that is the question, Does my collection contain this particular item?. In a vector, this is done in
    , while a HashSet can do it in
    .

How to do it...

  1. In the folder src/bin, create a file called hashset.rs.
  2. Add the following code, and run it with cargo run --bin hashset:
1   use std::collections::HashSet;
2 
3   fn main() {
4     // Most of the interface of HashSet
5     // is the same as HashMap, just without
6     // the methods that handle values
7     let mut books = HashSet::new();
8     books.insert("Harry Potter and the Philosopher's Stone");
9     books.insert("The Name of the Wind");
10    books.insert("A Game of Thrones");
11 
12    // A HashSet will...

Creating an own iterator


When you create an infinitely applicable algorithm or a collection-like structure, it's really nice to have the dozens of methods that an iterator provides at your disposal. For this, you will have to know how to tell Rust to implement them for you.

How to do it...

  1. In the folder src/bin, create a file called own_iterator.rs.
  2. Add the following code, and run it with cargo run --bin own_iterator:
1   fn main() {
2     let fib: Vec<_> = fibonacci().take(10).collect();
3     println!("First 10 numbers of the fibonacci sequence: {:?}", 
        fib);
4 
5     let mut squared_vec = SquaredVec::new();
6     squared_vec.push(1);
7     squared_vec.push(2);
8     squared_vec.push(3);
9     squared_vec.push(4);
10    for (index, num) in squared_vec.iter().enumerate() {
11      println!("{}^2 is {}", index + 1, num);
12    }
13  }
14 
15 
16  fn fibonacci() -> Fibonacci {
17    Fibonacci { curr: 0, next: 1 }
18  }
19  struct Fibonacci {
20  curr: u32,
21  next: u32,
22 ...

Using a slab


Some algorithms require you to hold access tokens to data that may or may not exist. This could be solved in Rust by using  Vec<Option<T>>, and treating the index of your data as a token. But we can do better! slab is an optimized abstraction of exactly this concept.

While it is not meant as a general-purpose collection, slab can help you a lot if you use it in the right places.

How to do it...

  1. Open the Cargo.toml file that has been generated earlier for you.

  2. Under [dependencies], add the following line:
slab = "0.4.0"
  1. If you want, you can go to slab's crates.io page (https://crates.io/crates/slab) to check for the newest version, and use that one instead.
  2. In the folder bin, create a file called slab.rs.

  3. Add the following code, and run it with cargo run --bin slab:

1   extern crate slab;
2   use slab::{Slab, VacantEntry};
3 
4   fn main() {
5     // A slab is meant to be used as a limited buffer
6     // As such, you should initialize it with a pre-
7     // defined capacity...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Develop high-quality, fast, and portable applications by leveraging the power of Rust's Standard library.
  • Practical recipes that will help you work with the Standard library to boost your productivity as a Rust developer.
  • Learn about most relevant external crates to be used along with the Standard library.

Description

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.

Who is this book for?

This book is for developers who would like to explore the power of Rust and learn to use the STL for various functionalities. A basic Rust programming knowledge is assumed.

What you will learn

  • How to use the basic modules of the library: strings, command line access, and more.
  • Implement collections and folding of collections using vectors, Deque, linked lists, and more.
  • Handle various file types, compressing, and decompressing data.
  • Search for files with glob patterns.
  • Implement parsing through various formats such as CSV, TOML, and JSON.
  • Utilize drop trait, the Rust version of destructor.
  • Resource locking with Bilocks.
Estimated delivery fee Deliver to Mexico

Standard delivery 10 - 13 business days

Mex$149.95

Premium delivery 3 - 6 business days

Mex$299.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Mar 29, 2018
Length: 360 pages
Edition : 1st
Language : English
ISBN-13 : 9781788623926
Category :
Languages :

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Mexico

Standard delivery 10 - 13 business days

Mex$149.95

Premium delivery 3 - 6 business days

Mex$299.95
(Includes tracking information)

Product Details

Publication date : Mar 29, 2018
Length: 360 pages
Edition : 1st
Language : English
ISBN-13 : 9781788623926
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$12.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 6,500+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$129.99 billed annually
Feature tick icon Unlimited access to Packt's library of 6,500+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Mex$85 each
Feature tick icon Exclusive print discounts
$179.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 6,500+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Mex$85 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Mex$ 3,014.97
Network Programming with Rust
Mex$1004.99
Rust High Performance
Mex$1004.99
Rust Standard Library Cookbook
Mex$1004.99
Total Mex$ 3,014.97 Stars icon
Visually different images

Table of Contents

10 Chapters
Learning the Basics Chevron down icon Chevron up icon
Working with Collections Chevron down icon Chevron up icon
Handling Files and the Filesystem Chevron down icon Chevron up icon
Serialization Chevron down icon Chevron up icon
Advanced Data Structures Chevron down icon Chevron up icon
Handling Errors Chevron down icon Chevron up icon
Parallelism and Rayon Chevron down icon Chevron up icon
Working with Futures Chevron down icon Chevron up icon
Networking Chevron down icon Chevron up icon
Using Experimental Nightly Features Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(1 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Donald A. Newell Jr. Mar 14, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Good reference book for Rust
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
Modal Close icon
Modal Close icon