• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Copying a value in a pattern match without owning it

Resolved: Copying a value in a pattern match without owning it

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I am going through the too-many-linked-lists tutorial, looking to implement a simple linked list:
The 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:
Any idea what I should be doing here? (I tried things like unpacking the node struct but they didn’t seem to work.)

Answer:

Usually when you’re performing this kind of operation, you want the actual element (the i32 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.
Note this operation should be called 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!

borrow-checker rust
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Vaadin 14.9 – Redirect on Session Destroy Event

26/03/2023

Resolved: How to separate multiple answers in one column, for multiple columns, by creating extra columns

26/03/2023

Resolved: How to set consistent decimal separators in R data frame?

26/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.