Something told me how to implement a linked list:
enum List {
Cons(u32, Box<List>),
Nil,
}
impl List {
fn prepend(self, elem: u32) -> List {
Cons(elem, Box::new(self))
}
}
When I want to use prepend
, I need to do the following:
list = list.prepend(1);
However, I want to create a function that does not need to create a new variable every time prepend
returns. I just want to change the list
variable itself using prepend
:
list.prepend(1);
Here is one implementation that I come up with, but it's not right:
fn my_prepend(&mut self, elem: u32) {
*self = Cons(elem, Box::new(*self));
}
The error is:
error[E0507]: cannot move out of borrowed content