From 1c2151b7f9b460cda4a028f7ad031d9dae3f5913 Mon Sep 17 00:00:00 2001 From: Devon Hollowood Date: Wed, 19 Oct 2016 22:08:49 -0700 Subject: [PATCH] Add `unwrap_or_default` method to `Result` --- src/libcore/result.rs | 33 +++++++++++++++++++++++++++++++++ src/libcoretest/result.rs | 6 ++++++ 2 files changed, 39 insertions(+) diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 96845259299..8964b29b3a6 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -792,6 +792,39 @@ impl Result { } } +impl Result { + /// 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")] + 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] diff --git a/src/libcoretest/result.rs b/src/libcoretest/result.rs index 6e9f653dcd8..bc2cd8bbfc6 100644 --- a/src/libcoretest/result.rs +++ b/src/libcoretest/result.rs @@ -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); +}