Description
Consider the following toy code to implement a simple HashMap
-based cache.
struct Table {
table: HashMap<String, Option<u32>>,
}
impl Table {
fn lookup(&mut self, s: String) -> Result<&u32> {
match self.table.entry(s) {
Entry::Occupied(o) => {
o.get().as_ref().ok_or_else(|| panic!())
},
Entry::Vacant(v) => {
// TODO: Calculate a value.
panic!();
}
}
}
}
The borrow checker will fail this.
rustc 1.14.0 (e8a0123 2016-12-16)
error:o
does not live long enough
--> :13:17
|
13 | o.get().as_ref().ok_or_else(|| panic!())
| ^ does not live long enough
...
19 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the block at 10:52...
--> :10:53
|
10 | fn lookup(&mut self, s: String) -> Result<&u32> {
| ^
It appears that OccupiedEntry::get
is returning a reference to the value in the HashMap
with the lifetime of the Entry
, not the HashMap
. This seems like a bug to me.