File tree Expand file tree Collapse file tree 3 files changed +43
-0
lines changed Expand file tree Collapse file tree 3 files changed +43
-0
lines changed Original file line number Diff line number Diff line change @@ -845,6 +845,33 @@ impl<T> Option<T> {
845
845
pub fn take ( & mut self ) -> Option < T > {
846
846
mem:: replace ( self , None )
847
847
}
848
+
849
+ /// Replaces the actual value in the option by the value given in parameter,
850
+ /// returning the old value if present,
851
+ /// leaving a [`Some`] in its place without deinitializing either one.
852
+ ///
853
+ /// [`Some`]: #variant.Some
854
+ ///
855
+ /// # Examples
856
+ ///
857
+ /// ```
858
+ /// #![feature(option_replace)]
859
+ ///
860
+ /// let mut x = Some(2);
861
+ /// let old = x.replace(5);
862
+ /// assert_eq!(x, Some(5));
863
+ /// assert_eq!(old, Some(2));
864
+ ///
865
+ /// let mut x = None;
866
+ /// let old = x.replace(3);
867
+ /// assert_eq!(x, Some(3));
868
+ /// assert_eq!(old, None);
869
+ /// ```
870
+ #[ inline]
871
+ #[ unstable( feature = "option_replace" , issue = "51998" ) ]
872
+ pub fn replace ( & mut self , value : T ) -> Option < T > {
873
+ mem:: replace ( self , Some ( value) )
874
+ }
848
875
}
849
876
850
877
impl < ' a , T : Clone > Option < & ' a T > {
Original file line number Diff line number Diff line change 44
44
#![ feature( reverse_bits) ]
45
45
#![ feature( iterator_find_map) ]
46
46
#![ feature( slice_internals) ]
47
+ #![ feature( option_replace) ]
47
48
48
49
extern crate core;
49
50
extern crate test;
Original file line number Diff line number Diff line change @@ -297,3 +297,18 @@ fn test_try() {
297
297
}
298
298
assert_eq ! ( try_option_err( ) , Err ( NoneError ) ) ;
299
299
}
300
+
301
+ #[ test]
302
+ fn test_replace ( ) {
303
+ let mut x = Some ( 2 ) ;
304
+ let old = x. replace ( 5 ) ;
305
+
306
+ assert_eq ! ( x, Some ( 5 ) ) ;
307
+ assert_eq ! ( old, Some ( 2 ) ) ;
308
+
309
+ let mut x = None ;
310
+ let old = x. replace ( 3 ) ;
311
+
312
+ assert_eq ! ( x, Some ( 3 ) ) ;
313
+ assert_eq ! ( old, None ) ;
314
+ }
You can’t perform that action at this time.
0 commit comments