I have a nested structure, to simplify the example, say it's a tree containing of nodes:
#[derive(Debug)]
struct Node {
left: Option>>,
value: T,
right: Option>>,
}
What I want to do, is to get a mutable reference to a value at one of the bottom branches to modify it. Let's say, to get the most up-right branch I could do:
let mut node = &mut tree;
loop {
if let Some(ref mut v) = node.right {
node = v.as_mut();
} else {
break;
}
}
node.value = -1;
println!("{:?}", tree)
The problem is that I don't necessarily know the structure of the tree in advance and my query can also change during the queries (so I could go once right, other time left, etc). That is why, I would like to have some kind of iterator like shown below that would allow me to try different branches until I find the final one and then .borrow_mut it.
struct Getter<'a, T>(&'a mut Node);
impl<'a, T> Getter<'a, T> {
fn get(&mut self, right: bool) -> bool {
if right {
if let Some(v) = &mut self.0.right {
self.0 = v;
return true;
}
} else {
if let Some(v) = &mut self.0.left {
self.0 = v;
return true;
}
}
false
}
}
impl<'a, T> BorrowMut for Getter<'a, T> { ... }
The problem is, that unlike the loop, this would not work because of lifetimes. Can such iterator be implemented, and if yes, how?