for loops
for and range
The for in
construct can be used to iterate through an Iterator
.
One of the easiest ways to create an iterator is to use the range
notation a..b
. This yields values from a
(inclusive) to b
(exclusive) in steps of one.
Let's write FizzBuzz using for
instead of while
.
for and iterators
The for in
construct is able to interact with an Iterator
in several ways.
As discussed in with the Iterator trait, if not specified, the for
loop will apply the into_iter
function on the collection provided to convert
the collection into an iterator. This is not the only means to convert a
collection into an iterator however, the other functions available include
iter
and iter_mut
.
These 3 functions will return different views of the data within your collection.
iter
- This borrows each element of the collection through each iteration. Thus leaving the collection untouched and available for reuse after the loop.
into_iter
- This consumes the collection so that on each iteration the exact data is provided. Once the collection has been consumed it is no longer available for reuse as it has been 'moved' within the loop.
iter_mut
- This mutably borrows each element of the collection, allowing for the collection to be modified in place.
In the above snippets note the type of match
branch, that is the key
difference in the types or iteration. The difference in type then of course
implies differing actions that are able to be performed.