RUST / CHAPTER 08

Iterator pipelines and collection

Advanced

Build lazy transformations and choose the ownership of resulting elements.

By the end of this chapter

  • Combine filter and map
  • Identify a consuming iterator operation
  • Collect an owned result from borrowed data

The idea

Enter with closures, references, and vectors understood. An iterator produces a sequence of items as consumers request them. Adaptors such as filter and map describe work but are lazy: creating the pipeline alone does not process every element. A consumer such as collect, sum, or a for loop drives the iterator. Keep side effects out of transformations when a simple value calculation will do.

The item type depends on how iteration begins. iter borrows collection elements, whereas into_iter can consume an owned collection. copied turns references to Copy values into copied items. This makes a pipeline over integers easy to read without moving the original vector. Type annotations on collect tell Rust which result collection to build. Choose the pipeline by its data ownership as well as its arithmetic.

Rust example
fn main(){
 let values=vec![1,4,7,8];
 let result:Vec<i32>=values.iter().copied().filter(|n|n%2==0).map(|n|n/2).collect();
 println!("{:?}",result);
}
Result
[2, 4]

The consumer collects only even input values after halving them. iter and copied leave the original vector available.

Try it yourself

Build a Vec<i32> containing the squares of positive inputs while retaining the source vector.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which operation drives a lazy map pipeline and constructs a vector?