Book Image

Rust Essentials - Second Edition

By : Ivo Balbaert
Book Image

Rust Essentials - Second Edition

By: Ivo Balbaert

Overview of this book

Rust is the new, open source, fast, and safe systems programming language for the 21st century, developed at Mozilla Research, and with a steadily growing community. It was created to solve the dilemma between high-level, slow code with minimal control over the system, and low-level, fast code with maximum system control. It is no longer necessary to learn C/C++ to develop resource intensive and low-level systems applications. This book will give you a head start to solve systems programming and application tasks with Rust. We start off with an argumentation of Rust's unique place in today's landscape of programming languages. You'll install Rust and learn how to work with its package manager Cargo. The various concepts are introduced step by step: variables, types, functions, and control structures to lay the groundwork. Then we explore more structured data such as strings, arrays, and enums, and you’ll see how pattern matching works. Throughout all this, we stress the unique ways of reasoning that the Rust compiler uses to produce safe code. Next we look at Rust's specific way of error handling, and the overall importance of traits in Rust code. The pillar of memory safety is treated in depth as we explore the various pointer kinds. Next, you’ll see how macros can simplify code generation, and how to compose bigger projects with modules and crates. Finally, you’ll discover how we can write safe concurrent code in Rust and interface with C programs, get a view of the Rust ecosystem, and explore the use of the standard library.
Table of Contents (13 chapters)

Consumers and adapters


Now, we will see some examples that show why iterators are so useful. Iterators are lazy and have to be activated by invoking a consumer to start using the values. Let's start with a range of the numbers from 0 to 999 included. To make this into a vector, we apply the function collect() consumer:

// see code in Chapter 5/code/adapters_consumers.rs 
let rng = 0..1000; 
let rngvec: Vec<i32> = rng.collect(); 
// alternative notation: 
// let rngvec = rng.collect::<Vec<i32>>(); 
println!("{:?}", rngvec); 

This prints out the range (we shortened the output with...):

[0, 1, 2, 3, 4, ... , 999]

The function collect() loops through the entire iterator, collecting all of the elements into a container, here of type Vec<i32>. That container does not have to be an iterator. Notice that we indicate the item type of the vector with Vec<i32>, but we could have also written it as Vec<_>. The notation collect::<Vec<i32>>() is new, it indicates...