Why does the immutable version in the following example work, but the mutable version does not compile with error error: lifetime may not live long enough
?
trait Car {
fn honk(&self);
}
struct CarCollection {
cars: HashMap<usize, Box<dyn Car>>,
}
impl CarCollection {
// Does compile
fn get(&self, id: usize) -> Option<&dyn Car> {
self.cars.get(&id).map(|c| c.as_ref())
}
// Does not compile
fn get_mut(&mut self, id: usize) -> Option<&mut dyn Car> {
self.cars.get_mut(&id).map(|c| c.as_mut())
}
}
I know I can work around this issue with:
if let Some(car) = self.cars.get_mut(id) {
Some(car.as_mut())
} else {
None
}
But nonetheless, I am really confused by this an would like to know, what is going on here? I thought lifetimes do not differ between mutable and immutable references.