I'm having trouble finding an ergonomic way to do the following:
I have a struct that contains a vector of items. I want to return a "best candidate" item by first filtering the vector and then sorting the vector. I also want the best candidate item to be a mutable reference.
Note: The filtering and sorting in this sample is just dummy code
The error I get is at the last line:
68 | subset.first().map(|x| *x)
| ^^ move occurs because *x has type &mut Item, which does not implement the Copy trait
I tried chaining rather than assigning to "subset", but "sort_by" doesn't return a reference to itself, so that didn't work.
This is because mutable references are guaranteed to be unique, and hence cannot be copied. So essentially, it fails for the same reason as why this fails:
error[E0507]: cannot move out of `*x` which is behind a shared reference
--> src/lib.rs:9:26
|
9 | strs.first().map(|x| *x)
| ^^ move occurs because `*x` has type `String`, which does not implement the `Copy` trait
To fix this, you must take ownership of the vector's first item rather than borrowing it mutably. The easiest way to do that is to call .into_iter().next().