Skip to content

Commit 1c2151b

Browse files
Add unwrap_or_default method to Result
1 parent d337f34 commit 1c2151b

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

src/libcore/result.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -792,6 +792,39 @@ 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+
/// let good_year_from_input = "1909";
811+
/// let bad_year_from_input = "190blarg";
812+
/// let good_year = good_year_from_input.parse().unwrap_or_default();
813+
/// let bad_year = bad_year_from_input.parse().unwrap_or_default();
814+
///
815+
/// assert_eq!(1909, good_year);
816+
/// assert_eq!(0, bad_year);
817+
/// ```
818+
#[inline]
819+
#[stable(feature = "rust1", since = "1.0.0")]
820+
pub fn unwrap_or_default(self) -> T {
821+
match self {
822+
Ok(x) => x,
823+
Err(_) => Default::default(),
824+
}
825+
}
826+
}
827+
795828
// This is a separate function to reduce the code size of the methods
796829
#[inline(never)]
797830
#[cold]

src/libcoretest/result.rs

Lines changed: 6 additions & 0 deletions
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)