Skip to content

map::OccupiedEntryRef::key should return &K rather than &Q #421

@programmerjake

Description

@programmerjake

returning Q unnecessarily throws away the key type, which may have extra information needed by the user, e.g. the Rc you want to clone.

example where returning K is useful:

struct Interner<T: Eq + Hash> {
    values: HashMap<Rc<T>, ()>,
}

impl<T: Eq + Hash> Interner<T>
where
    Rc<T>: for<'a> From<&'a T>,
{
    fn intern(&mut self, v: &T) -> Rc<T> {
        match self.values.entry_ref(v) {
            EntryRef::Occupied(entry) => Rc::clone(entry.key()), // getting `&Rc<T>` instead of `&T` avoids allocating a new `Rc<T>`
            EntryRef::Vacant(entry) => Rc::clone(entry.insert_entry(()).key())
        }
    }
}

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