diff options
author | bors <bors@rust-lang.org> | 2016-11-01 03:53:42 -0700 |
---|---|---|
committer | GitHub <noreply@github.com> | 2016-11-01 03:53:42 -0700 |
commit | ac968c466451cb9aafd9e8598ddb396ed0e6fe31 (patch) | |
tree | c8876882be5803e7bf2074c50e22f53c34faa0eb /src/libcore/result.rs | |
parent | 73f5cad6c436bb3fdf460d9671d92d1133c614a2 (diff) | |
parent | 5d31a818df97e8a71545e5ba6de0627abb7837ee (diff) | |
download | rust-ac968c466451cb9aafd9e8598ddb396ed0e6fe31.tar.gz |
Auto merge of #37299 - devonhollowood:result-unwrap-or-default, r=alexcrichton
Add `unwrap_or_default` method to `Result`
Fixes #37025
Diffstat (limited to 'src/libcore/result.rs')
-rw-r--r-- | src/libcore/result.rs | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 9cb42124e00..3d34f620067 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -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] |