I need to find the node with maximal value in tree, assuming that subnode's values are always larger than value of owning node, and then modify it:
#[derive(Debug)]
struct Node {
val: usize,
nodes: Vec<Node>,
}
fn find_max(node: &mut Node, val: usize) -> Option<&mut Node> {
if node.val < val {
return None;
}
let mut max_val = node.val;
let mut max: Option<&mut Node> = Some(node);
for n in &mut node.nodes {
if let Some(m) = find_max(n, max_val) {
max_val = m.val;
max = Some(m);
}
}
max
}
fn main() {
let mut root = Node {
val: 1,
nodes: vec![
Node {
val: 2,
nodes: vec![],
},
Node {
val: 3,
nodes: vec![
Node {
val: 4,
nodes: vec![],
},
],
},
],
};
println!("{:?}", find_max(&mut root, 0));
}
The borrow checker returns this error:
error[E0499]: cannot borrow `node.nodes` as mutable more than once at a time
--> src/main.rs:13:19
|
12 | let mut max: Option<&mut Node> = Some(node);
| ---- first mutable borrow occurs here
13 | for n in &mut node.nodes {
| ^^^^^^^^^^ second mutable borrow occurs here
...
20 | }
| - first borrow ends here
If I remove mut
from find_max
, it works, but I don't see how can I return a mutable reference from find_max
.
The important thing is that find_max
itself doesn't modify anything. It just searches for an appropriate node.
node
, because in some cases we need to return it. And we cannot use indices because there are multiple vectors. – red75prime