@@ -842,6 +842,40 @@ where
842
842
self . base . insert ( k, v)
843
843
}
844
844
845
+ /// Tries to insert a key-value pair into the map, and returns
846
+ /// a mutable reference to the value in the entry.
847
+ ///
848
+ /// If the map already had this key present, nothing is updated, and
849
+ /// an error containing the occupied entry and the value is returned.
850
+ ///
851
+ /// # Examples
852
+ ///
853
+ /// Basic usage:
854
+ ///
855
+ /// ```
856
+ /// #![feature(map_try_insert)]
857
+ ///
858
+ /// use std::collections::HashMap;
859
+ ///
860
+ /// let mut map = HashMap::new();
861
+ /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
862
+ ///
863
+ /// let err = map.try_insert(37, "b").unwrap_err();
864
+ /// assert_eq!(err.entry.key(), &37);
865
+ /// assert_eq!(err.entry.get(), &"a");
866
+ /// assert_eq!(err.value, "b");
867
+ /// ```
868
+ #[ unstable( feature = "map_try_insert" , issue = "none" ) ]
869
+ pub fn try_insert ( & mut self , key : K , value : V ) -> Result < & mut V , OccupiedError < ' _ , K , V > >
870
+ where
871
+ K : Ord ,
872
+ {
873
+ match self . entry ( key) {
874
+ Occupied ( entry) => Err ( OccupiedError { entry, value } ) ,
875
+ Vacant ( entry) => Ok ( entry. insert ( value) ) ,
876
+ }
877
+ }
878
+
845
879
/// Removes a key from the map, returning the value at the key if the key
846
880
/// was previously in the map.
847
881
///
@@ -1851,6 +1885,18 @@ impl<K: Debug, V> Debug for VacantEntry<'_, K, V> {
1851
1885
}
1852
1886
}
1853
1887
1888
+ /// The error returned by [`try_insert`](HashMap::try_insert) when the key already exists.
1889
+ ///
1890
+ /// Contains the occupied entry, and the value that was not inserted.
1891
+ #[ unstable( feature = "map_try_insert" , issue = "none" ) ]
1892
+ #[ derive( Debug ) ]
1893
+ pub struct OccupiedError < ' a , K : ' a , V : ' a > {
1894
+ /// The entry in the map that was already occupied.
1895
+ pub entry : OccupiedEntry < ' a , K , V > ,
1896
+ /// The value which was not inserted, because the entry was already occupied.
1897
+ pub value : V ,
1898
+ }
1899
+
1854
1900
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
1855
1901
impl < ' a , K , V , S > IntoIterator for & ' a HashMap < K , V , S > {
1856
1902
type Item = ( & ' a K , & ' a V ) ;
0 commit comments