Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

The for statement is a shortcut to iterate over an iterator object or an object convertible into an iterator. If the object on which the loop is applied is not an iterator but implements the IntoIterator trait, then a call to into_iter() is made for us to convert the object. This is what happens for instance with collections like Vec. It is implemented as a loop statement with a call to the next() method of the iterator at its start.

In the following example, we use the for statement to iterate over an array:

1 2 3 4 

A range being an iterator, we can use the for statement on it:

1 2 3 4 5 6 7 8 9 10 

Many methods (see Table 2 for a list of the main iterator methods) can be called onto the iterator to transform it. For instance, in the following example, we reverse the range to iterate from higher values to lower values, using the rev() iterator method:

10 9 8 7 6 5 4 3 2 1 

As for the loop statement:

see solution