I'd like to implement a Deque using the interior mutability pattern. For this purpose, I have the following Node
and Deque
structs:
pub struct Node<T: Clone> {
value: T,
next: Option<Rc<RefCell<Node<T>>>>,
prev: Option<Rc<RefCell<Node<T>>>>,
}
pub struct Deque<T: Clone> {
head: Option<Rc<RefCell<Node<T>>>>,
tail: Option<Rc<RefCell<Node<T>>>>,
}
Among others, I'd like to offer a method called get_values
that returns a vector of the copied values:
impl<T> Deque<T>
where
T: Clone,
{
pub fn get_values(&self) -> Vec<T> {
let mut values = Vec::new();
let mut temp = &self.head;
while let Some(node) = temp {
values.push(node.borrow().value.clone());
temp = &node.borrow().next.clone();
}
values
}
}
Unfortunately, the borrowed values doesn't live long enough:
error[E0716]: temporary value dropped while borrowed
--> src/deque.rs:85:21
|
83 | while let Some(node) = temp {
| ---- borrow later used here
84 | values.push(node.borrow().value.clone());
85 | temp = &node.borrow().next.clone();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^- temporary value is freed at the end of this statement
| |
| creates a temporary value which is freed while still in use
|
= note: consider using a `let` binding to create a longer lived value
So I create a let
binding:
80 pub fn get_values(&self) -> Vec<T> {
81 let mut values = Vec::new();
82 let mut temp = &self.head;
83 while let Some(node) = temp {
84 values.push(node.borrow().value.clone());
85 let next = &node.borrow().next.clone();
86 temp = next;
87 }
88 values
89 }
Which doesn't live long enough:
error[E0716]: temporary value dropped while borrowed
--> src/deque.rs:85:25
|
83 | while let Some(node) = temp {
| ---- borrow later used here
84 | values.push(node.borrow().value.clone());
85 | let next = &node.borrow().next.clone();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ creates a temporary value which is freed while still in use
86 | temp = next;
87 | }
| - temporary value is freed at the end of this statement
So let's move the binding further up in the scope:
80 pub fn get_values(&self) -> Vec<T> {
81 let mut values = Vec::new();
82 let mut temp = &self.head;
83 let mut next;
84 while let Some(node) = temp {
85 values.push(node.borrow().value.clone());
86 next = &node.borrow().next.clone();
87 temp = next;
88 }
89 values
90 }
Which gives me another error:
error[E0716]: temporary value dropped while borrowed
--> src/deque.rs:86:21
|
86 | next = &node.borrow().next.clone();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^- temporary value is freed at the end of this statement
| |
| creates a temporary value which is freed while still in use
87 | temp = next;
| ---- borrow later used here
|
= note: consider using a `let` binding to create a longer lived value
Here we are again, and I think I tackled the wrong issue.
Any ideas how to prevent this issue?