Open
Description
Feature gate: #![feature(map_try_insert)]
This is a tracking issue for BTreeMap::try_insert
and HashMap::try_insert
.
Unlike .insert()
, .try_insert()
does not overwrite existing values, and has a meaningful error type with more context. See #82764
Public API
// alloc::collections::btree_map
impl<K: Ord, V> BTreeMap<K, V> {
pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V>>;
}
pub struct OccupiedError<'a, K: 'a, V: 'a> {
pub entry: OccupiedEntry<'a, K, V>,
pub value: V,
}
impl<K: Debug + Ord, V: Debug> Debug for OccupiedError<'_, K, V>;
impl<'a, K: Debug + Ord, V: Debug> Display for OccupiedError<'a, K, V>;
impl<'a, K: Debug + Ord, V: Debug> Error for OccupiedError<'a, K, V>;
// std::collections::hash_map
impl<K: Eq + Hash, V, S: BuildHasher> HashMap<K, V, S> {
pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V>>;
}
pub struct OccupiedError<'a, K: 'a, V: 'a> {
pub entry: OccupiedEntry<'a, K, V>,
pub value: V,
}
impl<K: Debug, V: Debug> Debug for OccupiedError<'_, K, V>;
impl<'a, K: Debug, V: Debug> fmt::Display for OccupiedError<'a, K, V>;
impl<'a, K: Debug, V: Debug> Error for OccupiedError<'a, K, V>;
Steps / History
- Issue: Missing a good way to insert into a HashMap while panicking on duplicates rfcs#3092
- Implementation: Add {BTreeMap,HashMap}::try_insert #82764
- Final commenting period (FCP)
- Stabilization PR
Unresolved Questions
- Should
OccupiedError
implement Error (and Display)? Add {BTreeMap,HashMap}::try_insert #82764 (comment) - Should
OccupiedError
have public fields, or accessors? Add {BTreeMap,HashMap}::try_insert #82764 (comment) try_
might imply it returns anErr
when allocating fails, which is not the case. Maybe rename it toinsert_new
or something?- Put the
key: K
argument into theOccupiedError
?