-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Closed
Labels
T-libs-apiRelevant to the library API team, which will review and decide on the RFC.Relevant to the library API team, which will review and decide on the RFC.
Description
At present, HashMap
's OccupiedEntry
and VacantEntry
don't expose their associated keys. It would be useful to have a method (say, key()
) which exposes a reference to the key. The relevant use case I have run into is when performing a get-or-insert operation on a HashMap
, when the value that is inserted is a function of the key. If you want to compute the value to insert only when there is not already an entry in the map, the current API forces you to clone the key so that its value is still available after pulling an Entry
out of the map. For example:
pub fn get_or_insert<K: Clone + Eq + Hash, V, F: FnOnce(&K) -> V>(
table: &mut HashMap<K, V>, key: K, f: F) -> bool {
// table.entry() moves out of key, so we need to clone it,
// regardless of our need for it later.
match table.entry(key.clone()) {
Entry::Occupied(_) => false,
Entry::Vacant(e) => {
e.insert(f(&key));
true
}
}
}
It appears simple to add methods which return a reference to the keys of OccupiedEntry
and VacantEntry
. I would be happy to provide a pull request doing so.
Metadata
Metadata
Assignees
Labels
T-libs-apiRelevant to the library API team, which will review and decide on the RFC.Relevant to the library API team, which will review and decide on the RFC.