Skip to content

OccupiedEntry::get returns references bound to the lifetime of the Entry, not the HashMap #39099

Closed
@khuey

Description

@khuey

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions