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)

There's more...

The vector should always be your go-to collection. Internally, it is implemented as a continuous chunk of memory stored on the heap:

The important keyword here is continuous, which means that the memory is very cache-friendly. In other words, the vector is pretty fast! The vector even allocates a bit of extra memory in case you want to extend it. Be careful, though, when inserting a lot of data at the beginning of the vector: the entire stack will have to be moved.

At the end, you can see a bit of extra capacity. This is because Vec and many other collections preallocate a bit of extra memory each time you have to move the block, because it has grown too large. This is done in order to prevent as many reallocations as possible. You can check the exact amount of total space of a vector by calling capacity[140] on it. You can influence the preallocation by initializing your vector with with_capacity[137]. Use it when you have a rough idea about how many elements you...