8 Iterators and closures

 

This chapter covers

  • Using method chaining to call one method after another after another
  • Using iterators, which are the most convenient way to work with collections
  • Using closures, which are functions that don’t need names and can capture variables in their scope

In this chapter, we’re going to see a lot of Rust’s functional style, which is based on expressions. This style 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 works 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; it lets you do a lot of work with not very much code. Iterators and closures are a big help here, so they are the main focus of this chapter.

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 nonfunctional style (called imperative style) to make a Vec from 1 to 10:

fn main() {
    let mut new_vec = Vec::new();
    let mut counter = 1;
    loop {
        new_vec.push(counter);
        counter += 1;
        if counter == 10 {
            break;
        }
    }
    println!("{new_vec:?}");
}

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

8.2 Iterators

8.3 Closures and closures inside iterators

8.3.1 Closures inside of methods

8.3.2 Closures: Lazy and fast

8.3.3 |_| in a closure

Summary

sitemap