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
struct Item {
value: u8
}
struct Items {
items: Vec<Item>
}
impl Items {
fn get_mut_best_item(&mut self) -> Option<&mut Item> {
let mut subset: Vec<&mut Item> = self.items.iter_mut().filter(|i| i.value % 2 == 0).collect();
subset.sort_by(|lhs, rhs| lhs.value.partial_cmp(&rhs.value).unwrap());
subset.first().map(|x| *x)
}
}
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.