<!-- Morning -->
<!-- What do I want to do today? -->
<!-- Evening -->
<!-- What did I learn today? -->
<!-- Things I learned -->
<!-- Useful tools and libraries -->
Rust
Iterator and IntoIter traits
- The
Iterator trait is used to iterate over collections. - The
Iterator implements a next() method which returns an Option<T> next
item in the collection. - If you have a data structure that can be iterated over, you have to implement
the
IntoIter trait to iterate over it.- The
IntoIter returns an Iterator over the elements in the collection. - The
Iterator will be an additional structure that keeps track of the
current element in the collection and returns it when next() is called,
and then moves to the next element in the collection. - If a type implements
IntoIter (or Iterator) you can use it in a for
loop
- You have to implement different type of
Iterator structures for the each
type or reference type you have. - An example of an iterabile data structure is a slice
[T]- You can iterate the elements of the slice
- Slice implements
IntoIte for the for the following typesiml IntoTier<Iter> for &[T]Iter will yield &T items from a reference to a slice
iml IntoTier<IterMut> for &mut [T]IterMut will yield &mut T items from a mutable reference to a slice
iml IntoTier<IntoIter> for [T]IntoIter will yield T items from an owned slice
- Also
Vec<T> is an example, but it leverages the slice type to iterate; in
other words it implements IntoIter to the slices Iterator types.
- This design pattern is good to implement iterations for any structures
- The hardest part is to implement
Iterator for IterMut which yields
&mut T- This will give you a lot of headaches if your using safe Rust since you are
returning mutable reference that are behind a mutable reference to the
collection.
- A good blog post (even if a bit old) is:
Iterators yielding mutable references
- Good md-book:
Too many Lists