Skip to content

Commit ac968c4

Browse files
authored
Auto merge of #37299 - devonhollowood:result-unwrap-or-default, r=alexcrichton
Add `unwrap_or_default` method to `Result` Fixes #37025
2 parents 73f5cad + 5d31a81 commit ac968c4

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

src/libcore/result.rs

+38
Original file line numberDiff line numberDiff line change
@@ -792,6 +792,44 @@ impl<T: fmt::Debug, E> Result<T, E> {
792792
}
793793
}
794794

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+
795833
// This is a separate function to reduce the code size of the methods
796834
#[inline(never)]
797835
#[cold]

src/libcoretest/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
#![feature(unique)]
3535
#![feature(iter_max_by)]
3636
#![feature(iter_min_by)]
37+
#![feature(result_unwrap_or_default)]
3738

3839
extern crate core;
3940
extern crate test;

src/libcoretest/result.rs

+6
Original file line numberDiff line numberDiff line change
@@ -183,3 +183,9 @@ pub fn test_iter_mut() {
183183
}
184184
assert_eq!(err, Err("error"));
185185
}
186+
187+
#[test]
188+
pub fn test_unwrap_or_default() {
189+
assert_eq!(op1().unwrap_or_default(), 666);
190+
assert_eq!(op2().unwrap_or_default(), 0);
191+
}

0 commit comments

Comments
 (0)