I've searched about this question before, like this and this, but following the solution of the first link and try to apply them to my code, rustc seems misunderstand what I'm trying to do.
I wanted to create a linked list and assign some reference to the middle of the nodes and print their values. First I made them mutable in order to create the list from head ref to tail ref, then I wanted to convert them to be immutable, from tail ref to head ref, which wouldn't violate ownership rules. In the end, I wanted to access some immutable references(midway points) to get their values.
My code: (playground)
struct Node<T> {
val: T,
next: Option<Box<Node<T>>>,
}
impl<T> Node<T> {
fn new(val: T) -> Option<Box<Node<T>>> {
Some(Box::new(Node { val, next: None }))
}
}
fn main() {
let head = &mut Node::new(0);
let a = &mut head.as_mut().unwrap().next;
*a = Node::new(10);
let b = &mut a.as_mut().unwrap().next;
*b = Node::new(20);
let c = &mut b.as_mut().unwrap().next;
*c = Node::new(30);
let tail = &mut c.as_mut().unwrap().next;
*tail = Node::new(40);
// Trying to make these mutable reference immutable.
let tail = &*tail;
// reference 'c' is converted to immutable,
// so nothing borrows 'b' as mutable anymore
let c = &*c;
// Reports error anyway.
// error[E0502]: cannot borrow `*b` as immutable
// because it is also borrowed as mutable
// 16 | let c = &mut b.as_mut().unwrap().next;
// | ---------- mutable borrow occurs here
// Didn't I just convert c to immutable?
let b = &*b;
let a = &*a;
let head = &*head;
println!(
"a is {}, b is {}, c is {}",
a.as_ref().unwrap().val,
b.as_ref().unwrap().val,
c.as_ref().unwrap().val
);
}
Things had gone wrong here, rustc still reports that I try to borrow them as immutable because they are borrowed by ref that is mutable. But I already converted the ref to immutable before. Why?
Could there be any solution to make my program run as expected?