So, first, a clarification: this question is in essence very similar to Append an element to a recursive list iteratively and Convert tail-recursive form to iterative form?, however, there is a crucial difference, and it's the one that causes the problem - the conditional return of the current node.
This is a relatively barebones version of a list iterator:
struct Node {
node_data: Option<Box<Node>>,
}
impl Node {
fn find_iterative(&mut self) -> &mut Node {
let mut current = self;
loop {
match current.node_data {
Some(ref mut child) => {
if Self::some_condition() {
return current;
} else {
current = child;
}
}
_ => {
panic!("");
}
}
}
}
fn some_condition() -> bool {
true
}
}
(playground: Rust Playground)
Now, I get an error on the return current;
. I've tried the conventional workarounds:
- using a temporary value for
current
; - wrapping
current
in curly braces (in thematch
expression).
none of those worked. The culprit is the conditional block (intended as a whole, not just the if
expression), which I can't remove, because it's crucial.
The only two ways of making it work are:
- converting the logic to recursive;
- using the
polonius
Rust flag.
Is there some workaround/solution I can use, instead of the two above?