macro_rules! vec_comp { [$($t:tt)*] => { ... }; }
Expand description
Performs a comprehension and returns a Vec containing the results. If you
want the raw iterator, you can use the iter_comp! macro (that’s what
this macro uses internally anyway).
Usage
The core idea is simple: provide an easy and concise way to map, filter, and flatten iterators. For example, a basic comprehension looks like this:
let v = vec_comp![for x in 0..10 => x];This will make a vector with the numbers 0 through 9… not very useful, is it? Let’s add a filter:
let v = vec_comp![for x in 0..10 => x, if x % 2 == 0];Now we only get even numbers. We can also map the values:
let v = vec_comp![for x in 0..10 => x * 2, if x % 2 == 0];Now we get the even numbers, doubled. What’s better than that? Well, thanks to Rust’s expression syntax, you can destructure tuples:
let pairs = vec![(1, 2), (3, 4), (5, 6)];
let v = vec_comp![for (x, y) in pairs => x + y];and structs:
let points = //...
let v = vec_comp![for Point { x, y } in points => x + y];and anything else that destructures! You can also nest comprehensions:
let matrix = //...
let v = vec_comp![for row in matrix; for col in row => col, if col % 2 == 0];We could keep going with the nesting, but I think you get the idea.