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
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
£29.99
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (1 Ratings)
eBook Mar 2018 360 pages 1st Edition
eBook
£29.99
Paperback
£36.99
Subscription
Free Trial
Renews at £9.99p/m
Arrow left icon
Profile Icon Jan Hohenheim Profile Icon Daniel Durante
Arrow right icon
£29.99
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (1 Ratings)
eBook Mar 2018 360 pages 1st Edition
eBook
£29.99
Paperback
£36.99
Subscription
Free Trial
Renews at £9.99p/m
eBook
£29.99
Paperback
£36.99
Subscription
Free Trial
Renews at £9.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
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

Billing Address

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.

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 : 9781788629652
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
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

Billing Address

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
£9.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
£99.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 £5 each
Feature tick icon Exclusive print discounts
£139.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 £5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total £ 110.97
Network Programming with Rust
£36.99
Rust High Performance
£36.99
Rust Standard Library Cookbook
£36.99
Total £ 110.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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.