Rollup merge of #92444 - dtolnay:coremethods, r=joshtriplett

Consolidate Result's and Option's methods into fewer impl blocks

`Result`'s and `Option`'s methods have historically been separated up into `impl` blocks based on their trait bounds, with the bounds specified on type parameters of the impl block. I find this unhelpful because closely related methods, like `unwrap_or` and `unwrap_or_default`, end up disproportionately far apart in source code and rustdocs:

<pre>
impl&lt;T&gt; Option&lt;T&gt; {
    pub fn unwrap_or(self, default: T) -&gt; T {
        ...
    }

    <img alt="one eternity later" src="https://user-images.githubusercontent.com/1940490/147780325-ad4e01a4-c971-436e-bdf4-e755f2d35f15.jpg" width="750">
}

impl&lt;T: Default&gt; Option&lt;T&gt; {
    pub fn unwrap_or_default(self) -&gt; T {
        ...
    }
}
</pre>

I'd prefer for method to be in as few impl blocks as possible, with the most logical grouping within each impl block. Any bounds needed can be written as `where` clauses on the method instead:

```rust
impl<T> Option<T> {
    pub fn unwrap_or(self, default: T) -> T {
        ...
    }

    pub fn unwrap_or_default(self) -> T
    where
        T: Default,
    {
        ...
    }
}
```

*Warning: the end-to-end diff of this PR is computed confusingly by git / rendered confusingly by GitHub; it's practically impossible to review that way. I've broken the PR into commits that move small groups of methods for which git behaves better &mdash; these each should be easily individually reviewable.*
This commit is contained in:
Matthias Krüger 2022-01-03 14:44:21 +01:00 committed by GitHub
commit 13e284033e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 464 additions and 447 deletions

View file

@ -810,6 +810,45 @@ impl<T> Option<T> {
} }
} }
/// Returns the contained [`Some`] value or a default.
///
/// Consumes the `self` argument then, if [`Some`], returns the contained
/// value, otherwise if [`None`], returns the [default value] for that
/// type.
///
/// # Examples
///
/// Converts 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
/// [`None`] on error.
///
/// ```
/// let good_year_from_input = "1909";
/// let bad_year_from_input = "190blarg";
/// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
/// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
///
/// assert_eq!(1909, good_year);
/// assert_eq!(0, bad_year);
/// ```
///
/// [default value]: Default::default
/// [`parse`]: str::parse
/// [`FromStr`]: crate::str::FromStr
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
pub const fn unwrap_or_default(self) -> T
where
T: ~const Default,
{
match self {
Some(x) => x,
None => Default::default(),
}
}
/// Returns the contained [`Some`] value, consuming the `self` value, /// Returns the contained [`Some`] value, consuming the `self` value,
/// without checking that the value is not [`None`]. /// without checking that the value is not [`None`].
/// ///
@ -1033,6 +1072,58 @@ impl<T> Option<T> {
} }
} }
/// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.
///
/// Leaves the original Option in-place, creating a new one with a reference
/// to the original one, additionally coercing the contents via [`Deref`].
///
/// # Examples
///
/// ```
/// let x: Option<String> = Some("hey".to_owned());
/// assert_eq!(x.as_deref(), Some("hey"));
///
/// let x: Option<String> = None;
/// assert_eq!(x.as_deref(), None);
/// ```
#[stable(feature = "option_deref", since = "1.40.0")]
#[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
pub const fn as_deref(&self) -> Option<&T::Target>
where
T: ~const Deref,
{
match self.as_ref() {
Some(t) => Some(t.deref()),
None => None,
}
}
/// Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`.
///
/// Leaves the original `Option` in-place, creating a new one containing a mutable reference to
/// the inner type's [`Deref::Target`] type.
///
/// # Examples
///
/// ```
/// let mut x: Option<String> = Some("hey".to_owned());
/// assert_eq!(x.as_deref_mut().map(|x| {
/// x.make_ascii_uppercase();
/// x
/// }), Some("HEY".to_owned().as_mut_str()));
/// ```
#[stable(feature = "option_deref", since = "1.40.0")]
#[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
pub const fn as_deref_mut(&mut self) -> Option<&mut T::Target>
where
T: ~const DerefMut,
{
match self.as_mut() {
Some(t) => Some(t.deref_mut()),
None => None,
}
}
///////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////
// Iterator constructors // Iterator constructors
///////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////
@ -1581,7 +1672,7 @@ impl<T, U> Option<(T, U)> {
} }
} }
impl<T: Copy> Option<&T> { impl<T> Option<&T> {
/// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
/// option. /// option.
/// ///
@ -1597,7 +1688,10 @@ impl<T: Copy> Option<&T> {
#[must_use = "`self` will be dropped if the result is not used"] #[must_use = "`self` will be dropped if the result is not used"]
#[stable(feature = "copied", since = "1.35.0")] #[stable(feature = "copied", since = "1.35.0")]
#[rustc_const_unstable(feature = "const_option", issue = "67441")] #[rustc_const_unstable(feature = "const_option", issue = "67441")]
pub const fn copied(self) -> Option<T> { pub const fn copied(self) -> Option<T>
where
T: Copy,
{
// FIXME: this implementation, which sidesteps using `Option::map` since it's not const // FIXME: this implementation, which sidesteps using `Option::map` since it's not const
// ready yet, should be reverted when possible to avoid code repetition // ready yet, should be reverted when possible to avoid code repetition
match self { match self {
@ -1605,33 +1699,7 @@ impl<T: Copy> Option<&T> {
None => None, None => None,
} }
} }
}
impl<T: Copy> Option<&mut T> {
/// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the
/// option.
///
/// # Examples
///
/// ```
/// let mut x = 12;
/// let opt_x = Some(&mut x);
/// assert_eq!(opt_x, Some(&mut 12));
/// let copied = opt_x.copied();
/// assert_eq!(copied, Some(12));
/// ```
#[must_use = "`self` will be dropped if the result is not used"]
#[stable(feature = "copied", since = "1.35.0")]
#[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
pub const fn copied(self) -> Option<T> {
match self {
Some(&mut t) => Some(t),
None => None,
}
}
}
impl<T: Clone> Option<&T> {
/// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
/// option. /// option.
/// ///
@ -1658,7 +1726,32 @@ impl<T: Clone> Option<&T> {
} }
} }
impl<T: Clone> Option<&mut T> { impl<T> Option<&mut T> {
/// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the
/// option.
///
/// # Examples
///
/// ```
/// let mut x = 12;
/// let opt_x = Some(&mut x);
/// assert_eq!(opt_x, Some(&mut 12));
/// let copied = opt_x.copied();
/// assert_eq!(copied, Some(12));
/// ```
#[must_use = "`self` will be dropped if the result is not used"]
#[stable(feature = "copied", since = "1.35.0")]
#[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
pub const fn copied(self) -> Option<T>
where
T: Copy,
{
match self {
Some(&mut t) => Some(t),
None => None,
}
}
/// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
/// option. /// option.
/// ///
@ -1685,103 +1778,6 @@ impl<T: Clone> Option<&mut T> {
} }
} }
impl<T: Default> Option<T> {
/// Returns the contained [`Some`] value or a default.
///
/// Consumes the `self` argument then, if [`Some`], returns the contained
/// value, otherwise if [`None`], returns the [default value] for that
/// type.
///
/// # Examples
///
/// Converts 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
/// [`None`] on error.
///
/// ```
/// let good_year_from_input = "1909";
/// let bad_year_from_input = "190blarg";
/// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
/// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
///
/// assert_eq!(1909, good_year);
/// assert_eq!(0, bad_year);
/// ```
///
/// [default value]: Default::default
/// [`parse`]: str::parse
/// [`FromStr`]: crate::str::FromStr
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
pub const fn unwrap_or_default(self) -> T
where
T: ~const Default,
{
match self {
Some(x) => x,
None => Default::default(),
}
}
}
impl<T: Deref> Option<T> {
/// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.
///
/// Leaves the original Option in-place, creating a new one with a reference
/// to the original one, additionally coercing the contents via [`Deref`].
///
/// # Examples
///
/// ```
/// let x: Option<String> = Some("hey".to_owned());
/// assert_eq!(x.as_deref(), Some("hey"));
///
/// let x: Option<String> = None;
/// assert_eq!(x.as_deref(), None);
/// ```
#[stable(feature = "option_deref", since = "1.40.0")]
#[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
pub const fn as_deref(&self) -> Option<&T::Target>
where
T: ~const Deref,
{
match self.as_ref() {
Some(t) => Some(t.deref()),
None => None,
}
}
}
impl<T: DerefMut> Option<T> {
/// Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`.
///
/// Leaves the original `Option` in-place, creating a new one containing a mutable reference to
/// the inner type's [`Deref::Target`] type.
///
/// # Examples
///
/// ```
/// let mut x: Option<String> = Some("hey".to_owned());
/// assert_eq!(x.as_deref_mut().map(|x| {
/// x.make_ascii_uppercase();
/// x
/// }), Some("HEY".to_owned().as_mut_str()));
/// ```
#[stable(feature = "option_deref", since = "1.40.0")]
#[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
pub const fn as_deref_mut(&mut self) -> Option<&mut T::Target>
where
T: ~const DerefMut,
{
match self.as_mut() {
Some(t) => Some(t.deref_mut()),
None => None,
}
}
}
impl<T, E> Option<Result<T, E>> { impl<T, E> Option<Result<T, E>> {
/// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`. /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`.
/// ///

View file

@ -901,6 +901,56 @@ impl<T, E> Result<T, E> {
self self
} }
/// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&<T as Deref>::Target, &E>`.
///
/// Coerces the [`Ok`] variant of the original [`Result`] via [`Deref`](crate::ops::Deref)
/// and returns the new [`Result`].
///
/// # Examples
///
/// ```
/// let x: Result<String, u32> = Ok("hello".to_string());
/// let y: Result<&str, &u32> = Ok("hello");
/// assert_eq!(x.as_deref(), y);
///
/// let x: Result<String, u32> = Err(42);
/// let y: Result<&str, &u32> = Err(&42);
/// assert_eq!(x.as_deref(), y);
/// ```
#[stable(feature = "inner_deref", since = "1.47.0")]
pub fn as_deref(&self) -> Result<&T::Target, &E>
where
T: Deref,
{
self.as_ref().map(|t| t.deref())
}
/// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut <T as DerefMut>::Target, &mut E>`.
///
/// Coerces the [`Ok`] variant of the original [`Result`] via [`DerefMut`](crate::ops::DerefMut)
/// and returns the new [`Result`].
///
/// # Examples
///
/// ```
/// let mut s = "HELLO".to_string();
/// let mut x: Result<String, u32> = Ok("hello".to_string());
/// let y: Result<&mut str, &mut u32> = Ok(&mut s);
/// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
///
/// let mut i = 42;
/// let mut x: Result<String, u32> = Err(42);
/// let y: Result<&mut str, &mut u32> = Err(&mut i);
/// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
/// ```
#[stable(feature = "inner_deref", since = "1.47.0")]
pub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E>
where
T: DerefMut,
{
self.as_mut().map(|t| t.deref_mut())
}
///////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////
// Iterator constructors // Iterator constructors
///////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////
@ -951,6 +1001,253 @@ impl<T, E> Result<T, E> {
IterMut { inner: self.as_mut().ok() } IterMut { inner: self.as_mut().ok() }
} }
/////////////////////////////////////////////////////////////////////////
// Extract a value
/////////////////////////////////////////////////////////////////////////
/// Returns the contained [`Ok`] value, consuming the `self` value.
///
/// # Panics
///
/// Panics if the value is an [`Err`], with a panic message including the
/// passed message, and the content of the [`Err`].
///
///
/// # Examples
///
/// Basic usage:
///
/// ```should_panic
/// let x: Result<u32, &str> = Err("emergency failure");
/// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
/// ```
#[inline]
#[track_caller]
#[stable(feature = "result_expect", since = "1.4.0")]
pub fn expect(self, msg: &str) -> T
where
E: fmt::Debug,
{
match self {
Ok(t) => t,
Err(e) => unwrap_failed(msg, &e),
}
}
/// Returns the contained [`Ok`] value, consuming the `self` value.
///
/// Because this function may panic, its use is generally discouraged.
/// Instead, prefer to use pattern matching and handle the [`Err`]
/// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
/// [`unwrap_or_default`].
///
/// [`unwrap_or`]: Result::unwrap_or
/// [`unwrap_or_else`]: Result::unwrap_or_else
/// [`unwrap_or_default`]: Result::unwrap_or_default
///
/// # Panics
///
/// Panics if the value is an [`Err`], with a panic message provided by the
/// [`Err`]'s value.
///
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let x: Result<u32, &str> = Ok(2);
/// assert_eq!(x.unwrap(), 2);
/// ```
///
/// ```should_panic
/// let x: Result<u32, &str> = Err("emergency failure");
/// x.unwrap(); // panics with `emergency failure`
/// ```
#[inline]
#[track_caller]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn unwrap(self) -> T
where
E: fmt::Debug,
{
match self {
Ok(t) => t,
Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e),
}
}
/// Returns the contained [`Ok`] 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
///
/// Converts 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);
/// ```
///
/// [`parse`]: str::parse
/// [`FromStr`]: crate::str::FromStr
#[inline]
#[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
pub fn unwrap_or_default(self) -> T
where
T: Default,
{
match self {
Ok(x) => x,
Err(_) => Default::default(),
}
}
/// Returns the contained [`Err`] value, consuming the `self` value.
///
/// # Panics
///
/// Panics if the value is an [`Ok`], with a panic message including the
/// passed message, and the content of the [`Ok`].
///
///
/// # Examples
///
/// Basic usage:
///
/// ```should_panic
/// let x: Result<u32, &str> = Ok(10);
/// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
/// ```
#[inline]
#[track_caller]
#[stable(feature = "result_expect_err", since = "1.17.0")]
pub fn expect_err(self, msg: &str) -> E
where
T: fmt::Debug,
{
match self {
Ok(t) => unwrap_failed(msg, &t),
Err(e) => e,
}
}
/// Returns the contained [`Err`] value, consuming the `self` value.
///
/// # Panics
///
/// Panics if the value is an [`Ok`], with a custom panic message provided
/// by the [`Ok`]'s value.
///
/// # Examples
///
/// ```should_panic
/// let x: Result<u32, &str> = Ok(2);
/// x.unwrap_err(); // panics with `2`
/// ```
///
/// ```
/// let x: Result<u32, &str> = Err("emergency failure");
/// assert_eq!(x.unwrap_err(), "emergency failure");
/// ```
#[inline]
#[track_caller]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn unwrap_err(self) -> E
where
T: fmt::Debug,
{
match self {
Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t),
Err(e) => e,
}
}
/// Returns the contained [`Ok`] value, but never panics.
///
/// Unlike [`unwrap`], this method is known to never panic on the
/// result types it is implemented for. Therefore, it can be used
/// instead of `unwrap` as a maintainability safeguard that will fail
/// to compile if the error type of the `Result` is later changed
/// to an error that can actually occur.
///
/// [`unwrap`]: Result::unwrap
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # #![feature(never_type)]
/// # #![feature(unwrap_infallible)]
///
/// fn only_good_news() -> Result<String, !> {
/// Ok("this is fine".into())
/// }
///
/// let s: String = only_good_news().into_ok();
/// println!("{}", s);
/// ```
#[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
#[inline]
pub fn into_ok(self) -> T
where
E: Into<!>,
{
match self {
Ok(x) => x,
Err(e) => e.into(),
}
}
/// Returns the contained [`Err`] value, but never panics.
///
/// Unlike [`unwrap_err`], this method is known to never panic on the
/// result types it is implemented for. Therefore, it can be used
/// instead of `unwrap_err` as a maintainability safeguard that will fail
/// to compile if the ok type of the `Result` is later changed
/// to a type that can actually occur.
///
/// [`unwrap_err`]: Result::unwrap_err
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # #![feature(never_type)]
/// # #![feature(unwrap_infallible)]
///
/// fn only_bad_news() -> Result<!, String> {
/// Err("Oops, it failed".into())
/// }
///
/// let error: String = only_bad_news().into_err();
/// println!("{}", error);
/// ```
#[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
#[inline]
pub fn into_err(self) -> E
where
T: Into<!>,
{
match self {
Ok(x) => x.into(),
Err(e) => e,
}
}
//////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////
// Boolean operations on the values, eager and lazy // Boolean operations on the values, eager and lazy
///////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////
@ -1196,7 +1493,7 @@ impl<T, E> Result<T, E> {
} }
} }
impl<T: Copy, E> Result<&T, E> { impl<T, E> Result<&T, E> {
/// Maps a `Result<&T, E>` to a `Result<T, E>` by copying the contents of the /// Maps a `Result<&T, E>` to a `Result<T, E>` by copying the contents of the
/// `Ok` part. /// `Ok` part.
/// ///
@ -1211,32 +1508,13 @@ impl<T: Copy, E> Result<&T, E> {
/// assert_eq!(copied, Ok(12)); /// assert_eq!(copied, Ok(12));
/// ``` /// ```
#[unstable(feature = "result_copied", reason = "newly added", issue = "63168")] #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
pub fn copied(self) -> Result<T, E> { pub fn copied(self) -> Result<T, E>
where
T: Copy,
{
self.map(|&t| t) self.map(|&t| t)
} }
}
impl<T: Copy, E> Result<&mut T, E> {
/// Maps a `Result<&mut T, E>` to a `Result<T, E>` by copying the contents of the
/// `Ok` part.
///
/// # Examples
///
/// ```
/// #![feature(result_copied)]
/// let mut val = 12;
/// let x: Result<&mut i32, i32> = Ok(&mut val);
/// assert_eq!(x, Ok(&mut 12));
/// let copied = x.copied();
/// assert_eq!(copied, Ok(12));
/// ```
#[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
pub fn copied(self) -> Result<T, E> {
self.map(|&mut t| t)
}
}
impl<T: Clone, E> Result<&T, E> {
/// Maps a `Result<&T, E>` to a `Result<T, E>` by cloning the contents of the /// Maps a `Result<&T, E>` to a `Result<T, E>` by cloning the contents of the
/// `Ok` part. /// `Ok` part.
/// ///
@ -1251,12 +1529,36 @@ impl<T: Clone, E> Result<&T, E> {
/// assert_eq!(cloned, Ok(12)); /// assert_eq!(cloned, Ok(12));
/// ``` /// ```
#[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")] #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
pub fn cloned(self) -> Result<T, E> { pub fn cloned(self) -> Result<T, E>
where
T: Clone,
{
self.map(|t| t.clone()) self.map(|t| t.clone())
} }
} }
impl<T: Clone, E> Result<&mut T, E> { impl<T, E> Result<&mut T, E> {
/// Maps a `Result<&mut T, E>` to a `Result<T, E>` by copying the contents of the
/// `Ok` part.
///
/// # Examples
///
/// ```
/// #![feature(result_copied)]
/// let mut val = 12;
/// let x: Result<&mut i32, i32> = Ok(&mut val);
/// assert_eq!(x, Ok(&mut 12));
/// let copied = x.copied();
/// assert_eq!(copied, Ok(12));
/// ```
#[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
pub fn copied(self) -> Result<T, E>
where
T: Copy,
{
self.map(|&mut t| t)
}
/// Maps a `Result<&mut T, E>` to a `Result<T, E>` by cloning the contents of the /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by cloning the contents of the
/// `Ok` part. /// `Ok` part.
/// ///
@ -1271,291 +1573,14 @@ impl<T: Clone, E> Result<&mut T, E> {
/// assert_eq!(cloned, Ok(12)); /// assert_eq!(cloned, Ok(12));
/// ``` /// ```
#[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")] #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
pub fn cloned(self) -> Result<T, E> { pub fn cloned(self) -> Result<T, E>
where
T: Clone,
{
self.map(|t| t.clone()) self.map(|t| t.clone())
} }
} }
impl<T, E: fmt::Debug> Result<T, E> {
/// Returns the contained [`Ok`] value, consuming the `self` value.
///
/// # Panics
///
/// Panics if the value is an [`Err`], with a panic message including the
/// passed message, and the content of the [`Err`].
///
///
/// # Examples
///
/// Basic usage:
///
/// ```should_panic
/// let x: Result<u32, &str> = Err("emergency failure");
/// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
/// ```
#[inline]
#[track_caller]
#[stable(feature = "result_expect", since = "1.4.0")]
pub fn expect(self, msg: &str) -> T {
match self {
Ok(t) => t,
Err(e) => unwrap_failed(msg, &e),
}
}
/// Returns the contained [`Ok`] value, consuming the `self` value.
///
/// Because this function may panic, its use is generally discouraged.
/// Instead, prefer to use pattern matching and handle the [`Err`]
/// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
/// [`unwrap_or_default`].
///
/// [`unwrap_or`]: Result::unwrap_or
/// [`unwrap_or_else`]: Result::unwrap_or_else
/// [`unwrap_or_default`]: Result::unwrap_or_default
///
/// # Panics
///
/// Panics if the value is an [`Err`], with a panic message provided by the
/// [`Err`]'s value.
///
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let x: Result<u32, &str> = Ok(2);
/// assert_eq!(x.unwrap(), 2);
/// ```
///
/// ```should_panic
/// let x: Result<u32, &str> = Err("emergency failure");
/// x.unwrap(); // panics with `emergency failure`
/// ```
#[inline]
#[track_caller]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn unwrap(self) -> T {
match self {
Ok(t) => t,
Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e),
}
}
}
impl<T: fmt::Debug, E> Result<T, E> {
/// Returns the contained [`Err`] value, consuming the `self` value.
///
/// # Panics
///
/// Panics if the value is an [`Ok`], with a panic message including the
/// passed message, and the content of the [`Ok`].
///
///
/// # Examples
///
/// Basic usage:
///
/// ```should_panic
/// let x: Result<u32, &str> = Ok(10);
/// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
/// ```
#[inline]
#[track_caller]
#[stable(feature = "result_expect_err", since = "1.17.0")]
pub fn expect_err(self, msg: &str) -> E {
match self {
Ok(t) => unwrap_failed(msg, &t),
Err(e) => e,
}
}
/// Returns the contained [`Err`] value, consuming the `self` value.
///
/// # Panics
///
/// Panics if the value is an [`Ok`], with a custom panic message provided
/// by the [`Ok`]'s value.
///
/// # Examples
///
/// ```should_panic
/// let x: Result<u32, &str> = Ok(2);
/// x.unwrap_err(); // panics with `2`
/// ```
///
/// ```
/// let x: Result<u32, &str> = Err("emergency failure");
/// assert_eq!(x.unwrap_err(), "emergency failure");
/// ```
#[inline]
#[track_caller]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn unwrap_err(self) -> E {
match self {
Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t),
Err(e) => e,
}
}
}
impl<T: Default, E> Result<T, E> {
/// Returns the contained [`Ok`] 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
///
/// Converts 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);
/// ```
///
/// [`parse`]: str::parse
/// [`FromStr`]: crate::str::FromStr
#[inline]
#[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
pub fn unwrap_or_default(self) -> T {
match self {
Ok(x) => x,
Err(_) => Default::default(),
}
}
}
#[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
impl<T, E: Into<!>> Result<T, E> {
/// Returns the contained [`Ok`] value, but never panics.
///
/// Unlike [`unwrap`], this method is known to never panic on the
/// result types it is implemented for. Therefore, it can be used
/// instead of `unwrap` as a maintainability safeguard that will fail
/// to compile if the error type of the `Result` is later changed
/// to an error that can actually occur.
///
/// [`unwrap`]: Result::unwrap
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # #![feature(never_type)]
/// # #![feature(unwrap_infallible)]
///
/// fn only_good_news() -> Result<String, !> {
/// Ok("this is fine".into())
/// }
///
/// let s: String = only_good_news().into_ok();
/// println!("{}", s);
/// ```
#[inline]
pub fn into_ok(self) -> T {
match self {
Ok(x) => x,
Err(e) => e.into(),
}
}
}
#[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
impl<T: Into<!>, E> Result<T, E> {
/// Returns the contained [`Err`] value, but never panics.
///
/// Unlike [`unwrap_err`], this method is known to never panic on the
/// result types it is implemented for. Therefore, it can be used
/// instead of `unwrap_err` as a maintainability safeguard that will fail
/// to compile if the ok type of the `Result` is later changed
/// to a type that can actually occur.
///
/// [`unwrap_err`]: Result::unwrap_err
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # #![feature(never_type)]
/// # #![feature(unwrap_infallible)]
///
/// fn only_bad_news() -> Result<!, String> {
/// Err("Oops, it failed".into())
/// }
///
/// let error: String = only_bad_news().into_err();
/// println!("{}", error);
/// ```
#[inline]
pub fn into_err(self) -> E {
match self {
Ok(x) => x.into(),
Err(e) => e,
}
}
}
impl<T: Deref, E> Result<T, E> {
/// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&<T as Deref>::Target, &E>`.
///
/// Coerces the [`Ok`] variant of the original [`Result`] via [`Deref`](crate::ops::Deref)
/// and returns the new [`Result`].
///
/// # Examples
///
/// ```
/// let x: Result<String, u32> = Ok("hello".to_string());
/// let y: Result<&str, &u32> = Ok("hello");
/// assert_eq!(x.as_deref(), y);
///
/// let x: Result<String, u32> = Err(42);
/// let y: Result<&str, &u32> = Err(&42);
/// assert_eq!(x.as_deref(), y);
/// ```
#[stable(feature = "inner_deref", since = "1.47.0")]
pub fn as_deref(&self) -> Result<&T::Target, &E> {
self.as_ref().map(|t| t.deref())
}
}
impl<T: DerefMut, E> Result<T, E> {
/// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut <T as DerefMut>::Target, &mut E>`.
///
/// Coerces the [`Ok`] variant of the original [`Result`] via [`DerefMut`](crate::ops::DerefMut)
/// and returns the new [`Result`].
///
/// # Examples
///
/// ```
/// let mut s = "HELLO".to_string();
/// let mut x: Result<String, u32> = Ok("hello".to_string());
/// let y: Result<&mut str, &mut u32> = Ok(&mut s);
/// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
///
/// let mut i = 42;
/// let mut x: Result<String, u32> = Err(42);
/// let y: Result<&mut str, &mut u32> = Err(&mut i);
/// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
/// ```
#[stable(feature = "inner_deref", since = "1.47.0")]
pub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E> {
self.as_mut().map(|t| t.deref_mut())
}
}
impl<T, E> Result<Option<T>, E> { impl<T, E> Result<Option<T>, E> {
/// Transposes a `Result` of an `Option` into an `Option` of a `Result`. /// Transposes a `Result` of an `Option` into an `Option` of a `Result`.
/// ///

View file

@ -5,7 +5,6 @@ LL | let _result = &mut Some(42).as_deref_mut();
| ^^^^^^^^^^^^ method cannot be called on `Option<{integer}>` due to unsatisfied trait bounds | ^^^^^^^^^^^^ method cannot be called on `Option<{integer}>` due to unsatisfied trait bounds
| |
= note: the following trait bounds were not satisfied: = note: the following trait bounds were not satisfied:
`{integer}: DerefMut`
`{integer}: Deref` `{integer}: Deref`
error: aborting due to previous error error: aborting due to previous error

View file

@ -5,7 +5,6 @@ LL | let _result = &mut Ok(42).as_deref_mut();
| ^^^^^^^^^^^^ method cannot be called on `Result<{integer}, _>` due to unsatisfied trait bounds | ^^^^^^^^^^^^ method cannot be called on `Result<{integer}, _>` due to unsatisfied trait bounds
| |
= note: the following trait bounds were not satisfied: = note: the following trait bounds were not satisfied:
`{integer}: DerefMut`
`{integer}: Deref` `{integer}: Deref`
error: aborting due to previous error error: aborting due to previous error

View file

@ -3,5 +3,5 @@ struct Foo;
fn main() { fn main() {
let a: Result<(), Foo> = Ok(()); let a: Result<(), Foo> = Ok(());
a.unwrap(); a.unwrap();
//~^ ERROR the method //~^ ERROR `Foo` doesn't implement `Debug`
} }

View file

@ -1,19 +1,17 @@
error[E0599]: the method `unwrap` exists for enum `Result<(), Foo>`, but its trait bounds were not satisfied error[E0277]: `Foo` doesn't implement `Debug`
--> $DIR/method-help-unsatisfied-bound.rs:5:7 --> $DIR/method-help-unsatisfied-bound.rs:5:7
| |
LL | struct Foo;
| ----------- doesn't satisfy `Foo: Debug`
...
LL | a.unwrap(); LL | a.unwrap();
| ^^^^^^ method cannot be called on `Result<(), Foo>` due to unsatisfied trait bounds | ^^^^^^ `Foo` cannot be formatted using `{:?}`
| |
= note: the following trait bounds were not satisfied: = help: the trait `Debug` is not implemented for `Foo`
`Foo: Debug` = note: add `#[derive(Debug)]` to `Foo` or manually `impl Debug for Foo`
help: consider annotating `Foo` with `#[derive(Debug)]` note: required by a bound in `Result::<T, E>::unwrap`
| --> $SRC_DIR/core/src/result.rs:LL:COL
LL | #[derive(Debug)]
| |
LL | E: fmt::Debug,
| ^^^^^^^^^^ required by this bound in `Result::<T, E>::unwrap`
error: aborting due to previous error error: aborting due to previous error
For more information about this error, try `rustc --explain E0599`. For more information about this error, try `rustc --explain E0277`.