15. Scan
Iterator adapter similar to fold (see previous bite) - holds some internal state and produces new iterator.
Note that Option is yielded from the closure.
| |
Iterator adapter similar to fold (see previous bite) - holds some internal state and produces new iterator.
Note that Option is yielded from the closure.
| |
Use position to find position of an element in iterator. Returns None if the element does not exist.
| |
Similar to map but if allows to drop an item.
| |
Iterator consumer. Allows the accumulated value to be arbitrary type. Note the different types.
| |
Use enumerate to convert iterator over (usize,item) pairs.
| |
Useful when index of item is needed.
Fuse is an iterator that yields None forever after the underlying iterator yields None once. USage:
| |
Why is it useful? see example in this bite.
Sometimes an underlying iterator may or may yield Some(T) again after None was returned.
fuse ensures that after a None is returned for the first time, it always returns None.
Example from the rust documentation:
| |
Rust provides built-in methods to copy or clone elements when using an iterator.
Eg.
| |
What’s the difference? and when is it useful?
You may have done something like this:
| |
but instead, use copied.
| |
Example:
| |
Difference between cloned and copied?
Same reasoning aplies as for Copy and Clone traits. Use copied to avoid to accidentally cloing iterator elements. Use copied when possible.
Ever wondered how to print while iterating?
Use inspect.
| |
Use drain to remove specified range from a vector.
| |
What is the difference to call into_iter which returns T ?
into_iter takes the collection by value and consumes it.
drain borrows mutable reference, and returns a drain iterator of elements. If such iterator is dropped without exhausting it, all elements are dropped.
What is the difference between .iter() and .into_iter()?
iter yields &T
into_iter may yield any of T, &T or &mut T based on context.
| |
this works but …
This does not. This results in compile error because cars are moved due to into_iter call.
| |