@@ -594,34 +594,6 @@ impl<T> Option<T> {
594
594
}
595
595
}
596
596
597
- /// Inserts `value` into the option then returns a mutable reference to it.
598
- ///
599
- /// If the option already contains a value, the old value is dropped.
600
- ///
601
- /// # Example
602
- ///
603
- /// ```
604
- /// let mut opt = None;
605
- /// let val = opt.insert(1);
606
- /// assert_eq!(*val, 1);
607
- /// assert_eq!(opt.unwrap(), 1);
608
- /// let val = opt.insert(2);
609
- /// assert_eq!(*val, 2);
610
- /// *val = 3;
611
- /// assert_eq!(opt.unwrap(), 3);
612
- /// ```
613
- #[ inline]
614
- #[ stable( feature = "option_insert" , since = "1.53.0" ) ]
615
- pub fn insert ( & mut self , value : T ) -> & mut T {
616
- * self = Some ( value) ;
617
-
618
- match self {
619
- Some ( v) => v,
620
- // SAFETY: the code above just filled the option
621
- None => unsafe { hint:: unreachable_unchecked ( ) } ,
622
- }
623
- }
624
-
625
597
/////////////////////////////////////////////////////////////////////////
626
598
// Iterator constructors
627
599
/////////////////////////////////////////////////////////////////////////
@@ -849,12 +821,46 @@ impl<T> Option<T> {
849
821
}
850
822
851
823
/////////////////////////////////////////////////////////////////////////
852
- // Entry-like operations to insert if None and return a reference
824
+ // Entry-like operations to insert a value and return a reference
853
825
/////////////////////////////////////////////////////////////////////////
854
826
827
+ /// Inserts `value` into the option then returns a mutable reference to it.
828
+ ///
829
+ /// If the option already contains a value, the old value is dropped.
830
+ ///
831
+ /// See also [`Option::get_or_insert`], which doesn't update the value if
832
+ /// the option already contains [`Some`].
833
+ ///
834
+ /// # Example
835
+ ///
836
+ /// ```
837
+ /// let mut opt = None;
838
+ /// let val = opt.insert(1);
839
+ /// assert_eq!(*val, 1);
840
+ /// assert_eq!(opt.unwrap(), 1);
841
+ /// let val = opt.insert(2);
842
+ /// assert_eq!(*val, 2);
843
+ /// *val = 3;
844
+ /// assert_eq!(opt.unwrap(), 3);
845
+ /// ```
846
+ #[ inline]
847
+ #[ stable( feature = "option_insert" , since = "1.53.0" ) ]
848
+ pub fn insert ( & mut self , value : T ) -> & mut T {
849
+ * self = Some ( value) ;
850
+
851
+ match self {
852
+ Some ( v) => v,
853
+ // SAFETY: the code above just filled the option
854
+ None => unsafe { hint:: unreachable_unchecked ( ) } ,
855
+ }
856
+ }
857
+
855
858
/// Inserts `value` into the option if it is [`None`], then
856
859
/// returns a mutable reference to the contained value.
857
860
///
861
+ /// See also [`Option::insert`], which updates the value even if
862
+ /// the option already contains [`Some`].
863
+ ///
858
864
/// # Examples
859
865
///
860
866
/// ```
0 commit comments