I have encountered a problem trying to deal with keys with a specific lifetimes in a HashMap.
I have isolated the relevant parts of a HashMap in a simplified MyHashMap in the following code.
I don't understand why the compiler has no problem with the get() method but complains when calling get_mut().
use std::borrow::Borrow;
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
struct Key<'a> {
s: &'a str,
// more irrelevant fields
}
struct MyHashMap<K, V> {
entries: Vec<(K, V)>,
}
impl<K, V> MyHashMap<K, V> {
fn get<Q>(&self, key: &Q) -> Option<&V>
where
Q: ?Sized,
K: Borrow<Q>,
{
todo!()
}
fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
where
Q: ?Sized,
K: Borrow<Q>,
{
todo!()
}
// Trying to be more explicit about lifetimes doesn't help.
fn get_mut2<'a, Q>(&'a mut self, key: &Q) -> Option<&'a mut V>
where
Q: ?Sized,
K: Borrow<Q>,
{
todo!()
}
}
fn foo<'a>(map: &MyHashMap<Key<'static>, i32>, key: &Key<'a>) {
map.get(&key); // Ok
map.get_mut(&key); // Error: lifetime mismatch
//map.get_mut2(&key); // Error: lifetime mismatch
// also, with std HashMap: map[&key]; gives the same error: lifetime mismatch
}