-
Notifications
You must be signed in to change notification settings - Fork 12.9k
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
Changes from 1 commit
1c2151b
fb1ef4f
0958505
5d31a81
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -792,6 +792,39 @@ 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. | ||
/// | ||
/// ``` | ||
/// 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); | ||
/// ``` | ||
#[inline] | ||
#[stable(feature = "rust1", since = "1.0.0")] | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is this There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This should probably start as There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. instruction: Should be unstable, no version number. Pick a new feature name, for example "result_unwrap_or_default". Use |
||
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] | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It'd be nice to link
FromStr
to theFromStr
docs page