27. Option's sum/product
Rust’s option implements Sum and Product traits too!
Use it when you want to get None if there is a None element and sum of values otherwise.
| |
or sum of the values …
| |
And product.
| |
Rust’s option implements Sum and Product traits too!
Use it when you want to get None if there is a None element and sum of values otherwise.
| |
or sum of the values …
| |
And product.
| |
Rust’s option implements FromIterator too!
Use it when you want to get None if there is a None element and values otherwise.
| |
or values …
| |
Rust’s option implements an iterator!
| |
Why is this useful? see example.
| |
As of 1.66, it is possible to use ..=X in patterns
| |
Instead of manually implementing Default trait for an enum, you can derive it and explicitly tell which variant should be the default one.
| |
Use Debug trait to print enum values if needed.
| |
Sometimes there is a need to zip two iterables of various lengths.
If it is known which one is longer, then use the following approach:
First one must be longer.
| |
As of 1.65, it is possible to use let statement with a refutable pattern.
| |
As of 1.65, it is possible to label plain block expression and terminate that block early.
| |
Use flatten to iterate over only Some values if you have a collection of Options.
| |
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.
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.
| |