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 it works...

Our main function is split into three parts:

  1. Creating a file.
  2. Overwriting a file, which in this context is called truncating.
  3. Appending to a file.

In the first two parts, we load the entire content of the file into a single String and display it [11 and 18]. In the last one, we iterate over the individual lines in the file and print them [28].

File::open() opens a file in read-only mode and returns you a handle to it [39]. Because this handle implements the Read trait, we could now just directly read it into a string with read_to_string. However, in our examples, we wrap it first in a BufReader[42]. This is because a dedicated reader can greatly improve the performance of their resource access by collecting read instructions, which is called buffering, and executing them in big batches. For the first reading example, read_file[37], this doesn't make any difference whatsoever, as we read it all in one go anyway. We still use it because it is a good practice...