Question:
I am going through the too-many-linked-lists tutorial, looking to implement a simple linked list:pop_node
function is to return the node at the head of the list. However it
does not seem to compile complaining that I moved the variable node
while accessing nd
. Is there a way I can pass the bound variable in a pattern match without owning it?This is the error I see:
Answer:
Usually when you’re performing this kind of operation, you want the actual element (thei32
here), so maybe return Option<i32>
instead — None
would indicate that the list was empty. Doing this is much simpler than what you’re trying to do. Within the match
you can just return nd.elem
.shift_node
(pop_node
would be expected to remove the last node, not the first).I’d also consider replacing your
Link
type with Option<Box<Node>>
. Then you can use utilities already present on Option
. For example, your mem::replace()
call could be replaced with self.head.take()
and then you’re just mapping the result. You can keep the Link
name by making it an alias (type Link = Option<Box<Node>>;
).If you have better answer, please add a comment about this, thank you!