@@ -2173,9 +2173,37 @@ impl<T, A: Allocator> Vec<T, A> {
2173
2173
panic ! ( "removal index (is {index}) should be < len (is {len})" ) ;
2174
2174
}
2175
2175
2176
+ match self . try_remove ( index) {
2177
+ Some ( elem) => elem,
2178
+ None => assert_failed ( index, self . len ( ) ) ,
2179
+ }
2180
+ }
2181
+
2182
+ /// Remove and return the element at position `index` within the vector,
2183
+ /// shifting all elements after it to the left, or [`None`] if it does not
2184
+ /// exist.
2185
+ ///
2186
+ /// Note: Because this shifts over the remaining elements, it has a
2187
+ /// worst-case performance of *O*(*n*). If you'd like to remove
2188
+ /// elements from the beginning of the `Vec`, consider using
2189
+ /// [`VecDeque::pop_front`] instead.
2190
+ ///
2191
+ /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
2192
+ ///
2193
+ /// # Examples
2194
+ ///
2195
+ /// ```
2196
+ /// #![feature(vec_try_remove)]
2197
+ /// let mut v = vec![1, 2, 3];
2198
+ /// assert_eq!(v.try_remove(0), Some(1));
2199
+ /// assert_eq!(v.try_remove(2), None);
2200
+ /// ```
2201
+ #[ unstable( feature = "vec_try_remove" , issue = "146954" ) ]
2202
+ #[ rustc_confusables( "delete" , "take" , "remove" ) ]
2203
+ pub fn try_remove ( & mut self , index : usize ) -> Option < T > {
2176
2204
let len = self . len ( ) ;
2177
2205
if index >= len {
2178
- assert_failed ( index , len ) ;
2206
+ return None ;
2179
2207
}
2180
2208
unsafe {
2181
2209
// infallible
@@ -2191,7 +2219,7 @@ impl<T, A: Allocator> Vec<T, A> {
2191
2219
ptr:: copy ( ptr. add ( 1 ) , ptr, len - index - 1 ) ;
2192
2220
}
2193
2221
self . set_len ( len - 1 ) ;
2194
- ret
2222
+ Some ( ret)
2195
2223
}
2196
2224
}
2197
2225
0 commit comments