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

The purpose of our example is to read a file, age.txt, and return the number written in it, assuming that it represents some kind of age. We can encounter three errors during this process:

  • Failure to read the file (maybe it doesn't exist)
  • Failure to read its content as a number (it could contain text as well)
  • The number could be negative

These possible error states are the possible variants of our Error enum: AgeReaderError[7]. It is usual to name the variants after the sub-errors they represent. Because a failure to read the file raises an io::Error, we name our corresponding variant AgeReaderError::Io[8]. A failure to parse a &str as an i32 raises a num::ParseIntError, so we name our encompassing variant AgeReaderError::Parse[9].

These two std errors show the naming convention of errors neatly. If you have many different errors that can be returned by a module, export them via their full name, such as num::ParseIntError. If your module only...