-
Book Overview & Buying
-
Table Of Contents
Rust for C++ Developers
By :
As we've discussed, the least complicated way to consume an iterator is to call the next() method repeatedly to get each element until it returns None. While Rust has some syntax helpers, such as the while let loop, this can still be a cumbersome way to work with iterators. Surely it's not the only way? Let's take a look at the options provided by the language and standard library for consuming values from an iterator.
One of the most common and convenient ways to consume iterators ends up being the for loop that we've seen several times throughout the book. One surprising revelation might be that the for loop only exists to consume iterators. Now that we're working with iterators, we can fully explain the workings of this language construct.
The for loop is purely syntactic sugar, meaning that it hides a more complicated implementation that would be cumbersome to type out repeatedly....