This macro implements a syntax that emulates Pythons
generator-expression syntax in a form more compatible with rusts
usual syntax.
This means that there a few small differences between the python syntax and the syntax prvided in this macro:
- The expression in the beginning of the generator expression must end with a semicolon (;).
- The pattern between the
forandintokens is a fully-fledged rust pattern, which can be as simple as a simple token and as complex as struct destructuring. - The expression defining the iterator after the
fortoken (and potentially before aniftoken) must evaluate to either anIteratoror animpl IntoIterator, and end with a semicolon (;). - The conditional expression after the
ifexpression expression (and potentially before afortoken) must evaluate to a boolean, and end with a semicolon (;).
The expression replaced by the comp!() macro invocation is a lazy
iterator whose lifetime is bound by any references it needs to capture.
This means that it can be .collect()ed into any container you like.
Examples
Simple generator expression with a conditional:
use comp;
;
let arr = &;
// Notice the semicolons
let comp_vector = comp!
.;
assert_eq!
Triple cartesian product with conditions and patterns:
use comp;
;
// These need to be references to arrays because of how the closures
// that the macro expands to capture their environment.
let x = &;
let y = &;
let z = &;
let xyz = comp!
.;
// The result vector here is short for illustration purposes
// but can be as long as long as you need it to be.
assert_eq!