@@ -2173,9 +2173,38 @@ 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+ #[ track_caller]
2203+ #[ rustc_confusables( "delete" , "take" , "remove" ) ]
2204+ pub fn try_remove ( & mut self , index : usize ) -> Option < T > {
21762205 let len = self . len ( ) ;
21772206 if index >= len {
2178- assert_failed ( index , len ) ;
2207+ return None ;
21792208 }
21802209 unsafe {
21812210 // infallible
@@ -2191,7 +2220,7 @@ impl<T, A: Allocator> Vec<T, A> {
21912220 ptr:: copy ( ptr. add ( 1 ) , ptr, len - index - 1 ) ;
21922221 }
21932222 self . set_len ( len - 1 ) ;
2194- ret
2223+ Some ( ret)
21952224 }
21962225 }
21972226
0 commit comments