Skip to main content

core/
result.rs

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