struct MyLinkedList<A> {
elem: A,
next: Rc<RefCell<Option<MyLinkedList<A>>>>,
}
impl <A> MyLinkedList<A> {
fn append(&self, new_element: A) {
// Pull things into a bunch of different variables to understand
// compiler errors without seeing a bunch of temp value stuff
let mut current: &MyLinkedList<A> = self;
let mut rc_clone: Rc<RefCell<Option<MyLinkedList<A>>>>;
let mut rc_clone_borrow: Ref<Option<MyLinkedList<A>>>;
loop {
rc_clone = Rc::clone(¤t.next);
rc_clone_borrow = rc_clone.borrow();
if let Some(next_node) = rc_clone_borrow.as_ref() {
current = next_node;
} else {
break;
}
}
*Rc::clone(¤t.next).borrow_mut() = Some(
MyLinkedList {
elem: new_element,
next: Rc::new(RefCell::new(None)),
}
);
}
}
I'm fairly new to Rust, and so am a little confused by the errors I'm getting for this snippet of code.
I get some basic things about borrowing, at least, but I'm curious if there's a way to circumvent what I'm running into.
rc_clone
is borrowed by the rc_clone.borrow()
line (implicitly when doing deref coercion).
Then, rc_clone_borrow
gets borrowed with deref coercion on the rc_clone_borrow.as_ref()
line.
I guess I'm curious, is there some way to structure this code (without altering the struct definition) to avoid running into these borrowing errors? Or is this inherent with the way that I've structured things?