I have a tree structure, for which I've written a find_mut
function.
#[derive(Debug)]
struct Tree<'a> {
children: Vec<Tree<'a>>,
data: &'a Data,
}
#[derive(Debug)]
struct Data {
id: u32,
parent_id: u32,
}
impl<'a> Tree<'a> {
pub fn new(data: &'a Data) -> Self {
Self {
children: vec!(),
data: data,
}
}
fn find_mut(&mut self, find_id: u32) -> Option<&'a mut Tree> {
match self.data.id {
id if id == find_id => Some(self),
_ =>
match self.children
.iter_mut()
.map(|c| c.find_mut(find_id))
.filter(|c| c.is_some())
.next()
{
Some(child) => child,
None => None,
}
}
}
}
This appears to work, but renders the calling Tree
unusable, so e.g. this is impossible:
let mut tree = ...;
let mut find = tree.find_mut(0x1);
println!("{:#?}", tree);
// > error[E0502]: cannot borrow `tree` as immutable because it is also borrowed as mutable
The above makes sense to me, but I'm curious if my general idea can even work. My intuition is to write code like this:
- Grab a mutable reference indiscriminately to a
Tree
or one of its descendents - Do work on it
- Resume using the original
Tree
Is this feasible, or am I thinking in the wrong paradigm here?