0

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76
  • 1
    I don't think you can avoid the "useless" operation in safe code. You need _something_ to pass to `Box::new()`, and the tail can't be moved out of the borrowed context. That said, I don't think that operation has any measurable performance impact, since the runtime of `prepend()` is dominated by the memory allocation. The compiler may even be able to optiimise the redundant step away. – Sven Marnach May 11 '19 at 09:00
  • From the linked duplicate: *simultaneously replace it with `Nil`, so that the `self` reference is never invalid*. This is why it's needed in safe Rust. – Shepmaster May 11 '19 at 11:49

0 Answers0