]> git.proxmox.com Git - rustc.git/blame - library/core/src/result.rs
New upstream version 1.56.0~beta.4+dfsg1
[rustc.git] / library / core / src / result.rs
CommitLineData
54a0048b 1//! Error handling with the `Result` type.
1a4d82fc 2//!
9e0c209e
SL
3//! [`Result<T, E>`][`Result`] is the type used for returning and propagating
4//! errors. It is an enum with the variants, [`Ok(T)`], representing
5//! success and containing a value, and [`Err(E)`], representing error
1a4d82fc
JJ
6//! and containing an error value.
7//!
8//! ```
92a42be0 9//! # #[allow(dead_code)]
1a4d82fc
JJ
10//! enum Result<T, E> {
11//! Ok(T),
a7813a04 12//! Err(E),
1a4d82fc
JJ
13//! }
14//! ```
15//!
9e0c209e
SL
16//! Functions return [`Result`] whenever errors are expected and
17//! recoverable. In the `std` crate, [`Result`] is most prominently used
1a4d82fc
JJ
18//! for [I/O](../../std/io/index.html).
19//!
9e0c209e 20//! A simple function returning [`Result`] might be
1a4d82fc
JJ
21//! defined and used like so:
22//!
23//! ```
85aaf69f 24//! #[derive(Debug)]
1a4d82fc
JJ
25//! enum Version { Version1, Version2 }
26//!
27//! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
9346a6ac
AL
28//! match header.get(0) {
29//! None => Err("invalid header length"),
30//! Some(&1) => Ok(Version::Version1),
31//! Some(&2) => Ok(Version::Version2),
a7813a04 32//! Some(_) => Err("invalid version"),
1a4d82fc
JJ
33//! }
34//! }
35//!
36//! let version = parse_version(&[1, 2, 3, 4]);
37//! match version {
9346a6ac
AL
38//! Ok(v) => println!("working with version: {:?}", v),
39//! Err(e) => println!("error parsing header: {:?}", e),
1a4d82fc
JJ
40//! }
41//! ```
42//!
9e0c209e
SL
43//! Pattern matching on [`Result`]s is clear and straightforward for
44//! simple cases, but [`Result`] comes with some convenience methods
1a4d82fc
JJ
45//! that make working with it more succinct.
46//!
47//! ```
c34b1796
AL
48//! let good_result: Result<i32, i32> = Ok(10);
49//! let bad_result: Result<i32, i32> = Err(10);
1a4d82fc
JJ
50//!
51//! // The `is_ok` and `is_err` methods do what they say.
52//! assert!(good_result.is_ok() && !good_result.is_err());
53//! assert!(bad_result.is_err() && !bad_result.is_ok());
54//!
55//! // `map` consumes the `Result` and produces another.
c34b1796
AL
56//! let good_result: Result<i32, i32> = good_result.map(|i| i + 1);
57//! let bad_result: Result<i32, i32> = bad_result.map(|i| i - 1);
1a4d82fc
JJ
58//!
59//! // Use `and_then` to continue the computation.
c34b1796 60//! let good_result: Result<bool, i32> = good_result.and_then(|i| Ok(i == 11));
1a4d82fc
JJ
61//!
62//! // Use `or_else` to handle the error.
9346a6ac 63//! let bad_result: Result<i32, i32> = bad_result.or_else(|i| Ok(i + 20));
1a4d82fc
JJ
64//!
65//! // Consume the result and return the contents with `unwrap`.
c34b1796 66//! let final_awesome_result = good_result.unwrap();
1a4d82fc
JJ
67//! ```
68//!
69//! # Results must be used
70//!
71//! A common problem with using return values to indicate errors is
72//! that it is easy to ignore the return value, thus failing to handle
9e0c209e 73//! the error. [`Result`] is annotated with the `#[must_use]` attribute,
1a4d82fc 74//! which will cause the compiler to issue a warning when a Result
9e0c209e 75//! value is ignored. This makes [`Result`] especially useful with
1a4d82fc
JJ
76//! functions that may encounter errors but don't otherwise return a
77//! useful value.
78//!
9e0c209e
SL
79//! Consider the [`write_all`] method defined for I/O types
80//! by the [`Write`] trait:
1a4d82fc
JJ
81//!
82//! ```
9346a6ac 83//! use std::io;
1a4d82fc 84//!
9346a6ac
AL
85//! trait Write {
86//! fn write_all(&mut self, bytes: &[u8]) -> Result<(), io::Error>;
1a4d82fc
JJ
87//! }
88//! ```
89//!
9e0c209e
SL
90//! *Note: The actual definition of [`Write`] uses [`io::Result`], which
91//! is just a synonym for [`Result`]`<T, `[`io::Error`]`>`.*
1a4d82fc
JJ
92//!
93//! This method doesn't produce a value, but the write may
94//! fail. It's crucial to handle the error case, and *not* write
95//! something like this:
96//!
9346a6ac 97//! ```no_run
92a42be0 98//! # #![allow(unused_must_use)] // \o/
9346a6ac
AL
99//! use std::fs::File;
100//! use std::io::prelude::*;
1a4d82fc 101//!
9346a6ac
AL
102//! let mut file = File::create("valuable_data.txt").unwrap();
103//! // If `write_all` errors, then we'll never know, because the return
1a4d82fc 104//! // value is ignored.
9346a6ac 105//! file.write_all(b"important message");
1a4d82fc
JJ
106//! ```
107//!
85aaf69f 108//! If you *do* write that in Rust, the compiler will give you a
1a4d82fc
JJ
109//! warning (by default, controlled by the `unused_must_use` lint).
110//!
111//! You might instead, if you don't want to handle the error, simply
9e0c209e 112//! assert success with [`expect`]. This will panic if the
92a42be0 113//! write fails, providing a marginally useful message indicating why:
1a4d82fc 114//!
6a06907d 115//! ```no_run
9346a6ac
AL
116//! use std::fs::File;
117//! use std::io::prelude::*;
1a4d82fc 118//!
9346a6ac 119//! let mut file = File::create("valuable_data.txt").unwrap();
92a42be0 120//! file.write_all(b"important message").expect("failed to write message");
1a4d82fc
JJ
121//! ```
122//!
123//! You might also simply assert success:
124//!
6a06907d 125//! ```no_run
9346a6ac
AL
126//! # use std::fs::File;
127//! # use std::io::prelude::*;
128//! # let mut file = File::create("valuable_data.txt").unwrap();
129//! assert!(file.write_all(b"important message").is_ok());
1a4d82fc
JJ
130//! ```
131//!
8bb4bdeb 132//! Or propagate the error up the call stack with [`?`]:
1a4d82fc
JJ
133//!
134//! ```
9346a6ac
AL
135//! # use std::fs::File;
136//! # use std::io::prelude::*;
137//! # use std::io;
92a42be0 138//! # #[allow(dead_code)]
9346a6ac 139//! fn write_message() -> io::Result<()> {
8bb4bdeb
XL
140//! let mut file = File::create("valuable_data.txt")?;
141//! file.write_all(b"important message")?;
9346a6ac 142//! Ok(())
1a4d82fc
JJ
143//! }
144//! ```
145//!
ff7c6d11 146//! # The question mark operator, `?`
1a4d82fc
JJ
147//!
148//! When writing code that calls many functions that return the
ff7c6d11
XL
149//! [`Result`] type, the error handling can be tedious. The question mark
150//! operator, [`?`], hides some of the boilerplate of propagating errors
151//! up the call stack.
1a4d82fc
JJ
152//!
153//! It replaces this:
154//!
155//! ```
92a42be0 156//! # #![allow(dead_code)]
9346a6ac
AL
157//! use std::fs::File;
158//! use std::io::prelude::*;
159//! use std::io;
1a4d82fc
JJ
160//!
161//! struct Info {
162//! name: String,
c34b1796
AL
163//! age: i32,
164//! rating: i32,
1a4d82fc
JJ
165//! }
166//!
9346a6ac 167//! fn write_info(info: &Info) -> io::Result<()> {
1a4d82fc 168//! // Early return on error
3157f602
XL
169//! let mut file = match File::create("my_best_friends.txt") {
170//! Err(e) => return Err(e),
171//! Ok(f) => f,
172//! };
9346a6ac 173//! if let Err(e) = file.write_all(format!("name: {}\n", info.name).as_bytes()) {
85aaf69f 174//! return Err(e)
1a4d82fc 175//! }
9346a6ac 176//! if let Err(e) = file.write_all(format!("age: {}\n", info.age).as_bytes()) {
85aaf69f 177//! return Err(e)
1a4d82fc 178//! }
9346a6ac
AL
179//! if let Err(e) = file.write_all(format!("rating: {}\n", info.rating).as_bytes()) {
180//! return Err(e)
181//! }
182//! Ok(())
1a4d82fc
JJ
183//! }
184//! ```
185//!
186//! With this:
187//!
188//! ```
92a42be0 189//! # #![allow(dead_code)]
9346a6ac
AL
190//! use std::fs::File;
191//! use std::io::prelude::*;
192//! use std::io;
1a4d82fc
JJ
193//!
194//! struct Info {
195//! name: String,
c34b1796
AL
196//! age: i32,
197//! rating: i32,
1a4d82fc
JJ
198//! }
199//!
9346a6ac 200//! fn write_info(info: &Info) -> io::Result<()> {
8bb4bdeb 201//! let mut file = File::create("my_best_friends.txt")?;
1a4d82fc 202//! // Early return on error
8bb4bdeb
XL
203//! file.write_all(format!("name: {}\n", info.name).as_bytes())?;
204//! file.write_all(format!("age: {}\n", info.age).as_bytes())?;
205//! file.write_all(format!("rating: {}\n", info.rating).as_bytes())?;
9346a6ac 206//! Ok(())
1a4d82fc
JJ
207//! }
208//! ```
209//!
210//! *It's much nicer!*
211//!
8bb4bdeb 212//! Ending the expression with [`?`] will result in the unwrapped
9e0c209e 213//! success ([`Ok`]) value, unless the result is [`Err`], in which case
8bb4bdeb 214//! [`Err`] is returned early from the enclosing function.
1a4d82fc 215//!
8bb4bdeb
XL
216//! [`?`] can only be used in functions that return [`Result`] because of the
217//! early return of [`Err`] that it provides.
9e0c209e 218//!
3dfed10e 219//! [`expect`]: Result::expect
9e0c209e
SL
220//! [`Write`]: ../../std/io/trait.Write.html
221//! [`write_all`]: ../../std/io/trait.Write.html#method.write_all
222//! [`io::Result`]: ../../std/io/type.Result.html
3dfed10e
XL
223//! [`?`]: crate::ops::Try
224//! [`Ok(T)`]: Ok
225//! [`Err(E)`]: Err
9e0c209e 226//! [`io::Error`]: ../../std/io/struct.Error.html
136023e0
XL
227//!
228//! # Method overview
229//!
230//! In addition to working with pattern matching, [`Result`] provides a
231//! wide variety of different methods.
232//!
233//! ## Querying the variant
234//!
235//! The [`is_ok`] and [`is_err`] methods return [`true`] if the [`Result`]
236//! is [`Ok`] or [`Err`], respectively.
237//!
238//! [`is_err`]: Result::is_err
239//! [`is_ok`]: Result::is_ok
240//!
241//! ## Adapters for working with references
242//!
243//! * [`as_ref`] converts from `&Result<T, E>` to `Result<&T, &E>`
244//! * [`as_mut`] converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`
245//! * [`as_deref`] converts from `&Result<T, E>` to `Result<&T::Target, &E>`
246//! * [`as_deref_mut`] converts from `&mut Result<T, E>` to
247//! `Result<&mut T::Target, &mut E>`
248//!
249//! [`as_deref`]: Result::as_deref
250//! [`as_deref_mut`]: Result::as_deref_mut
251//! [`as_mut`]: Result::as_mut
252//! [`as_ref`]: Result::as_ref
253//!
254//! ## Extracting contained values
255//!
256//! These methods extract the contained value in a [`Result<T, E>`] when it
257//! is the [`Ok`] variant. If the [`Result`] is [`Err`]:
258//!
259//! * [`expect`] panics with a provided custom message
260//! * [`unwrap`] panics with a generic message
261//! * [`unwrap_or`] returns the provided default value
262//! * [`unwrap_or_default`] returns the default value of the type `T`
263//! (which must implement the [`Default`] trait)
264//! * [`unwrap_or_else`] returns the result of evaluating the provided
265//! function
266//!
267//! The panicking methods [`expect`] and [`unwrap`] require `E` to
268//! implement the [`Debug`] trait.
269//!
270//! [`Debug`]: crate::fmt::Debug
271//! [`expect`]: Result::expect
272//! [`unwrap`]: Result::unwrap
273//! [`unwrap_or`]: Result::unwrap_or
274//! [`unwrap_or_default`]: Result::unwrap_or_default
275//! [`unwrap_or_else`]: Result::unwrap_or_else
276//!
277//! These methods extract the contained value in a [`Result<T, E>`] when it
278//! is the [`Err`] variant. They require `T` to implement the [`Debug`]
279//! trait. If the [`Result`] is [`Ok`]:
280//!
281//! * [`expect_err`] panics with a provided custom message
282//! * [`unwrap_err`] panics with a generic message
283//!
284//! [`Debug`]: crate::fmt::Debug
285//! [`expect_err`]: Result::expect_err
286//! [`unwrap_err`]: Result::unwrap_err
287//!
288//! ## Transforming contained values
289//!
290//! These methods transform [`Result`] to [`Option`]:
291//!
292//! * [`err`][Result::err] transforms [`Result<T, E>`] into [`Option<E>`],
293//! mapping [`Err(e)`] to [`Some(e)`] and [`Ok(v)`] to [`None`]
294//! * [`ok`][Result::ok] transforms [`Result<T, E>`] into [`Option<T>`],
295//! mapping [`Ok(v)`] to [`Some(v)`] and [`Err(e)`] to [`None`]
296//! * [`transpose`] transposes a [`Result`] of an [`Option`] into an
297//! [`Option`] of a [`Result`]
298//!
299// Do NOT add link reference definitions for `err` or `ok`, because they
300// will generate numerous incorrect URLs for `Err` and `Ok` elsewhere, due
301// to case folding.
302//!
303//! [`Err(e)`]: Err
304//! [`Ok(v)`]: Ok
305//! [`Some(e)`]: Option::Some
306//! [`Some(v)`]: Option::Some
307//! [`transpose`]: Result::transpose
308//!
309//! This method transforms the contained value of the [`Ok`] variant:
310//!
311//! * [`map`] transforms [`Result<T, E>`] into [`Result<U, E>`] by applying
312//! the provided function to the contained value of [`Ok`] and leaving
313//! [`Err`] values unchanged
314//!
315//! [`map`]: Result::map
316//!
317//! This method transforms the contained value of the [`Err`] variant:
318//!
319//! * [`map_err`] transforms [`Result<T, E>`] into [`Result<T, F>`] by
320//! applying the provided function to the contained value of [`Err`] and
321//! leaving [`Ok`] values unchanged
322//!
323//! [`map_err`]: Result::map_err
324//!
325//! These methods transform a [`Result<T, E>`] into a value of a possibly
326//! different type `U`:
327//!
328//! * [`map_or`] applies the provided function to the contained value of
329//! [`Ok`], or returns the provided default value if the [`Result`] is
330//! [`Err`]
331//! * [`map_or_else`] applies the provided function to the contained value
332//! of [`Ok`], or applies the provided fallback function to the contained
333//! value of [`Err`]
334//!
335//! [`map_or`]: Result::map_or
336//! [`map_or_else`]: Result::map_or_else
337//!
338//! ## Boolean operators
339//!
340//! These methods treat the [`Result`] as a boolean value, where [`Ok`]
341//! acts like [`true`] and [`Err`] acts like [`false`]. There are two
342//! categories of these methods: ones that take a [`Result`] as input, and
343//! ones that take a function as input (to be lazily evaluated).
344//!
345//! The [`and`] and [`or`] methods take another [`Result`] as input, and
346//! produce a [`Result`] as output. The [`and`] method can produce a
347//! [`Result<U, E>`] value having a different inner type `U` than
348//! [`Result<T, E>`]. The [`or`] method can produce a [`Result<T, F>`]
349//! value having a different error type `F` than [`Result<T, E>`].
350//!
351//! | method | self | input | output |
352//! |---------|----------|-----------|----------|
353//! | [`and`] | `Err(e)` | (ignored) | `Err(e)` |
354//! | [`and`] | `Ok(x)` | `Err(d)` | `Err(d)` |
355//! | [`and`] | `Ok(x)` | `Ok(y)` | `Ok(y)` |
356//! | [`or`] | `Err(e)` | `Err(d)` | `Err(d)` |
357//! | [`or`] | `Err(e)` | `Ok(y)` | `Ok(y)` |
358//! | [`or`] | `Ok(x)` | (ignored) | `Ok(x)` |
359//!
360//! [`and`]: Result::and
361//! [`or`]: Result::or
362//!
363//! The [`and_then`] and [`or_else`] methods take a function as input, and
364//! only evaluate the function when they need to produce a new value. The
365//! [`and_then`] method can produce a [`Result<U, E>`] value having a
366//! different inner type `U` than [`Result<T, E>`]. The [`or_else`] method
367//! can produce a [`Result<T, F>`] value having a different error type `F`
368//! than [`Result<T, E>`].
369//!
370//! | method | self | function input | function result | output |
371//! |--------------|----------|----------------|-----------------|----------|
372//! | [`and_then`] | `Err(e)` | (not provided) | (not evaluated) | `Err(e)` |
373//! | [`and_then`] | `Ok(x)` | `x` | `Err(d)` | `Err(d)` |
374//! | [`and_then`] | `Ok(x)` | `x` | `Ok(y)` | `Ok(y)` |
375//! | [`or_else`] | `Err(e)` | `e` | `Err(d)` | `Err(d)` |
376//! | [`or_else`] | `Err(e)` | `e` | `Ok(y)` | `Ok(y)` |
377//! | [`or_else`] | `Ok(x)` | (not provided) | (not evaluated) | `Ok(x)` |
378//!
379//! [`and_then`]: Result::and_then
380//! [`or_else`]: Result::or_else
381//!
94222f64
XL
382//! ## Comparison operators
383//!
384//! If `T` and `E` both implement [`PartialOrd`] then [`Result<T, E>`] will
385//! derive its [`PartialOrd`] implementation. With this order, an [`Ok`]
386//! compares as less than any [`Err`], while two [`Ok`] or two [`Err`]
387//! compare as their contained values would in `T` or `E` respectively. If `T`
388//! and `E` both also implement [`Ord`], then so does [`Result<T, E>`].
389//!
390//! ```
391//! assert!(Ok(1) < Err(0));
392//! let x: Result<i32, ()> = Ok(0);
393//! let y = Ok(1);
394//! assert!(x < y);
395//! let x: Result<(), i32> = Err(0);
396//! let y = Err(1);
397//! assert!(x < y);
398//! ```
399//!
136023e0
XL
400//! ## Iterating over `Result`
401//!
402//! A [`Result`] can be iterated over. This can be helpful if you need an
403//! iterator that is conditionally empty. The iterator will either produce
404//! a single value (when the [`Result`] is [`Ok`]), or produce no values
405//! (when the [`Result`] is [`Err`]). For example, [`into_iter`] acts like
406//! [`once(v)`] if the [`Result`] is [`Ok(v)`], and like [`empty()`] if the
407//! [`Result`] is [`Err`].
408//!
409//! [`Ok(v)`]: Ok
410//! [`empty()`]: crate::iter::empty
411//! [`once(v)`]: crate::iter::once
412//!
413//! Iterators over [`Result<T, E>`] come in three types:
414//!
415//! * [`into_iter`] consumes the [`Result`] and produces the contained
416//! value
417//! * [`iter`] produces an immutable reference of type `&T` to the
418//! contained value
419//! * [`iter_mut`] produces a mutable reference of type `&mut T` to the
420//! contained value
421//!
422//! See [Iterating over `Option`] for examples of how this can be useful.
423//!
424//! [Iterating over `Option`]: crate::option#iterating-over-option
425//! [`into_iter`]: Result::into_iter
426//! [`iter`]: Result::iter
427//! [`iter_mut`]: Result::iter_mut
428//!
429//! You might want to use an iterator chain to do multiple instances of an
430//! operation that can fail, but would like to ignore failures while
431//! continuing to process the successful results. In this example, we take
432//! advantage of the iterable nature of [`Result`] to select only the
433//! [`Ok`] values using [`flatten`][Iterator::flatten].
434//!
435//! ```
436//! # use std::str::FromStr;
437//! let mut results = vec![];
438//! let mut errs = vec![];
439//! let nums: Vec<_> = vec!["17", "not a number", "99", "-27", "768"]
440//! .into_iter()
441//! .map(u8::from_str)
442//! // Save clones of the raw `Result` values to inspect
443//! .inspect(|x| results.push(x.clone()))
444//! // Challenge: explain how this captures only the `Err` values
445//! .inspect(|x| errs.extend(x.clone().err()))
446//! .flatten()
447//! .collect();
448//! assert_eq!(errs.len(), 3);
449//! assert_eq!(nums, [17, 99]);
450//! println!("results {:?}", results);
451//! println!("errs {:?}", errs);
452//! println!("nums {:?}", nums);
453//! ```
454//!
455//! ## Collecting into `Result`
456//!
457//! [`Result`] implements the [`FromIterator`][impl-FromIterator] trait,
458//! which allows an iterator over [`Result`] values to be collected into a
459//! [`Result`] of a collection of each contained value of the original
460//! [`Result`] values, or [`Err`] if any of the elements was [`Err`].
461//!
462//! [impl-FromIterator]: Result#impl-FromIterator%3CResult%3CA%2C%20E%3E%3E
463//!
464//! ```
465//! let v = vec![Ok(2), Ok(4), Err("err!"), Ok(8)];
466//! let res: Result<Vec<_>, &str> = v.into_iter().collect();
467//! assert_eq!(res, Err("err!"));
468//! let v = vec![Ok(2), Ok(4), Ok(8)];
469//! let res: Result<Vec<_>, &str> = v.into_iter().collect();
470//! assert_eq!(res, Ok(vec![2, 4, 8]));
471//! ```
472//!
473//! [`Result`] also implements the [`Product`][impl-Product] and
474//! [`Sum`][impl-Sum] traits, allowing an iterator over [`Result`] values
475//! to provide the [`product`][Iterator::product] and
476//! [`sum`][Iterator::sum] methods.
477//!
478//! [impl-Product]: Result#impl-Product%3CResult%3CU%2C%20E%3E%3E
479//! [impl-Sum]: Result#impl-Sum%3CResult%3CU%2C%20E%3E%3E
480//!
481//! ```
482//! let v = vec![Err("error!"), Ok(1), Ok(2), Ok(3), Err("foo")];
483//! let res: Result<i32, &str> = v.into_iter().sum();
484//! assert_eq!(res, Err("error!"));
485//! let v: Vec<Result<i32, &str>> = vec![Ok(1), Ok(2), Ok(21)];
486//! let res: Result<i32, &str> = v.into_iter().product();
487//! assert_eq!(res, Ok(42));
488//! ```
1a4d82fc 489
85aaf69f 490#![stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 491
416331ca 492use crate::iter::{self, FromIterator, FusedIterator, TrustedLen};
cdc7bbd5 493use crate::ops::{self, ControlFlow, Deref, DerefMut};
5869c6ff 494use crate::{convert, fmt, hint};
1a4d82fc 495
3b2f2976 496/// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]).
1a4d82fc 497///
29967ef6 498/// See the [module documentation](self) for details.
dc9dc135 499#[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
94b46f34 500#[must_use = "this `Result` may be an `Err` variant, which should be handled"]
dfeec247 501#[rustc_diagnostic_item = "result_type"]
85aaf69f 502#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
503pub enum Result<T, E> {
504 /// Contains the success value
1b1a35ee 505 #[lang = "Ok"]
85aaf69f 506 #[stable(feature = "rust1", since = "1.0.0")]
7453a54e 507 Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
1a4d82fc
JJ
508
509 /// Contains the error value
1b1a35ee 510 #[lang = "Err"]
85aaf69f 511 #[stable(feature = "rust1", since = "1.0.0")]
a7813a04 512 Err(#[stable(feature = "rust1", since = "1.0.0")] E),
1a4d82fc
JJ
513}
514
515/////////////////////////////////////////////////////////////////////////////
516// Type implementation
517/////////////////////////////////////////////////////////////////////////////
518
1a4d82fc
JJ
519impl<T, E> Result<T, E> {
520 /////////////////////////////////////////////////////////////////////////
521 // Querying the contained values
522 /////////////////////////////////////////////////////////////////////////
523
3b2f2976
XL
524 /// Returns `true` if the result is [`Ok`].
525 ///
c34b1796 526 /// # Examples
1a4d82fc 527 ///
a7813a04
XL
528 /// Basic usage:
529 ///
1a4d82fc 530 /// ```
c34b1796 531 /// let x: Result<i32, &str> = Ok(-3);
1a4d82fc
JJ
532 /// assert_eq!(x.is_ok(), true);
533 ///
c34b1796 534 /// let x: Result<i32, &str> = Err("Some error message");
1a4d82fc
JJ
535 /// assert_eq!(x.is_ok(), false);
536 /// ```
416331ca 537 #[must_use = "if you intended to assert that this is ok, consider `.unwrap()` instead"]
1b1a35ee 538 #[rustc_const_stable(feature = "const_result", since = "1.48.0")]
1a4d82fc 539 #[inline]
85aaf69f 540 #[stable(feature = "rust1", since = "1.0.0")]
dfeec247
XL
541 pub const fn is_ok(&self) -> bool {
542 matches!(*self, Ok(_))
1a4d82fc
JJ
543 }
544
3b2f2976
XL
545 /// Returns `true` if the result is [`Err`].
546 ///
c34b1796 547 /// # Examples
1a4d82fc 548 ///
a7813a04
XL
549 /// Basic usage:
550 ///
1a4d82fc 551 /// ```
c34b1796 552 /// let x: Result<i32, &str> = Ok(-3);
1a4d82fc
JJ
553 /// assert_eq!(x.is_err(), false);
554 ///
c34b1796 555 /// let x: Result<i32, &str> = Err("Some error message");
1a4d82fc
JJ
556 /// assert_eq!(x.is_err(), true);
557 /// ```
416331ca 558 #[must_use = "if you intended to assert that this is err, consider `.unwrap_err()` instead"]
1b1a35ee 559 #[rustc_const_stable(feature = "const_result", since = "1.48.0")]
1a4d82fc 560 #[inline]
85aaf69f 561 #[stable(feature = "rust1", since = "1.0.0")]
dfeec247 562 pub const fn is_err(&self) -> bool {
1a4d82fc
JJ
563 !self.is_ok()
564 }
565
416331ca
XL
566 /// Returns `true` if the result is an [`Ok`] value containing the given value.
567 ///
568 /// # Examples
569 ///
570 /// ```
571 /// #![feature(option_result_contains)]
572 ///
573 /// let x: Result<u32, &str> = Ok(2);
574 /// assert_eq!(x.contains(&2), true);
575 ///
576 /// let x: Result<u32, &str> = Ok(3);
577 /// assert_eq!(x.contains(&2), false);
578 ///
579 /// let x: Result<u32, &str> = Err("Some error message");
580 /// assert_eq!(x.contains(&2), false);
581 /// ```
582 #[must_use]
583 #[inline]
584 #[unstable(feature = "option_result_contains", issue = "62358")]
dfeec247
XL
585 pub fn contains<U>(&self, x: &U) -> bool
586 where
587 U: PartialEq<T>,
588 {
416331ca
XL
589 match self {
590 Ok(y) => x == y,
dfeec247 591 Err(_) => false,
416331ca
XL
592 }
593 }
594
595 /// Returns `true` if the result is an [`Err`] value containing the given value.
596 ///
597 /// # Examples
598 ///
599 /// ```
600 /// #![feature(result_contains_err)]
601 ///
602 /// let x: Result<u32, &str> = Ok(2);
603 /// assert_eq!(x.contains_err(&"Some error message"), false);
604 ///
605 /// let x: Result<u32, &str> = Err("Some error message");
606 /// assert_eq!(x.contains_err(&"Some error message"), true);
607 ///
608 /// let x: Result<u32, &str> = Err("Some other error message");
609 /// assert_eq!(x.contains_err(&"Some error message"), false);
610 /// ```
611 #[must_use]
612 #[inline]
613 #[unstable(feature = "result_contains_err", issue = "62358")]
dfeec247
XL
614 pub fn contains_err<F>(&self, f: &F) -> bool
615 where
616 F: PartialEq<E>,
617 {
416331ca
XL
618 match self {
619 Ok(_) => false,
dfeec247 620 Err(e) => f == e,
416331ca
XL
621 }
622 }
623
1a4d82fc
JJ
624 /////////////////////////////////////////////////////////////////////////
625 // Adapter for each variant
626 /////////////////////////////////////////////////////////////////////////
627
9e0c209e 628 /// Converts from `Result<T, E>` to [`Option<T>`].
1a4d82fc 629 ///
9e0c209e 630 /// Converts `self` into an [`Option<T>`], consuming `self`,
1a4d82fc
JJ
631 /// and discarding the error, if any.
632 ///
c34b1796 633 /// # Examples
1a4d82fc 634 ///
a7813a04
XL
635 /// Basic usage:
636 ///
1a4d82fc 637 /// ```
85aaf69f 638 /// let x: Result<u32, &str> = Ok(2);
1a4d82fc
JJ
639 /// assert_eq!(x.ok(), Some(2));
640 ///
85aaf69f 641 /// let x: Result<u32, &str> = Err("Nothing here");
1a4d82fc
JJ
642 /// assert_eq!(x.ok(), None);
643 /// ```
644 #[inline]
85aaf69f 645 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
646 pub fn ok(self) -> Option<T> {
647 match self {
dfeec247 648 Ok(x) => Some(x),
1a4d82fc
JJ
649 Err(_) => None,
650 }
651 }
652
9e0c209e 653 /// Converts from `Result<T, E>` to [`Option<E>`].
1a4d82fc 654 ///
9e0c209e 655 /// Converts `self` into an [`Option<E>`], consuming `self`,
c34b1796 656 /// and discarding the success value, if any.
1a4d82fc 657 ///
c34b1796 658 /// # Examples
1a4d82fc 659 ///
a7813a04
XL
660 /// Basic usage:
661 ///
1a4d82fc 662 /// ```
85aaf69f 663 /// let x: Result<u32, &str> = Ok(2);
1a4d82fc
JJ
664 /// assert_eq!(x.err(), None);
665 ///
85aaf69f 666 /// let x: Result<u32, &str> = Err("Nothing here");
1a4d82fc
JJ
667 /// assert_eq!(x.err(), Some("Nothing here"));
668 /// ```
669 #[inline]
85aaf69f 670 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
671 pub fn err(self) -> Option<E> {
672 match self {
dfeec247 673 Ok(_) => None,
1a4d82fc
JJ
674 Err(x) => Some(x),
675 }
676 }
677
678 /////////////////////////////////////////////////////////////////////////
679 // Adapter for working with references
680 /////////////////////////////////////////////////////////////////////////
681
532ac7d7 682 /// Converts from `&Result<T, E>` to `Result<&T, &E>`.
1a4d82fc
JJ
683 ///
684 /// Produces a new `Result`, containing a reference
685 /// into the original, leaving the original in place.
686 ///
a7813a04
XL
687 /// # Examples
688 ///
689 /// Basic usage:
690 ///
1a4d82fc 691 /// ```
85aaf69f 692 /// let x: Result<u32, &str> = Ok(2);
1a4d82fc
JJ
693 /// assert_eq!(x.as_ref(), Ok(&2));
694 ///
85aaf69f 695 /// let x: Result<u32, &str> = Err("Error");
1a4d82fc
JJ
696 /// assert_eq!(x.as_ref(), Err(&"Error"));
697 /// ```
698 #[inline]
1b1a35ee 699 #[rustc_const_stable(feature = "const_result", since = "1.48.0")]
85aaf69f 700 #[stable(feature = "rust1", since = "1.0.0")]
dfeec247 701 pub const fn as_ref(&self) -> Result<&T, &E> {
1a4d82fc
JJ
702 match *self {
703 Ok(ref x) => Ok(x),
704 Err(ref x) => Err(x),
705 }
706 }
707
532ac7d7 708 /// Converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`.
1a4d82fc 709 ///
a7813a04
XL
710 /// # Examples
711 ///
712 /// Basic usage:
713 ///
1a4d82fc 714 /// ```
c34b1796 715 /// fn mutate(r: &mut Result<i32, i32>) {
1a4d82fc 716 /// match r.as_mut() {
5bcae85e
SL
717 /// Ok(v) => *v = 42,
718 /// Err(e) => *e = 0,
1a4d82fc
JJ
719 /// }
720 /// }
721 ///
c34b1796 722 /// let mut x: Result<i32, i32> = Ok(2);
1a4d82fc
JJ
723 /// mutate(&mut x);
724 /// assert_eq!(x.unwrap(), 42);
725 ///
c34b1796 726 /// let mut x: Result<i32, i32> = Err(13);
1a4d82fc
JJ
727 /// mutate(&mut x);
728 /// assert_eq!(x.unwrap_err(), 0);
729 /// ```
730 #[inline]
85aaf69f 731 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
732 pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
733 match *self {
734 Ok(ref mut x) => Ok(x),
735 Err(ref mut x) => Err(x),
736 }
737 }
738
1a4d82fc
JJ
739 /////////////////////////////////////////////////////////////////////////
740 // Transforming contained values
741 /////////////////////////////////////////////////////////////////////////
742
92a42be0 743 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
3b2f2976 744 /// contained [`Ok`] value, leaving an [`Err`] value untouched.
1a4d82fc
JJ
745 ///
746 /// This function can be used to compose the results of two functions.
747 ///
c34b1796 748 /// # Examples
1a4d82fc 749 ///
9346a6ac 750 /// Print the numbers on each line of a string multiplied by two.
1a4d82fc
JJ
751 ///
752 /// ```
9346a6ac 753 /// let line = "1\n2\n3\n4\n";
1a4d82fc 754 ///
9346a6ac
AL
755 /// for num in line.lines() {
756 /// match num.parse::<i32>().map(|i| i * 2) {
757 /// Ok(n) => println!("{}", n),
758 /// Err(..) => {}
759 /// }
1a4d82fc 760 /// }
1a4d82fc
JJ
761 /// ```
762 #[inline]
85aaf69f 763 #[stable(feature = "rust1", since = "1.0.0")]
dfeec247 764 pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U, E> {
1a4d82fc
JJ
765 match self {
766 Ok(t) => Ok(op(t)),
dfeec247 767 Err(e) => Err(e),
1a4d82fc
JJ
768 }
769 }
770
cdc7bbd5
XL
771 /// Returns the provided default (if [`Err`]), or
772 /// applies a function to the contained value (if [`Ok`]),
60c5eb7d 773 ///
74b04a01
XL
774 /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
775 /// the result of a function call, it is recommended to use [`map_or_else`],
776 /// which is lazily evaluated.
777 ///
3dfed10e 778 /// [`map_or_else`]: Result::map_or_else
74b04a01 779 ///
60c5eb7d
XL
780 /// # Examples
781 ///
782 /// ```
783 /// let x: Result<_, &str> = Ok("foo");
784 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
785 ///
786 /// let x: Result<&str, _> = Err("bar");
787 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
788 /// ```
789 #[inline]
790 #[stable(feature = "result_map_or", since = "1.41.0")]
791 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
792 match self {
793 Ok(t) => f(t),
794 Err(_) => default,
795 }
796 }
797
cdc7bbd5
XL
798 /// Maps a `Result<T, E>` to `U` by applying a fallback function to a
799 /// contained [`Err`] value, or a default function to a
800 /// contained [`Ok`] value.
b7449926
XL
801 ///
802 /// This function can be used to unpack a successful result
803 /// while handling an error.
804 ///
b7449926
XL
805 ///
806 /// # Examples
807 ///
808 /// Basic usage:
809 ///
810 /// ```
b7449926
XL
811 /// let k = 21;
812 ///
813 /// let x : Result<_, &str> = Ok("foo");
814 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);
815 ///
816 /// let x : Result<&str, _> = Err("bar");
817 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
818 /// ```
819 #[inline]
60c5eb7d
XL
820 #[stable(feature = "result_map_or_else", since = "1.41.0")]
821 pub fn map_or_else<U, D: FnOnce(E) -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
822 match self {
823 Ok(t) => f(t),
824 Err(e) => default(e),
825 }
b7449926
XL
826 }
827
92a42be0 828 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
3b2f2976 829 /// contained [`Err`] value, leaving an [`Ok`] value untouched.
1a4d82fc
JJ
830 ///
831 /// This function can be used to pass through a successful result while handling
832 /// an error.
833 ///
3b2f2976 834 ///
c34b1796 835 /// # Examples
1a4d82fc 836 ///
a7813a04
XL
837 /// Basic usage:
838 ///
1a4d82fc 839 /// ```
85aaf69f 840 /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
1a4d82fc 841 ///
85aaf69f
SL
842 /// let x: Result<u32, u32> = Ok(2);
843 /// assert_eq!(x.map_err(stringify), Ok(2));
1a4d82fc 844 ///
85aaf69f 845 /// let x: Result<u32, u32> = Err(13);
1a4d82fc
JJ
846 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
847 /// ```
848 #[inline]
85aaf69f 849 #[stable(feature = "rust1", since = "1.0.0")]
dfeec247 850 pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T, F> {
1a4d82fc
JJ
851 match self {
852 Ok(t) => Ok(t),
dfeec247 853 Err(e) => Err(op(e)),
1a4d82fc
JJ
854 }
855 }
856
857 /////////////////////////////////////////////////////////////////////////
858 // Iterator constructors
859 /////////////////////////////////////////////////////////////////////////
860
861 /// Returns an iterator over the possibly contained value.
862 ///
b7449926 863 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
32a655c1 864 ///
c34b1796 865 /// # Examples
1a4d82fc 866 ///
a7813a04
XL
867 /// Basic usage:
868 ///
1a4d82fc 869 /// ```
85aaf69f 870 /// let x: Result<u32, &str> = Ok(7);
1a4d82fc
JJ
871 /// assert_eq!(x.iter().next(), Some(&7));
872 ///
85aaf69f 873 /// let x: Result<u32, &str> = Err("nothing!");
1a4d82fc
JJ
874 /// assert_eq!(x.iter().next(), None);
875 /// ```
876 #[inline]
85aaf69f 877 #[stable(feature = "rust1", since = "1.0.0")]
48663c56 878 pub fn iter(&self) -> Iter<'_, T> {
1a4d82fc
JJ
879 Iter { inner: self.as_ref().ok() }
880 }
881
882 /// Returns a mutable iterator over the possibly contained value.
883 ///
b7449926 884 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
32a655c1 885 ///
c34b1796 886 /// # Examples
1a4d82fc 887 ///
a7813a04
XL
888 /// Basic usage:
889 ///
1a4d82fc 890 /// ```
85aaf69f 891 /// let mut x: Result<u32, &str> = Ok(7);
1a4d82fc 892 /// match x.iter_mut().next() {
b039eaaf 893 /// Some(v) => *v = 40,
1a4d82fc
JJ
894 /// None => {},
895 /// }
896 /// assert_eq!(x, Ok(40));
897 ///
85aaf69f 898 /// let mut x: Result<u32, &str> = Err("nothing!");
1a4d82fc
JJ
899 /// assert_eq!(x.iter_mut().next(), None);
900 /// ```
901 #[inline]
85aaf69f 902 #[stable(feature = "rust1", since = "1.0.0")]
48663c56 903 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1a4d82fc
JJ
904 IterMut { inner: self.as_mut().ok() }
905 }
906
1a4d82fc
JJ
907 ////////////////////////////////////////////////////////////////////////
908 // Boolean operations on the values, eager and lazy
909 /////////////////////////////////////////////////////////////////////////
910
3b2f2976
XL
911 /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
912 ///
1a4d82fc 913 ///
c34b1796 914 /// # Examples
1a4d82fc 915 ///
a7813a04
XL
916 /// Basic usage:
917 ///
1a4d82fc 918 /// ```
85aaf69f 919 /// let x: Result<u32, &str> = Ok(2);
1a4d82fc
JJ
920 /// let y: Result<&str, &str> = Err("late error");
921 /// assert_eq!(x.and(y), Err("late error"));
922 ///
85aaf69f 923 /// let x: Result<u32, &str> = Err("early error");
1a4d82fc
JJ
924 /// let y: Result<&str, &str> = Ok("foo");
925 /// assert_eq!(x.and(y), Err("early error"));
926 ///
85aaf69f 927 /// let x: Result<u32, &str> = Err("not a 2");
1a4d82fc
JJ
928 /// let y: Result<&str, &str> = Err("late error");
929 /// assert_eq!(x.and(y), Err("not a 2"));
930 ///
85aaf69f 931 /// let x: Result<u32, &str> = Ok(2);
1a4d82fc
JJ
932 /// let y: Result<&str, &str> = Ok("different result type");
933 /// assert_eq!(x.and(y), Ok("different result type"));
934 /// ```
935 #[inline]
85aaf69f 936 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
937 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
938 match self {
939 Ok(_) => res,
940 Err(e) => Err(e),
941 }
942 }
943
3b2f2976
XL
944 /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
945 ///
1a4d82fc 946 ///
9e0c209e 947 /// This function can be used for control flow based on `Result` values.
1a4d82fc 948 ///
c34b1796 949 /// # Examples
1a4d82fc 950 ///
a7813a04
XL
951 /// Basic usage:
952 ///
1a4d82fc 953 /// ```
85aaf69f
SL
954 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
955 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
1a4d82fc
JJ
956 ///
957 /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
958 /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
959 /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
960 /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
961 /// ```
962 #[inline]
85aaf69f 963 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
964 pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
965 match self {
966 Ok(t) => op(t),
967 Err(e) => Err(e),
968 }
969 }
970
3b2f2976
XL
971 /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
972 ///
ff7c6d11
XL
973 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
974 /// result of a function call, it is recommended to use [`or_else`], which is
975 /// lazily evaluated.
976 ///
3dfed10e 977 /// [`or_else`]: Result::or_else
1a4d82fc 978 ///
c34b1796 979 /// # Examples
1a4d82fc 980 ///
a7813a04
XL
981 /// Basic usage:
982 ///
1a4d82fc 983 /// ```
85aaf69f
SL
984 /// let x: Result<u32, &str> = Ok(2);
985 /// let y: Result<u32, &str> = Err("late error");
1a4d82fc
JJ
986 /// assert_eq!(x.or(y), Ok(2));
987 ///
85aaf69f
SL
988 /// let x: Result<u32, &str> = Err("early error");
989 /// let y: Result<u32, &str> = Ok(2);
1a4d82fc
JJ
990 /// assert_eq!(x.or(y), Ok(2));
991 ///
85aaf69f
SL
992 /// let x: Result<u32, &str> = Err("not a 2");
993 /// let y: Result<u32, &str> = Err("late error");
1a4d82fc
JJ
994 /// assert_eq!(x.or(y), Err("late error"));
995 ///
85aaf69f
SL
996 /// let x: Result<u32, &str> = Ok(2);
997 /// let y: Result<u32, &str> = Ok(100);
1a4d82fc
JJ
998 /// assert_eq!(x.or(y), Ok(2));
999 /// ```
1000 #[inline]
85aaf69f 1001 #[stable(feature = "rust1", since = "1.0.0")]
c34b1796 1002 pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
1a4d82fc 1003 match self {
c34b1796 1004 Ok(v) => Ok(v),
1a4d82fc
JJ
1005 Err(_) => res,
1006 }
1007 }
1008
3b2f2976 1009 /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
1a4d82fc
JJ
1010 ///
1011 /// This function can be used for control flow based on result values.
1012 ///
3b2f2976 1013 ///
c34b1796 1014 /// # Examples
1a4d82fc 1015 ///
a7813a04
XL
1016 /// Basic usage:
1017 ///
1a4d82fc 1018 /// ```
85aaf69f
SL
1019 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
1020 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
1a4d82fc
JJ
1021 ///
1022 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
1023 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
1024 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
1025 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
1026 /// ```
1027 #[inline]
85aaf69f 1028 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1029 pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
1030 match self {
1031 Ok(t) => Ok(t),
1032 Err(e) => op(e),
1033 }
1034 }
1035
74b04a01 1036 /// Returns the contained [`Ok`] value or a provided default.
1a4d82fc 1037 ///
ff7c6d11
XL
1038 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
1039 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
1040 /// which is lazily evaluated.
1041 ///
3dfed10e 1042 /// [`unwrap_or_else`]: Result::unwrap_or_else
3b2f2976 1043 ///
c34b1796 1044 /// # Examples
1a4d82fc 1045 ///
a7813a04
XL
1046 /// Basic usage:
1047 ///
1a4d82fc 1048 /// ```
74b04a01 1049 /// let default = 2;
85aaf69f 1050 /// let x: Result<u32, &str> = Ok(9);
74b04a01 1051 /// assert_eq!(x.unwrap_or(default), 9);
1a4d82fc 1052 ///
85aaf69f 1053 /// let x: Result<u32, &str> = Err("error");
74b04a01 1054 /// assert_eq!(x.unwrap_or(default), default);
1a4d82fc
JJ
1055 /// ```
1056 #[inline]
85aaf69f 1057 #[stable(feature = "rust1", since = "1.0.0")]
74b04a01 1058 pub fn unwrap_or(self, default: T) -> T {
1a4d82fc
JJ
1059 match self {
1060 Ok(t) => t,
74b04a01 1061 Err(_) => default,
1a4d82fc
JJ
1062 }
1063 }
1064
74b04a01 1065 /// Returns the contained [`Ok`] value or computes it from a closure.
3b2f2976 1066 ///
1a4d82fc 1067 ///
c34b1796 1068 /// # Examples
1a4d82fc 1069 ///
a7813a04
XL
1070 /// Basic usage:
1071 ///
1a4d82fc 1072 /// ```
85aaf69f 1073 /// fn count(x: &str) -> usize { x.len() }
1a4d82fc 1074 ///
85aaf69f
SL
1075 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
1076 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
1a4d82fc
JJ
1077 /// ```
1078 #[inline]
85aaf69f 1079 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1080 pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
1081 match self {
1082 Ok(t) => t,
dfeec247 1083 Err(e) => op(e),
1a4d82fc
JJ
1084 }
1085 }
5869c6ff
XL
1086
1087 /// Returns the contained [`Ok`] value, consuming the `self` value,
1088 /// without checking that the value is not an [`Err`].
1089 ///
1090 /// # Safety
1091 ///
1092 /// Calling this method on an [`Err`] is *[undefined behavior]*.
1093 ///
1094 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1095 ///
1096 /// # Examples
1097 ///
1098 /// ```
1099 /// #![feature(option_result_unwrap_unchecked)]
1100 /// let x: Result<u32, &str> = Ok(2);
1101 /// assert_eq!(unsafe { x.unwrap_unchecked() }, 2);
1102 /// ```
1103 ///
1104 /// ```no_run
1105 /// #![feature(option_result_unwrap_unchecked)]
1106 /// let x: Result<u32, &str> = Err("emergency failure");
1107 /// unsafe { x.unwrap_unchecked(); } // Undefined behavior!
1108 /// ```
1109 #[inline]
1110 #[track_caller]
1111 #[unstable(feature = "option_result_unwrap_unchecked", reason = "newly added", issue = "81383")]
1112 pub unsafe fn unwrap_unchecked(self) -> T {
1113 debug_assert!(self.is_ok());
1114 match self {
1115 Ok(t) => t,
1116 // SAFETY: the safety contract must be upheld by the caller.
1117 Err(_) => unsafe { hint::unreachable_unchecked() },
1118 }
1119 }
1120
1121 /// Returns the contained [`Err`] value, consuming the `self` value,
1122 /// without checking that the value is not an [`Ok`].
1123 ///
1124 /// # Safety
1125 ///
1126 /// Calling this method on an [`Ok`] is *[undefined behavior]*.
1127 ///
1128 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1129 ///
1130 /// # Examples
1131 ///
1132 /// ```no_run
1133 /// #![feature(option_result_unwrap_unchecked)]
1134 /// let x: Result<u32, &str> = Ok(2);
1135 /// unsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
1136 /// ```
1137 ///
1138 /// ```
1139 /// #![feature(option_result_unwrap_unchecked)]
1140 /// let x: Result<u32, &str> = Err("emergency failure");
1141 /// assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure");
1142 /// ```
1143 #[inline]
1144 #[track_caller]
1145 #[unstable(feature = "option_result_unwrap_unchecked", reason = "newly added", issue = "81383")]
1146 pub unsafe fn unwrap_err_unchecked(self) -> E {
1147 debug_assert!(self.is_err());
1148 match self {
1149 // SAFETY: the safety contract must be upheld by the caller.
1150 Ok(_) => unsafe { hint::unreachable_unchecked() },
1151 Err(e) => e,
1152 }
1153 }
1a4d82fc
JJ
1154}
1155
e1599b0c
XL
1156impl<T: Copy, E> Result<&T, E> {
1157 /// Maps a `Result<&T, E>` to a `Result<T, E>` by copying the contents of the
1158 /// `Ok` part.
1159 ///
1160 /// # Examples
1161 ///
1162 /// ```
1163 /// #![feature(result_copied)]
1164 /// let val = 12;
1165 /// let x: Result<&i32, i32> = Ok(&val);
1166 /// assert_eq!(x, Ok(&12));
1167 /// let copied = x.copied();
1168 /// assert_eq!(copied, Ok(12));
1169 /// ```
1170 #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
1171 pub fn copied(self) -> Result<T, E> {
1172 self.map(|&t| t)
1173 }
1174}
1175
1176impl<T: Copy, E> Result<&mut T, E> {
1177 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by copying the contents of the
1178 /// `Ok` part.
1179 ///
1180 /// # Examples
1181 ///
1182 /// ```
1183 /// #![feature(result_copied)]
1184 /// let mut val = 12;
1185 /// let x: Result<&mut i32, i32> = Ok(&mut val);
1186 /// assert_eq!(x, Ok(&mut 12));
1187 /// let copied = x.copied();
1188 /// assert_eq!(copied, Ok(12));
1189 /// ```
1190 #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
1191 pub fn copied(self) -> Result<T, E> {
1192 self.map(|&mut t| t)
1193 }
1194}
1195
1196impl<T: Clone, E> Result<&T, E> {
1197 /// Maps a `Result<&T, E>` to a `Result<T, E>` by cloning the contents of the
1198 /// `Ok` part.
1199 ///
1200 /// # Examples
1201 ///
1202 /// ```
1203 /// #![feature(result_cloned)]
1204 /// let val = 12;
1205 /// let x: Result<&i32, i32> = Ok(&val);
1206 /// assert_eq!(x, Ok(&12));
1207 /// let cloned = x.cloned();
1208 /// assert_eq!(cloned, Ok(12));
1209 /// ```
1210 #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
1211 pub fn cloned(self) -> Result<T, E> {
1212 self.map(|t| t.clone())
1213 }
1214}
1215
1216impl<T: Clone, E> Result<&mut T, E> {
1217 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by cloning the contents of the
1218 /// `Ok` part.
1219 ///
1220 /// # Examples
1221 ///
1222 /// ```
1223 /// #![feature(result_cloned)]
1224 /// let mut val = 12;
1225 /// let x: Result<&mut i32, i32> = Ok(&mut val);
1226 /// assert_eq!(x, Ok(&mut 12));
1227 /// let cloned = x.cloned();
1228 /// assert_eq!(cloned, Ok(12));
1229 /// ```
1230 #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
1231 pub fn cloned(self) -> Result<T, E> {
1232 self.map(|t| t.clone())
1233 }
1234}
1235
85aaf69f 1236impl<T, E: fmt::Debug> Result<T, E> {
74b04a01
XL
1237 /// Returns the contained [`Ok`] value, consuming the `self` value.
1238 ///
1239 /// # Panics
1240 ///
1241 /// Panics if the value is an [`Err`], with a panic message including the
1242 /// passed message, and the content of the [`Err`].
1243 ///
74b04a01
XL
1244 ///
1245 /// # Examples
1246 ///
1247 /// Basic usage:
1248 ///
6a06907d 1249 /// ```should_panic
74b04a01
XL
1250 /// let x: Result<u32, &str> = Err("emergency failure");
1251 /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
1252 /// ```
1253 #[inline]
1254 #[track_caller]
1255 #[stable(feature = "result_expect", since = "1.4.0")]
1256 pub fn expect(self, msg: &str) -> T {
1257 match self {
1258 Ok(t) => t,
1259 Err(e) => unwrap_failed(msg, &e),
1260 }
1261 }
1262
1263 /// Returns the contained [`Ok`] value, consuming the `self` value.
1264 ///
1265 /// Because this function may panic, its use is generally discouraged.
1266 /// Instead, prefer to use pattern matching and handle the [`Err`]
1267 /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
1268 /// [`unwrap_or_default`].
1269 ///
3dfed10e
XL
1270 /// [`unwrap_or`]: Result::unwrap_or
1271 /// [`unwrap_or_else`]: Result::unwrap_or_else
1272 /// [`unwrap_or_default`]: Result::unwrap_or_default
1a4d82fc
JJ
1273 ///
1274 /// # Panics
1275 ///
3b2f2976
XL
1276 /// Panics if the value is an [`Err`], with a panic message provided by the
1277 /// [`Err`]'s value.
1278 ///
1a4d82fc 1279 ///
c34b1796 1280 /// # Examples
1a4d82fc 1281 ///
a7813a04
XL
1282 /// Basic usage:
1283 ///
1a4d82fc 1284 /// ```
85aaf69f
SL
1285 /// let x: Result<u32, &str> = Ok(2);
1286 /// assert_eq!(x.unwrap(), 2);
1a4d82fc
JJ
1287 /// ```
1288 ///
6a06907d 1289 /// ```should_panic
85aaf69f 1290 /// let x: Result<u32, &str> = Err("emergency failure");
1a4d82fc
JJ
1291 /// x.unwrap(); // panics with `emergency failure`
1292 /// ```
1293 #[inline]
dfeec247 1294 #[track_caller]
85aaf69f 1295 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1296 pub fn unwrap(self) -> T {
1297 match self {
1298 Ok(t) => t,
416331ca 1299 Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e),
1a4d82fc
JJ
1300 }
1301 }
74b04a01 1302}
62682a34 1303
74b04a01
XL
1304impl<T: fmt::Debug, E> Result<T, E> {
1305 /// Returns the contained [`Err`] value, consuming the `self` value.
62682a34 1306 ///
9cc50fc6
SL
1307 /// # Panics
1308 ///
74b04a01
XL
1309 /// Panics if the value is an [`Ok`], with a panic message including the
1310 /// passed message, and the content of the [`Ok`].
3b2f2976 1311 ///
62682a34
SL
1312 ///
1313 /// # Examples
a7813a04
XL
1314 ///
1315 /// Basic usage:
1316 ///
6a06907d 1317 /// ```should_panic
74b04a01
XL
1318 /// let x: Result<u32, &str> = Ok(10);
1319 /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
62682a34
SL
1320 /// ```
1321 #[inline]
dfeec247 1322 #[track_caller]
74b04a01
XL
1323 #[stable(feature = "result_expect_err", since = "1.17.0")]
1324 pub fn expect_err(self, msg: &str) -> E {
62682a34 1325 match self {
74b04a01
XL
1326 Ok(t) => unwrap_failed(msg, &t),
1327 Err(e) => e,
62682a34
SL
1328 }
1329 }
1a4d82fc 1330
74b04a01 1331 /// Returns the contained [`Err`] value, consuming the `self` value.
1a4d82fc
JJ
1332 ///
1333 /// # Panics
1334 ///
3b2f2976
XL
1335 /// Panics if the value is an [`Ok`], with a custom panic message provided
1336 /// by the [`Ok`]'s value.
1337 ///
c34b1796 1338 /// # Examples
1a4d82fc 1339 ///
6a06907d 1340 /// ```should_panic
85aaf69f 1341 /// let x: Result<u32, &str> = Ok(2);
1a4d82fc
JJ
1342 /// x.unwrap_err(); // panics with `2`
1343 /// ```
1344 ///
1345 /// ```
85aaf69f 1346 /// let x: Result<u32, &str> = Err("emergency failure");
1a4d82fc
JJ
1347 /// assert_eq!(x.unwrap_err(), "emergency failure");
1348 /// ```
1349 #[inline]
dfeec247 1350 #[track_caller]
85aaf69f 1351 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1352 pub fn unwrap_err(self) -> E {
1353 match self {
416331ca 1354 Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t),
7453a54e 1355 Err(e) => e,
1a4d82fc
JJ
1356 }
1357 }
1358}
1359
c30ab7b3 1360impl<T: Default, E> Result<T, E> {
74b04a01 1361 /// Returns the contained [`Ok`] value or a default
c30ab7b3 1362 ///
3b2f2976
XL
1363 /// Consumes the `self` argument then, if [`Ok`], returns the contained
1364 /// value, otherwise if [`Err`], returns the default value for that
c30ab7b3
SL
1365 /// type.
1366 ///
1367 /// # Examples
1368 ///
9fa01778 1369 /// Converts a string to an integer, turning poorly-formed strings
c30ab7b3
SL
1370 /// into 0 (the default value for integers). [`parse`] converts
1371 /// a string to any other type that implements [`FromStr`], returning an
3b2f2976 1372 /// [`Err`] on error.
c30ab7b3
SL
1373 ///
1374 /// ```
c30ab7b3
SL
1375 /// let good_year_from_input = "1909";
1376 /// let bad_year_from_input = "190blarg";
1377 /// let good_year = good_year_from_input.parse().unwrap_or_default();
1378 /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
1379 ///
1380 /// assert_eq!(1909, good_year);
1381 /// assert_eq!(0, bad_year);
cc61c64b 1382 /// ```
c30ab7b3 1383 ///
3dfed10e
XL
1384 /// [`parse`]: str::parse
1385 /// [`FromStr`]: crate::str::FromStr
c30ab7b3 1386 #[inline]
32a655c1 1387 #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
c30ab7b3
SL
1388 pub fn unwrap_or_default(self) -> T {
1389 match self {
1390 Ok(x) => x,
1391 Err(_) => Default::default(),
2c00a5a8
XL
1392 }
1393 }
1394}
1395
dfeec247
XL
1396#[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
1397impl<T, E: Into<!>> Result<T, E> {
74b04a01 1398 /// Returns the contained [`Ok`] value, but never panics.
dfeec247
XL
1399 ///
1400 /// Unlike [`unwrap`], this method is known to never panic on the
1401 /// result types it is implemented for. Therefore, it can be used
1402 /// instead of `unwrap` as a maintainability safeguard that will fail
1403 /// to compile if the error type of the `Result` is later changed
1404 /// to an error that can actually occur.
1405 ///
3dfed10e 1406 /// [`unwrap`]: Result::unwrap
dfeec247
XL
1407 ///
1408 /// # Examples
1409 ///
1410 /// Basic usage:
1411 ///
1412 /// ```
1413 /// # #![feature(never_type)]
1414 /// # #![feature(unwrap_infallible)]
1415 ///
1416 /// fn only_good_news() -> Result<String, !> {
1417 /// Ok("this is fine".into())
1418 /// }
1419 ///
1420 /// let s: String = only_good_news().into_ok();
1421 /// println!("{}", s);
1422 /// ```
1423 #[inline]
1424 pub fn into_ok(self) -> T {
1425 match self {
1426 Ok(x) => x,
1427 Err(e) => e.into(),
1428 }
1429 }
1430}
1431
cdc7bbd5
XL
1432#[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
1433impl<T: Into<!>, E> Result<T, E> {
1434 /// Returns the contained [`Err`] value, but never panics.
1435 ///
1436 /// Unlike [`unwrap_err`], this method is known to never panic on the
1437 /// result types it is implemented for. Therefore, it can be used
1438 /// instead of `unwrap_err` as a maintainability safeguard that will fail
1439 /// to compile if the ok type of the `Result` is later changed
1440 /// to a type that can actually occur.
1441 ///
1442 /// [`unwrap_err`]: Result::unwrap_err
1443 ///
1444 /// # Examples
1445 ///
1446 /// Basic usage:
1447 ///
1448 /// ```
1449 /// # #![feature(never_type)]
1450 /// # #![feature(unwrap_infallible)]
1451 ///
1452 /// fn only_bad_news() -> Result<!, String> {
1453 /// Err("Oops, it failed".into())
1454 /// }
1455 ///
1456 /// let error: String = only_bad_news().into_err();
1457 /// println!("{}", error);
1458 /// ```
1459 #[inline]
1460 pub fn into_err(self) -> E {
1461 match self {
1462 Ok(x) => x.into(),
1463 Err(e) => e,
1464 }
1465 }
1466}
1467
b7449926 1468impl<T: Deref, E> Result<T, E> {
f035d41b 1469 /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&<T as Deref>::Target, &E>`.
b7449926 1470 ///
f035d41b
XL
1471 /// Coerces the [`Ok`] variant of the original [`Result`] via [`Deref`](crate::ops::Deref)
1472 /// and returns the new [`Result`].
1473 ///
1474 /// # Examples
1475 ///
1476 /// ```
f035d41b
XL
1477 /// let x: Result<String, u32> = Ok("hello".to_string());
1478 /// let y: Result<&str, &u32> = Ok("hello");
1479 /// assert_eq!(x.as_deref(), y);
1480 ///
1481 /// let x: Result<String, u32> = Err(42);
1482 /// let y: Result<&str, &u32> = Err(&42);
1483 /// assert_eq!(x.as_deref(), y);
1484 /// ```
3dfed10e 1485 #[stable(feature = "inner_deref", since = "1.47.0")]
dfeec247 1486 pub fn as_deref(&self) -> Result<&T::Target, &E> {
b7449926
XL
1487 self.as_ref().map(|t| t.deref())
1488 }
1489}
1490
416331ca 1491impl<T: DerefMut, E> Result<T, E> {
f035d41b 1492 /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut <T as DerefMut>::Target, &mut E>`.
416331ca 1493 ///
f035d41b
XL
1494 /// Coerces the [`Ok`] variant of the original [`Result`] via [`DerefMut`](crate::ops::DerefMut)
1495 /// and returns the new [`Result`].
1496 ///
1497 /// # Examples
1498 ///
1499 /// ```
f035d41b
XL
1500 /// let mut s = "HELLO".to_string();
1501 /// let mut x: Result<String, u32> = Ok("hello".to_string());
1502 /// let y: Result<&mut str, &mut u32> = Ok(&mut s);
1503 /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
1504 ///
1505 /// let mut i = 42;
1506 /// let mut x: Result<String, u32> = Err(42);
1507 /// let y: Result<&mut str, &mut u32> = Err(&mut i);
1508 /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
1509 /// ```
3dfed10e 1510 #[stable(feature = "inner_deref", since = "1.47.0")]
dfeec247 1511 pub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E> {
416331ca
XL
1512 self.as_mut().map(|t| t.deref_mut())
1513 }
1514}
1515
2c00a5a8
XL
1516impl<T, E> Result<Option<T>, E> {
1517 /// Transposes a `Result` of an `Option` into an `Option` of a `Result`.
1518 ///
1519 /// `Ok(None)` will be mapped to `None`.
1520 /// `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`.
1521 ///
1522 /// # Examples
1523 ///
1524 /// ```
2c00a5a8
XL
1525 /// #[derive(Debug, Eq, PartialEq)]
1526 /// struct SomeErr;
1527 ///
1528 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1529 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1530 /// assert_eq!(x.transpose(), y);
1531 /// ```
1532 #[inline]
0731742a 1533 #[stable(feature = "transpose_result", since = "1.33.0")]
6a06907d
XL
1534 #[rustc_const_unstable(feature = "const_result", issue = "82814")]
1535 pub const fn transpose(self) -> Option<Result<T, E>> {
2c00a5a8
XL
1536 match self {
1537 Ok(Some(x)) => Some(Ok(x)),
1538 Ok(None) => None,
1539 Err(e) => Some(Err(e)),
c30ab7b3
SL
1540 }
1541 }
1542}
1543
ba9703b0
XL
1544impl<T, E> Result<Result<T, E>, E> {
1545 /// Converts from `Result<Result<T, E>, E>` to `Result<T, E>`
1546 ///
1547 /// # Examples
fc512014 1548 ///
ba9703b0 1549 /// Basic usage:
fc512014 1550 ///
ba9703b0
XL
1551 /// ```
1552 /// #![feature(result_flattening)]
1553 /// let x: Result<Result<&'static str, u32>, u32> = Ok(Ok("hello"));
1554 /// assert_eq!(Ok("hello"), x.flatten());
1555 ///
1556 /// let x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));
1557 /// assert_eq!(Err(6), x.flatten());
1558 ///
1559 /// let x: Result<Result<&'static str, u32>, u32> = Err(6);
1560 /// assert_eq!(Err(6), x.flatten());
1561 /// ```
1562 ///
fc512014 1563 /// Flattening only removes one level of nesting at a time:
ba9703b0
XL
1564 ///
1565 /// ```
1566 /// #![feature(result_flattening)]
1567 /// let x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok("hello")));
1568 /// assert_eq!(Ok(Ok("hello")), x.flatten());
1569 /// assert_eq!(Ok("hello"), x.flatten().flatten());
1570 /// ```
1571 #[inline]
1572 #[unstable(feature = "result_flattening", issue = "70142")]
1573 pub fn flatten(self) -> Result<T, E> {
1574 self.and_then(convert::identity)
1575 }
1576}
1577
6a06907d
XL
1578impl<T> Result<T, T> {
1579 /// Returns the [`Ok`] value if `self` is `Ok`, and the [`Err`] value if
1580 /// `self` is `Err`.
1581 ///
1582 /// In other words, this function returns the value (the `T`) of a
1583 /// `Result<T, T>`, regardless of whether or not that result is `Ok` or
1584 /// `Err`.
1585 ///
1586 /// This can be useful in conjunction with APIs such as
1587 /// [`Atomic*::compare_exchange`], or [`slice::binary_search`], but only in
1588 /// cases where you don't care if the result was `Ok` or not.
1589 ///
1590 /// [`Atomic*::compare_exchange`]: crate::sync::atomic::AtomicBool::compare_exchange
1591 ///
1592 /// # Examples
1593 ///
1594 /// ```
1595 /// #![feature(result_into_ok_or_err)]
1596 /// let ok: Result<u32, u32> = Ok(3);
1597 /// let err: Result<u32, u32> = Err(4);
1598 ///
1599 /// assert_eq!(ok.into_ok_or_err(), 3);
1600 /// assert_eq!(err.into_ok_or_err(), 4);
1601 /// ```
1602 #[inline]
1603 #[unstable(feature = "result_into_ok_or_err", reason = "newly added", issue = "82223")]
1604 pub const fn into_ok_or_err(self) -> T {
1605 match self {
1606 Ok(v) => v,
1607 Err(v) => v,
1608 }
1609 }
1610}
1611
7453a54e
SL
1612// This is a separate function to reduce the code size of the methods
1613#[inline(never)]
1614#[cold]
dfeec247 1615#[track_caller]
416331ca 1616fn unwrap_failed(msg: &str, error: &dyn fmt::Debug) -> ! {
7453a54e
SL
1617 panic!("{}: {:?}", msg, error)
1618}
1619
1a4d82fc
JJ
1620/////////////////////////////////////////////////////////////////////////////
1621// Trait implementations
1622/////////////////////////////////////////////////////////////////////////////
1623
dc9dc135
XL
1624#[stable(feature = "rust1", since = "1.0.0")]
1625impl<T: Clone, E: Clone> Clone for Result<T, E> {
1626 #[inline]
1627 fn clone(&self) -> Self {
1628 match self {
1629 Ok(x) => Ok(x.clone()),
1630 Err(x) => Err(x.clone()),
1631 }
1632 }
1633
1634 #[inline]
1635 fn clone_from(&mut self, source: &Self) {
1636 match (self, source) {
1637 (Ok(to), Ok(from)) => to.clone_from(from),
1638 (Err(to), Err(from)) => to.clone_from(from),
1639 (to, from) => *to = from.clone(),
1640 }
1641 }
1642}
1643
9346a6ac
AL
1644#[stable(feature = "rust1", since = "1.0.0")]
1645impl<T, E> IntoIterator for Result<T, E> {
1646 type Item = T;
1647 type IntoIter = IntoIter<T>;
1648
1649 /// Returns a consuming iterator over the possibly contained value.
1650 ///
b7449926 1651 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
32a655c1 1652 ///
9346a6ac
AL
1653 /// # Examples
1654 ///
a7813a04
XL
1655 /// Basic usage:
1656 ///
9346a6ac
AL
1657 /// ```
1658 /// let x: Result<u32, &str> = Ok(5);
1659 /// let v: Vec<u32> = x.into_iter().collect();
1660 /// assert_eq!(v, [5]);
1661 ///
1662 /// let x: Result<u32, &str> = Err("nothing!");
1663 /// let v: Vec<u32> = x.into_iter().collect();
1664 /// assert_eq!(v, []);
1665 /// ```
1a4d82fc 1666 #[inline]
9346a6ac
AL
1667 fn into_iter(self) -> IntoIter<T> {
1668 IntoIter { inner: self.ok() }
1a4d82fc
JJ
1669 }
1670}
1671
e9174d1e
SL
1672#[stable(since = "1.4.0", feature = "result_iter")]
1673impl<'a, T, E> IntoIterator for &'a Result<T, E> {
1674 type Item = &'a T;
1675 type IntoIter = Iter<'a, T>;
1676
1677 fn into_iter(self) -> Iter<'a, T> {
1678 self.iter()
1679 }
1680}
1681
1682#[stable(since = "1.4.0", feature = "result_iter")]
1683impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
1684 type Item = &'a mut T;
1685 type IntoIter = IterMut<'a, T>;
1686
3b2f2976 1687 fn into_iter(self) -> IterMut<'a, T> {
e9174d1e
SL
1688 self.iter_mut()
1689 }
1690}
1691
1a4d82fc
JJ
1692/////////////////////////////////////////////////////////////////////////////
1693// The Result Iterators
1694/////////////////////////////////////////////////////////////////////////////
1695
9e0c209e
SL
1696/// An iterator over a reference to the [`Ok`] variant of a [`Result`].
1697///
32a655c1
SL
1698/// The iterator yields one value if the result is [`Ok`], otherwise none.
1699///
1700/// Created by [`Result::iter`].
54a0048b 1701#[derive(Debug)]
85aaf69f 1702#[stable(feature = "rust1", since = "1.0.0")]
dfeec247
XL
1703pub struct Iter<'a, T: 'a> {
1704 inner: Option<&'a T>,
1705}
1a4d82fc 1706
85aaf69f 1707#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1708impl<'a, T> Iterator for Iter<'a, T> {
1709 type Item = &'a T;
1710
1711 #[inline]
dfeec247
XL
1712 fn next(&mut self) -> Option<&'a T> {
1713 self.inner.take()
1714 }
1a4d82fc 1715 #[inline]
85aaf69f 1716 fn size_hint(&self) -> (usize, Option<usize>) {
dfeec247 1717 let n = if self.inner.is_some() { 1 } else { 0 };
1a4d82fc
JJ
1718 (n, Some(n))
1719 }
1720}
1721
85aaf69f 1722#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1723impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1724 #[inline]
dfeec247
XL
1725 fn next_back(&mut self) -> Option<&'a T> {
1726 self.inner.take()
1727 }
1a4d82fc
JJ
1728}
1729
85aaf69f 1730#[stable(feature = "rust1", since = "1.0.0")]
0bf4aa26 1731impl<T> ExactSizeIterator for Iter<'_, T> {}
1a4d82fc 1732
0531ce1d 1733#[stable(feature = "fused", since = "1.26.0")]
0bf4aa26 1734impl<T> FusedIterator for Iter<'_, T> {}
9e0c209e 1735
c30ab7b3 1736#[unstable(feature = "trusted_len", issue = "37572")]
0bf4aa26 1737unsafe impl<A> TrustedLen for Iter<'_, A> {}
c30ab7b3 1738
92a42be0 1739#[stable(feature = "rust1", since = "1.0.0")]
0bf4aa26 1740impl<T> Clone for Iter<'_, T> {
b7449926 1741 #[inline]
dfeec247
XL
1742 fn clone(&self) -> Self {
1743 Iter { inner: self.inner }
1744 }
1a4d82fc
JJ
1745}
1746
9e0c209e
SL
1747/// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
1748///
32a655c1 1749/// Created by [`Result::iter_mut`].
54a0048b 1750#[derive(Debug)]
85aaf69f 1751#[stable(feature = "rust1", since = "1.0.0")]
dfeec247
XL
1752pub struct IterMut<'a, T: 'a> {
1753 inner: Option<&'a mut T>,
1754}
1a4d82fc 1755
85aaf69f 1756#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1757impl<'a, T> Iterator for IterMut<'a, T> {
1758 type Item = &'a mut T;
1759
1760 #[inline]
dfeec247
XL
1761 fn next(&mut self) -> Option<&'a mut T> {
1762 self.inner.take()
1763 }
1a4d82fc 1764 #[inline]
85aaf69f 1765 fn size_hint(&self) -> (usize, Option<usize>) {
dfeec247 1766 let n = if self.inner.is_some() { 1 } else { 0 };
1a4d82fc
JJ
1767 (n, Some(n))
1768 }
1769}
1770
85aaf69f 1771#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1772impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1773 #[inline]
dfeec247
XL
1774 fn next_back(&mut self) -> Option<&'a mut T> {
1775 self.inner.take()
1776 }
1a4d82fc
JJ
1777}
1778
85aaf69f 1779#[stable(feature = "rust1", since = "1.0.0")]
0bf4aa26 1780impl<T> ExactSizeIterator for IterMut<'_, T> {}
1a4d82fc 1781
0531ce1d 1782#[stable(feature = "fused", since = "1.26.0")]
0bf4aa26 1783impl<T> FusedIterator for IterMut<'_, T> {}
9e0c209e 1784
c30ab7b3 1785#[unstable(feature = "trusted_len", issue = "37572")]
0bf4aa26 1786unsafe impl<A> TrustedLen for IterMut<'_, A> {}
c30ab7b3 1787
32a655c1
SL
1788/// An iterator over the value in a [`Ok`] variant of a [`Result`].
1789///
1790/// The iterator yields one value if the result is [`Ok`], otherwise none.
1791///
1792/// This struct is created by the [`into_iter`] method on
dfeec247 1793/// [`Result`] (provided by the [`IntoIterator`] trait).
9e0c209e 1794///
3dfed10e 1795/// [`into_iter`]: IntoIterator::into_iter
abe05a73 1796#[derive(Clone, Debug)]
85aaf69f 1797#[stable(feature = "rust1", since = "1.0.0")]
dfeec247
XL
1798pub struct IntoIter<T> {
1799 inner: Option<T>,
1800}
1a4d82fc 1801
85aaf69f 1802#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1803impl<T> Iterator for IntoIter<T> {
1804 type Item = T;
1805
1806 #[inline]
dfeec247
XL
1807 fn next(&mut self) -> Option<T> {
1808 self.inner.take()
1809 }
1a4d82fc 1810 #[inline]
85aaf69f 1811 fn size_hint(&self) -> (usize, Option<usize>) {
dfeec247 1812 let n = if self.inner.is_some() { 1 } else { 0 };
1a4d82fc
JJ
1813 (n, Some(n))
1814 }
1815}
1816
85aaf69f 1817#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1818impl<T> DoubleEndedIterator for IntoIter<T> {
1819 #[inline]
dfeec247
XL
1820 fn next_back(&mut self) -> Option<T> {
1821 self.inner.take()
1822 }
1a4d82fc
JJ
1823}
1824
85aaf69f 1825#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1826impl<T> ExactSizeIterator for IntoIter<T> {}
1827
0531ce1d 1828#[stable(feature = "fused", since = "1.26.0")]
9e0c209e
SL
1829impl<T> FusedIterator for IntoIter<T> {}
1830
c30ab7b3
SL
1831#[unstable(feature = "trusted_len", issue = "37572")]
1832unsafe impl<A> TrustedLen for IntoIter<A> {}
1833
1a4d82fc
JJ
1834/////////////////////////////////////////////////////////////////////////////
1835// FromIterator
1836/////////////////////////////////////////////////////////////////////////////
1837
85aaf69f 1838#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1839impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
1840 /// Takes each element in the `Iterator`: if it is an `Err`, no further
1841 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
1842 /// container with the values of each `Result` is returned.
1843 ///
1844 /// Here is an example which increments every integer in a vector,
1845 /// checking for overflow:
1846 ///
c34b1796 1847 /// ```
c30ab7b3 1848 /// let v = vec![1, 2];
041b39d2
XL
1849 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1850 /// x.checked_add(1).ok_or("Overflow!")
1a4d82fc 1851 /// ).collect();
532ac7d7 1852 /// assert_eq!(res, Ok(vec![2, 3]));
1a4d82fc 1853 /// ```
532ac7d7
XL
1854 ///
1855 /// Here is another example that tries to subtract one from another list
1856 /// of integers, this time checking for underflow:
1857 ///
1858 /// ```
1859 /// let v = vec![1, 2, 0];
1860 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1861 /// x.checked_sub(1).ok_or("Underflow!")
1862 /// ).collect();
1863 /// assert_eq!(res, Err("Underflow!"));
1864 /// ```
1865 ///
1866 /// Here is a variation on the previous example, showing that no
1867 /// further elements are taken from `iter` after the first `Err`.
1868 ///
1869 /// ```
1870 /// let v = vec![3, 2, 1, 10];
1871 /// let mut shared = 0;
1872 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {
1873 /// shared += x;
1874 /// x.checked_sub(2).ok_or("Underflow!")
1875 /// }).collect();
1876 /// assert_eq!(res, Err("Underflow!"));
1877 /// assert_eq!(shared, 6);
1878 /// ```
1879 ///
1880 /// Since the third element caused an underflow, no further elements were taken,
1881 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1a4d82fc 1882 #[inline]
dfeec247 1883 fn from_iter<I: IntoIterator<Item = Result<A, E>>>(iter: I) -> Result<V, E> {
1a4d82fc
JJ
1884 // FIXME(#11084): This could be replaced with Iterator::scan when this
1885 // performance bug is closed.
1886
416331ca 1887 iter::process_results(iter.into_iter(), |i| i.collect())
1a4d82fc
JJ
1888 }
1889}
7cac9316 1890
cdc7bbd5 1891#[unstable(feature = "try_trait_v2", issue = "84277")]
94222f64 1892impl<T, E> ops::Try for Result<T, E> {
cdc7bbd5
XL
1893 type Output = T;
1894 type Residual = Result<convert::Infallible, E>;
1895
1896 #[inline]
1897 fn from_output(output: Self::Output) -> Self {
1898 Ok(output)
1899 }
1900
1901 #[inline]
1902 fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
1903 match self {
1904 Ok(v) => ControlFlow::Continue(v),
1905 Err(e) => ControlFlow::Break(Err(e)),
1906 }
1907 }
1908}
1909
1910#[unstable(feature = "try_trait_v2", issue = "84277")]
1911impl<T, E, F: From<E>> ops::FromResidual<Result<convert::Infallible, E>> for Result<T, F> {
1912 #[inline]
1913 fn from_residual(residual: Result<convert::Infallible, E>) -> Self {
1914 match residual {
1915 Err(e) => Err(From::from(e)),
1916 }
1917 }
1918}