@@ -2173,9 +2173,37 @@ impl<T, A: Allocator> Vec<T, A> {
21732173 panic ! ( "removal index (is {index}) should be < len (is {len})" ) ;
21742174 }
21752175
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 > {
21762204 let len = self . len ( ) ;
21772205 if index >= len {
2178- assert_failed ( index , len ) ;
2206+ return None ;
21792207 }
21802208 unsafe {
21812209 // infallible
@@ -2191,7 +2219,7 @@ impl<T, A: Allocator> Vec<T, A> {
21912219 ptr:: copy ( ptr. add ( 1 ) , ptr, len - index - 1 ) ;
21922220 }
21932221 self . set_len ( len - 1 ) ;
2194- ret
2222+ Some ( ret)
21952223 }
21962224 }
21972225
0 commit comments