I am going through Testcase: linked-list in Rust by Example. RBE has implemented prepend
method by passing self
by value:
fn prepend(self, elem: u32) -> List {
// `Cons` also has type List
Cons(elem, Box::new(self))
}
and calls it as:
list = list.prepend(1);
list = list.prepend(2);
list = list.prepend(3);
I want to use &mut self
and not assign list
over and over, like so:
list.prepend("asd");
list.prepend("def");
list.prepend("jkl");
I tried:
enum LinkedList<T> {
Cons(T, Box<LinkedList<T>>),
Nil
}
impl<T> LinkedList<T> where T: Copy {
fn prepend(&mut self, value: T) {
let tail = mem::replace(self, Nil);
*self = Cons(value, Box::new(tail));
}
}
This works, but I am doing a useless assignment of Nil
to self
. Is there a better way to do this, perhaps using mem::replace
or something else?