Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
khuey opened this issue Jan 16, 2017 · 1 comment

Comments

@khuey
Copy link
Contributor

khuey commented Jan 16, 2017

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.

@khuey
Copy link
Contributor Author

khuey commented Jan 16, 2017

talchas on IRC introduced me to into_mut

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant