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