I have a fairly simple use case where I store my own generic KeyValuePair struct in a Vector, declared like this:
#[derive(Eq, Ord, PartialEq, PartialOrd)]
pub struct KeyValuePair<TKey, TValue> {
key : TKey,
value : TValue
}
pub struct OtherStruct<TKey, TValue>
where TKey : Hash + Eq + Ord
{
values : Vec<KeyValuePair<TKey, TValue>>
}
This is all great, but I'm having trouble figuring out how to use Vector's binary_search_by_key function with this setup. No matter what I pass the ownership checker seems to get angry. I understand some of the exception messages, but I'm still stuck on how to accomplish what I actually want.
I started with:
match &self.values.binary_search_by_key(key, |kvp| kvp.key) {
Ok(pos) => return self.values.get(*pos),
Err(pos) => return None
}
This gives me the error:
error[E0507]: cannot move out of `kvp.key` which is behind a shared refere
This one makes sense; as written it would have to move the return value. So I changed the return to a borrow:
match &self.values.binary_search_by_key(key, |kvp| &kvp.key) {
This one fails because the closure function definition expects TKey as the return type, not &TKey
^^^^^^^^ expected type parameter `TKey`, found `&TKey`
My next attempt was to borrow the parameter to avoid the move, but I got this:
match &self.values.binary_search_by_key(key, |&kvp| kvp.key) {
| ^---
| ||
| |data moved here
| |move occurs because `kvp` has type `KeyValuePair<TKey, TValue>`, which does not implement the `Copy` trait
| help: consider removing the `&`: `kvp`
This one doesn't make any sense to me; I don't get why borrowing kvp would cause a move? Isn't it the other way around - it would normally move, but adding & borrows instead?
What is the proper syntax to search the vector by key without breaking ownership?