The following code produces the lifetime errors below despite the fact that the V
instance in question is owned.
use std::collections::hash_map::HashMap;
use std::cmp::Eq;
use std::hash::Hash;
trait Set<V> {
fn set(&mut self, value: V) -> Option<V>;
}
impl<'a, K: Eq + Hash + From<&'a V>, V: 'a> Set<V> for HashMap<K, V> {
fn set(&mut self, v: V) -> Option<V> {
let k = K::from(&v);
self.insert(k, v)
}
}
The resulting errors ...
|
9 | impl<'a, K: Eq + Hash + From<&'a V>, V: 'a> Set<V> for HashMap<K, V> {
| -- lifetime `'a` defined here
10 | fn set(&mut self, v: V) -> Option<V> {
11 | let k = K::from(&v);
| --------^^-
| | |
| | borrowed value does not live long enough
| argument requires that `v` is borrowed for `'a`
12 | self.insert(k, v)
13 | }
| - `v` dropped here while still borrowed
error[E0505]: cannot move out of `v` because it is borrowed
--> src/lib.rs:12:24
|
9 | impl<'a, K: Eq + Hash + From<&'a V>, V: 'a> Set<V> for HashMap<K, V> {
| -- lifetime `'a` defined here
10 | fn set(&mut self, v: V) -> Option<V> {
11 | let k = K::from(&v);
| -----------
| | |
| | borrow of `v` occurs here
| argument requires that `v` is borrowed for `'a`
12 | self.insert(k, v)
| ^ move out of `v` occurs here