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> {
845845 pub fn take ( & mut self ) -> Option < T > {
846846 mem:: replace ( self , None )
847847 }
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+ }
848875}
849876
850877impl < ' a , T : Clone > Option < & ' a T > {
Original file line number Diff line number Diff line change 4444#![ feature( reverse_bits) ]
4545#![ feature( iterator_find_map) ]
4646#![ feature( slice_internals) ]
47+ #![ feature( option_replace) ]
4748
4849extern crate core;
4950extern crate test;
Original file line number Diff line number Diff line change @@ -297,3 +297,18 @@ fn test_try() {
297297 }
298298 assert_eq ! ( try_option_err( ) , Err ( NoneError ) ) ;
299299}
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