Skip to content

In the Entry API, the lifetime of the key should be dissociated from the lifetime of the container #20625

@tomaka

Description

@tomaka

This code:

use std::collections::hash_map::{HashMap, Entry};

fn get_the_value_of_0_or_insert(h: &mut HashMap<int, String>) -> &String {
    match h.entry(&0) {
        Entry::Occupied(val) => val.into_mut(),
        Entry::Vacant(v) => v.insert("hello".to_string())
    }
}

Produces:

D:\Projets\test\src\lib.rs:4:20: 4:21 error: borrowed value does not live long enough
D:\Projets\test\src\lib.rs:4     match h.entry(&0) {
                                                ^
D:\Projets\test\src\lib.rs:3:74: 8:2 note: reference must be valid for the anonymous lifetime #1 defined on the block at 3:73...
D:\Projets\test\src\lib.rs:3 fn get_the_value_of_0_or_insert(h: &mut HashMap<int, String>) -> &String {
D:\Projets\test\src\lib.rs:4     match h.entry(&0) {
D:\Projets\test\src\lib.rs:5         Entry::Occupied(val) => val.get(),
D:\Projets\test\src\lib.rs:6         Entry::Vacant(v) => v.insert("hello".to_string())
D:\Projets\test\src\lib.rs:7     }
D:\Projets\test\src\lib.rs:8 }
D:\Projets\test\src\lib.rs:3:74: 8:2 note: ...but borrowed value is only valid for the block at 3:73
D:\Projets\test\src\lib.rs:3 fn get_the_value_of_0_or_insert(h: &mut HashMap<int, String>) -> &String {
D:\Projets\test\src\lib.rs:4     match h.entry(&0) {
D:\Projets\test\src\lib.rs:5         Entry::Occupied(val) => val.get(),
D:\Projets\test\src\lib.rs:6         Entry::Vacant(v) => v.insert("hello".to_string())
D:\Projets\test\src\lib.rs:7     }
D:\Projets\test\src\lib.rs:8 }

This is because VacantEntry::insert returns a reference of lifetime 'a, which is the same lifetime as the key passed to entry.

The signature of entry and Entry should be changed from:

fn entry<'a, Q>(&'a mut self, key: &'a Q) -> Entry<'a, Q, K, V> 

To:

fn entry<'a, 'b, Q>(&'a mut self, key: &'b Q) -> Entry<'a, 'b, Q, K, V> 

cc @gankro

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions