Hi! Can you suggest a fix? I have a singly linked list of `Option<Rc<RefCell<Node<T>>>>`, and I'm trying to return a `core::cell::Ref` from the middle of it. Is there a way to do it without being limited by the lifetime of a local variable?
Yet another linked list question about RefCell.
Hi! Can you suggest a fix? I have a singly linked list of `Option<Rc<RefCell<Node<T>>>>`, and I'm trying to return a `core::cell::Ref` from the middle of it. Is there a way to do it without being limited by the lifetime of a local variable?
#[derive(Debug)]
pub struct List<T> {
maybe_head: Option<Rc<RefCell<Node<T>>>>,
maybe_tail: Option<Rc<RefCell<Node<T>>>>,
length: usize,
}
#[derive(Debug)]
struct Node<T> {
value: T,
maybe_next: Option<Rc<RefCell<Node<T>>>>,
}
impl<T> List<T> {
fn get<'a>(&'a self, ind: usize) -> Box<dyn Deref<Target = T> + 'a> {
if self.length == 0 || ind < 0 || ind >= self.length {
panic!("Index out of bounds!");
}
if ind == 0 {
let a = self.maybe_head.as_ref().unwrap();
let b = a.borrow();
let c = Ref::map(b, |d| &d.value);
return Box::new(c);
}
let mut opt: Option<Rc<RefCell<Node<T>>>> = Some(Rc::clone(self.maybe_head.as_ref().unwrap()));
let mut rc: Rc<RefCell<Node<T>>>;
let mut borrowed_node: Ref<Node<T>>;
let mut countdown = ind;
#[allow(unused_must_use)]
loop {
rc = Rc::clone(opt.as_ref().unwrap());
borrowed_node = rc.borrow();
if countdown == 0 {
let tmp = Ref::map(borrowed_node, |node| &node.value);
return Box::new(tmp);
} else {
let tmp1 = borrowed_node.maybe_next.as_ref().unwrap();
let tmp2 = Rc::clone(tmp1);
opt.replace(tmp2);
countdown -= 1;
}
}
}
}
impl<T> List<T> { fn get<'a>(&'a self, ind: usize) -> Box<dyn Deref<Target = T> + 'a> { if self.length == 0 || ind < 0 || ind >= self.length { panic!("Index out of bounds!"); }
if ind == 0 { let a = self.maybe_head.as_ref().unwrap(); let b = a.borrow(); let c = Ref::map(b, |d| &d.value); return Box::new(c); }
let mut opt: Option<Rc<RefCell<Node<T>>>> = Some(Rc::clone(self.maybe_head.as_ref().unwrap())); let mut rc: Rc<RefCell<Node<T>>>; let mut borrowed_node: Ref<Node<T>>; let mut countdown = ind;