I'm trying to build a tree structure and maintain a path while traversing the tree.
Here's some code:
use std::collections::VecDeque;
struct Node {
children: VecDeque<Node>,
}
struct Cursor<'a> {
path: VecDeque<&'a mut Node>,
}
impl<'a> Cursor<'a> {
fn new(n: &mut Node) -> Cursor {
let mut v = VecDeque::new();
v.push_front(n);
Cursor { path: v }
}
fn go_down(&'a mut self, idx: usize) -> bool {
let n = match self.path[0].children.get_mut(idx) {
None => return false,
Some(x) => x
};
self.path.push_front(n);
true
}
}
I have two questions. First, the lifetime specifier in go_down()
self
argument was suggested by the compiler, but I'm not sure why it fixes the reported issue.
Even with this change, however, the above code will not compile because self.path
is borrowed two times. Is there a way to maintain a path of tree nodes without writing "unsafe" code?