I'm writing an implementation of linked list to learn rust. I have run into a problem with writing the function pop_first element of the linked list. Rust telling me that I can't assign to immutable.
Assigning to self would just mutate the local variable self, but this function wants to mutate *self (the thing that self points to). To do this, you'll need to assign a new value of type List, but next has type &mut List.
std::mem::replace is one useful way to move a value out of a mutable reference, by putting a new value in its place:
use std::mem::replace;
match *self {
List::Cons(value, ref mut next) => {
let tail = replace(next, Box::new(List::Nil));
*self = *tail;
Some(value)
},
List::Nil => None,
}