Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add unwrap_or_default method to Result #37299

Merged
merged 4 commits into from
Nov 1, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/libcore/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -792,6 +792,44 @@ impl<T: fmt::Debug, E> Result<T, E> {
}
}

impl<T: Default, E> Result<T, E> {
/// Returns the contained value or a default
///
/// Consumes the `self` argument then, if `Ok`, returns the contained
/// value, otherwise if `Err`, returns the default value for that
/// type.
///
/// # Examples
///
/// Convert a string to an integer, turning poorly-formed strings
/// into 0 (the default value for integers). [`parse`] converts
/// a string to any other type that implements [`FromStr`], returning an
/// `Err` on error.
///
/// ```
/// #![feature(result_unwrap_or_default)]
///
/// let good_year_from_input = "1909";
/// let bad_year_from_input = "190blarg";
/// let good_year = good_year_from_input.parse().unwrap_or_default();
/// let bad_year = bad_year_from_input.parse().unwrap_or_default();
///
/// assert_eq!(1909, good_year);
/// assert_eq!(0, bad_year);
///
/// [`parse`]: ../../std/primitive.str.html#method.parse
/// [`FromStr`]: ../../std/str/trait.FromStr.html
/// ```
#[inline]
#[unstable(feature = "result_unwrap_or_default", issue = "0")]
pub fn unwrap_or_default(self) -> T {
match self {
Ok(x) => x,
Err(_) => Default::default(),
}
}
}

// This is a separate function to reduce the code size of the methods
#[inline(never)]
#[cold]
Expand Down
1 change: 1 addition & 0 deletions src/libcoretest/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
#![feature(unique)]
#![feature(iter_max_by)]
#![feature(iter_min_by)]
#![feature(result_unwrap_or_default)]

extern crate core;
extern crate test;
Expand Down
6 changes: 6 additions & 0 deletions src/libcoretest/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,3 +183,9 @@ pub fn test_iter_mut() {
}
assert_eq!(err, Err("error"));
}

#[test]
pub fn test_unwrap_or_default() {
assert_eq!(op1().unwrap_or_default(), 666);
assert_eq!(op2().unwrap_or_default(), 0);
}