@@ -792,6 +792,44 @@ impl<T: fmt::Debug, E> Result<T, E> {
792
792
}
793
793
}
794
794
795
+ impl < T : Default , E > Result < T , E > {
796
+ /// Returns the contained value or a default
797
+ ///
798
+ /// Consumes the `self` argument then, if `Ok`, returns the contained
799
+ /// value, otherwise if `Err`, returns the default value for that
800
+ /// type.
801
+ ///
802
+ /// # Examples
803
+ ///
804
+ /// Convert a string to an integer, turning poorly-formed strings
805
+ /// into 0 (the default value for integers). [`parse`] converts
806
+ /// a string to any other type that implements [`FromStr`], returning an
807
+ /// `Err` on error.
808
+ ///
809
+ /// ```
810
+ /// #![feature(result_unwrap_or_default)]
811
+ ///
812
+ /// let good_year_from_input = "1909";
813
+ /// let bad_year_from_input = "190blarg";
814
+ /// let good_year = good_year_from_input.parse().unwrap_or_default();
815
+ /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
816
+ ///
817
+ /// assert_eq!(1909, good_year);
818
+ /// assert_eq!(0, bad_year);
819
+ ///
820
+ /// [`parse`]: ../../std/primitive.str.html#method.parse
821
+ /// [`FromStr`]: ../../std/str/trait.FromStr.html
822
+ /// ```
823
+ #[ inline]
824
+ #[ unstable( feature = "result_unwrap_or_default" , issue = "0" ) ]
825
+ pub fn unwrap_or_default ( self ) -> T {
826
+ match self {
827
+ Ok ( x) => x,
828
+ Err ( _) => Default :: default ( ) ,
829
+ }
830
+ }
831
+ }
832
+
795
833
// This is a separate function to reduce the code size of the methods
796
834
#[ inline( never) ]
797
835
#[ cold]
0 commit comments