[Rust Guide] 13.5. Iterators - Definitions, the Iterator Trait, and the Next Method
13.5.0 Before We Begin During its design, Rust drew inspiration from many languages, and functional programming had a particularly strong influence on Rust. Functional programming often includes passing functions as values to parameters, returning them from other functions, assigning them to variables for later execution, and so on. In this chapter, we will discuss some Rust features that are similar to what many languages call functional features: Closures Iterators (this article) Improving the I/O Project with Closures and Iterators Performance of Closures and Iterators If you find this helpful, please like, bookmark, and follow. To keep learning along, follow this series. 13.5.1 What Is an Iterator To talk about iterators, we first need to talk about the iterator pattern. The iterator pattern allows you to perform a task on each element in a sequence, one by one. In that process, the iterator is responsible for: Traversing each item Determining when the sequence has finished iterating Rust iterators are lazy: unless you call a method that consumes the iterator, the iterator itself does nothing. In other words, if you write an iterator in your code but never use it, it is as if it did nothing at all. Take a look at an example: fn main () { let v1 = vec! [ 1 , 2 , 3 ]; let v1_iter = v1 .iter (); } v1 is a Vector , and v1.iter() creates an iterator for v1 and assigns it to v1_iter . But v1_iter is not used yet, so the iterator can be considered to have no effect. Now let’s use the iterator to traverse the values: fn main () { let v1 = vec! [ 1 , 2 , 3 ]; let v1_iter = v1 .iter (); for val in v1_iter { println! ( "Got: {}" , val ); } } This is equivalent to using each element in the iterator once in a loop. 13.5.2 The Iterator Trait All iterators implement the Iterator trait. This trait is defined in the standard library and looks roughly like this: pub trait Iterator { type Item ; fn next ( & mut self ) -> Option < Self :: Item > ; // methods with default implementa