The error occurs because a and b form a reference cycle where each Rc<List> points to the other, preventing their reference counts from ever reaching zero. To fix this, replace one of the Rc<List> pointers in the cycle with a Weak<List> pointer so the cycle can be broken and memory cleaned up.
use std::cell::RefCell;
use std::rc::{Rc, Weak};
#[derive(Debug)]
enum List {
Cons(i32, RefCell<Weak<List>>),
Nil,
}
impl List {
fn tail(&self) -> Option<&RefCell<Weak<List>>> {
match self {
Cons(_, item) => Some(item),
Nil => None,
}
}
}
fn main() {
let a = Rc::new(Cons(5, RefCell::new(Rc::downgrade(&Rc::new(Nil)))));
let b = Rc::new(Cons(10, RefCell::new(Rc::clone(&a))));
if let Some(link) = a.tail() {
*link.borrow_mut() = Rc::downgrade(&b);
}
println!("a next item = {:?}", a.tail());
}