Macro rustcomp::iter_comp

source ·
macro_rules! iter_comp {
    (@__ for $($vars:pat),+ in $iter:expr; $($recurse:tt)+) => { ... };
    (@__ for $($vars:pat),+ in $iter:expr => $mapper:expr $(, if $guard:expr)? $(,)?) => { ... };
    (for $($t:tt)+) => { ... };
}
Expand description

Generates an iterator that yields the results of the comprehension. The syntax allows for filtering, mapping, and flattening iterators (in that order).

There are 3 main components to a comprehension:

  • The for-in clause, which iterates over the input
  • The guard expression, which filters the input
  • The mapping expression, which transforms the input. If the guard is present, the mapping expression is only applied to values that pass the guard.

Examples

Comprehensions can be as simple or complex as you want. They can collect the input, filter it, map it, and flatten it all in one go. For example, here’s how you can create a HashMap of numbers and their squares using a comprehension:

let m = iter_comp!(for i in 0..10 => (i, i * i)).collect::<HashMap<_, _>>();
let it = (0..10).map(|i| (i, i * i)).collect::<HashMap<_, _>>();
assert_eq!(m, it);

See the crate-level documentation for more examples.