Question:I am going through the too-many-linked-lists tutorial, looking to implement a simple linked list:
pop_nodefunction is to return the node at the head of the list. However it does not seem to compile complaining that I moved the variable
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 (the
i32here), so maybe return
Nonewould indicate that the list was empty. Doing this is much simpler than what you’re trying to do. Within the
matchyou can just return
pop_nodewould be expected to remove the last node, not the first).
I’d also consider replacing your
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
Linkname by making it an alias (
type Link = Option<Box<Node>>;).
If you have better answer, please add a comment about this, thank you!