def_fn_iter!((n: usize). {
for i in 0 .. n
yield_value(i);
}
})
Consider the above pseudocode. It takes a plain Rust function. This Rust function uses yield_value
inside it. We can mechanically transform this into an Iterator as follows:
-
run everything up until the field Yield, this goes in the constructor of the Iterator
-
for Iterator::next(), run until first yield(), return Some(v); if function terminates, return None
If we mechanically convert the function into a state machine, we can write iterators with yield_value.
Question: is there any Rust macro for doing something like this?
===
Pre-emptive answers:
This won't work if the yield_value is in a nested function. That's fine. We make it a requirement that the yield_value has to be lexically within the macro. Clojure's go block ( Clojure - Go Block Best Practices ) has the same limitation and it's fine.