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