chapter eight

8 Iterators and closures

 

This chapter covers

  • Method chaining - calling one method after another after another
  • Iterators - the most convenient way to work with collections
  • Closures - functions that don't need names and can capture variables in their scope

In this chapter you’re going to see a lot of Rust’s functional style. This lets you use a method that gives an output, that output becomes the next method’s input, and you repeat until you have the final output that you want. It's like a chain of methods, which is why people call it 'method chaining'. Method chaining is a lot of fun once you get used to it and lets you do a lot of work with not very much code. Iterators and closures are a big help here, so those are the main focus of this chapter. But first let's chain a few methods to see what it looks like.

8.1 Chaining methods

Rust is a systems programming language like C and C++, and its code can be written as separate commands in separate lines, but it also has a functional style. Both styles are okay, but functional style is usually shorter.

Here is an example of the non-functional style (called "imperative style") to make a Vec from 1 to 10:

fn main() {
    let mut new_vec = Vec::new();
    let mut counter = 1;
 
    while counter < 11 {
        new_vec.push(counter);
        counter += 1;
    }
 
    println!("{new_vec:?}");
}

This prints [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].

8.2 Iterators

8.2.1 How an iterator works

8.3 Closures

8.3.1 in a closure

8.4 Summary