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

In order to read from the standard console input, stdin, we first need to obtain a handle to it. We do this by calling io::stdin() [29]. Imagine the returned object as a reference to a global stdin object. This global buffer is managed by a Mutex, which means that only one thread can access it at a time (more on that later in the book, in the Parallelly accessing resources with Mutexes section in Chapter 7, Parallelism and Rayon). We get this access by locking (using lock()) the buffer, which returns a new handle [31]. After we have done this, we can call the lines method on it, which returns an iterator over the lines the user will write [31 and 52]. More on iterators in the Accessing collections as Iterators section in Chapter 2, Working with Collections.

Finally, we can iterate over as many submitted lines as we want until some kind of break condition is reached, otherwise the iteration would go on forever. In our example, we break the number-checking loop as soon as a valid number has been entered [56].

If we're not particularly picky about our input and just want the next line, we have two options:

  • We can continue using the infinite iterator provided by lines(), but simply call next on it in order to just take the first one. This comes with an additional error check as, generally speaking, we cannot guarantee that there is a next element.

  • We can use read_line in order to populate an existing buffer [43]. This doesn't require that we lock the handler first, as it is done implicitly.

Although they both result in the same end effect, you should choose the first option. It is more idiomatic as it uses iterators instead of a mutable state, which makes it more maintainable and readable.

On a side note, we are using print! instead of println! in some places in this recipe for aesthetic reasons [22]. If you prefer the look of newlines before user input, you can refrain from using them.