I'm having trouble understanding why this causes an error:
#[derive(Debug)]
pub struct Node {
next: Option<Box<Node>>,
}
pub fn print_root_or_next(root: &mut Node, try_next: bool) {
let mut current = root;
match &mut current.next {
Some(node) => {
if try_next {
current = &mut *node;
}
}
None => return,
}
println!("{:?}", current);
}
error[E0502]: cannot borrow `current` as immutable because it is also borrowed as mutable
--> src/lib.rs:17:22
|
8 | match &mut current.next {
| ----------------- mutable borrow occurs here
...
17 | println!("{:?}", current);
| ^^^^^^^
| |
| immutable borrow occurs here
| mutable borrow later used here
I can't see how there are conflicting borrows; even the error message seems to indicate that two borrows are one and the same. Is this an issue in with the borrow checker or is this example actually flawed in some way?
I am very interested in this limitation. I don't know much about the implementation, but considering that a basic if
:
if try_next {
current = &mut *current.next.as_mut().unwrap();
}
and basic match
:
match &mut current.next {
Some(node) => {
current = &mut *node;
}
None => return,
}
and even inverting them:
if try_next {
match &mut current.next {
Some(node) => {
current = &mut *node;
}
None => return,
}
}
all work, there must be some thing that the borrow checker is or is not considering that conflicts with my understanding of why the original form doesn't work.