@@ -1241,6 +1241,46 @@ impl<K, V, S> HashMap<K, V, S>
1241
1241
self . search_mut ( k) . into_occupied_bucket ( ) . map ( |bucket| pop_internal ( bucket) . 1 )
1242
1242
}
1243
1243
1244
+ /// Removes a key from the map, returning the stored key and value if the
1245
+ /// key was previously in the map.
1246
+ ///
1247
+ /// The key may be any borrowed form of the map's key type, but
1248
+ /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1249
+ /// the key type.
1250
+ ///
1251
+ /// [`Eq`]: ../../std/cmp/trait.Eq.html
1252
+ /// [`Hash`]: ../../std/hash/trait.Hash.html
1253
+ ///
1254
+ /// # Examples
1255
+ ///
1256
+ /// ```
1257
+ /// #![feature(hash_map_remove_entry)]
1258
+ /// use std::collections::HashMap;
1259
+ ///
1260
+ /// # fn main() {
1261
+ /// let mut map = HashMap::new();
1262
+ /// map.insert(1, "a");
1263
+ /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1264
+ /// assert_eq!(map.remove(&1), None);
1265
+ /// # }
1266
+ /// ```
1267
+ #[ unstable( feature = "hash_map_remove_entry" , issue = "46344" ) ]
1268
+ pub fn remove_entry < Q : ?Sized > ( & mut self , k : & Q ) -> Option < ( K , V ) >
1269
+ where K : Borrow < Q > ,
1270
+ Q : Hash + Eq
1271
+ {
1272
+ if self . table . size ( ) == 0 {
1273
+ return None ;
1274
+ }
1275
+
1276
+ self . search_mut ( k)
1277
+ . into_occupied_bucket ( )
1278
+ . map ( |bucket| {
1279
+ let ( k, v, _) = pop_internal ( bucket) ;
1280
+ ( k, v)
1281
+ } )
1282
+ }
1283
+
1244
1284
/// Retains only the elements specified by the predicate.
1245
1285
///
1246
1286
/// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`.
@@ -3040,13 +3080,21 @@ mod test_map {
3040
3080
}
3041
3081
3042
3082
#[ test]
3043
- fn test_pop ( ) {
3083
+ fn test_remove ( ) {
3044
3084
let mut m = HashMap :: new ( ) ;
3045
3085
m. insert ( 1 , 2 ) ;
3046
3086
assert_eq ! ( m. remove( & 1 ) , Some ( 2 ) ) ;
3047
3087
assert_eq ! ( m. remove( & 1 ) , None ) ;
3048
3088
}
3049
3089
3090
+ #[ test]
3091
+ fn test_remove_entry ( ) {
3092
+ let mut m = HashMap :: new ( ) ;
3093
+ m. insert ( 1 , 2 ) ;
3094
+ assert_eq ! ( m. remove_entry( & 1 ) , Some ( ( 1 , 2 ) ) ) ;
3095
+ assert_eq ! ( m. remove( & 1 ) , None ) ;
3096
+ }
3097
+
3050
3098
#[ test]
3051
3099
fn test_iterate ( ) {
3052
3100
let mut m = HashMap :: with_capacity ( 4 ) ;
0 commit comments