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
536#[cfg(not(feature = "ferrocene_certified"))]
537use crate::iter::{self, FusedIterator, TrustedLen};
538use crate::marker::Destruct;
539#[cfg(not(feature = "ferrocene_certified"))]
540use crate::ops::{self, ControlFlow, Deref, DerefMut};
541#[cfg(feature = "ferrocene_certified")]
542use crate::ops::{Deref, DerefMut};
543#[cfg(not(feature = "ferrocene_certified"))]
544use crate::{convert, fmt, hint};
545
546/// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]).
547///
548/// See the [module documentation](self) for details.
549#[doc(search_unbox)]
550#[cfg_attr(not(feature = "ferrocene_certified"), derive(Copy, Debug, Hash))]
551#[cfg_attr(not(feature = "ferrocene_certified"), derive_const(PartialEq, PartialOrd, Eq, Ord,))]
552#[must_use = "this `Result` may be an `Err` variant, which should be handled"]
553#[rustc_diagnostic_item = "Result"]
554#[stable(feature = "rust1", since = "1.0.0")]
555pub enum Result<T, E> {
556 /// Contains the success value
557 #[lang = "Ok"]
558 #[stable(feature = "rust1", since = "1.0.0")]
559 Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
560
561 /// Contains the error value
562 #[lang = "Err"]
563 #[stable(feature = "rust1", since = "1.0.0")]
564 Err(#[stable(feature = "rust1", since = "1.0.0")] E),
565}
566
567/////////////////////////////////////////////////////////////////////////////
568// Type implementation
569/////////////////////////////////////////////////////////////////////////////
570
571impl<T, E> Result<T, E> {
572 /////////////////////////////////////////////////////////////////////////
573 // Querying the contained values
574 /////////////////////////////////////////////////////////////////////////
575
576 /// Returns `true` if the result is [`Ok`].
577 ///
578 /// # Examples
579 ///
580 /// ```
581 /// let x: Result<i32, &str> = Ok(-3);
582 /// assert_eq!(x.is_ok(), true);
583 ///
584 /// let x: Result<i32, &str> = Err("Some error message");
585 /// assert_eq!(x.is_ok(), false);
586 /// ```
587 #[must_use = "if you intended to assert that this is ok, consider `.unwrap()` instead"]
588 #[rustc_const_stable(feature = "const_result_basics", since = "1.48.0")]
589 #[inline]
590 #[stable(feature = "rust1", since = "1.0.0")]
591 pub const fn is_ok(&self) -> bool {
592 matches!(*self, Ok(_))
593 }
594
595 /// Returns `true` if the result is [`Ok`] and the value inside of it matches a predicate.
596 ///
597 /// # Examples
598 ///
599 /// ```
600 /// let x: Result<u32, &str> = Ok(2);
601 /// assert_eq!(x.is_ok_and(|x| x > 1), true);
602 ///
603 /// let x: Result<u32, &str> = Ok(0);
604 /// assert_eq!(x.is_ok_and(|x| x > 1), false);
605 ///
606 /// let x: Result<u32, &str> = Err("hey");
607 /// assert_eq!(x.is_ok_and(|x| x > 1), false);
608 ///
609 /// let x: Result<String, &str> = Ok("ownership".to_string());
610 /// assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true);
611 /// println!("still alive {:?}", x);
612 /// ```
613 #[must_use]
614 #[inline]
615 #[stable(feature = "is_some_and", since = "1.70.0")]
616 #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
617 pub const fn is_ok_and<F>(self, f: F) -> bool
618 where
619 F: [const] FnOnce(T) -> bool + [const] Destruct,
620 T: [const] Destruct,
621 E: [const] Destruct,
622 {
623 match self {
624 Err(_) => false,
625 Ok(x) => f(x),
626 }
627 }
628
629 /// Returns `true` if the result is [`Err`].
630 ///
631 /// # Examples
632 ///
633 /// ```
634 /// let x: Result<i32, &str> = Ok(-3);
635 /// assert_eq!(x.is_err(), false);
636 ///
637 /// let x: Result<i32, &str> = Err("Some error message");
638 /// assert_eq!(x.is_err(), true);
639 /// ```
640 #[must_use = "if you intended to assert that this is err, consider `.unwrap_err()` instead"]
641 #[rustc_const_stable(feature = "const_result_basics", since = "1.48.0")]
642 #[inline]
643 #[stable(feature = "rust1", since = "1.0.0")]
644 pub const fn is_err(&self) -> bool {
645 !self.is_ok()
646 }
647
648 /// Returns `true` if the result is [`Err`] and the value inside of it matches a predicate.
649 ///
650 /// # Examples
651 ///
652 /// ```
653 /// use std::io::{Error, ErrorKind};
654 ///
655 /// let x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, "!"));
656 /// assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);
657 ///
658 /// let x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, "!"));
659 /// assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
660 ///
661 /// let x: Result<u32, Error> = Ok(123);
662 /// assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
663 ///
664 /// let x: Result<u32, String> = Err("ownership".to_string());
665 /// assert_eq!(x.as_ref().is_err_and(|x| x.len() > 1), true);
666 /// println!("still alive {:?}", x);
667 /// ```
668 #[must_use]
669 #[inline]
670 #[stable(feature = "is_some_and", since = "1.70.0")]
671 #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
672 pub const fn is_err_and<F>(self, f: F) -> bool
673 where
674 F: [const] FnOnce(E) -> bool + [const] Destruct,
675 E: [const] Destruct,
676 T: [const] Destruct,
677 {
678 match self {
679 Ok(_) => false,
680 Err(e) => f(e),
681 }
682 }
683
684 /////////////////////////////////////////////////////////////////////////
685 // Adapter for each variant
686 /////////////////////////////////////////////////////////////////////////
687
688 /// Converts from `Result<T, E>` to [`Option<T>`].
689 ///
690 /// Converts `self` into an [`Option<T>`], consuming `self`,
691 /// and discarding the error, if any.
692 ///
693 /// # Examples
694 ///
695 /// ```
696 /// let x: Result<u32, &str> = Ok(2);
697 /// assert_eq!(x.ok(), Some(2));
698 ///
699 /// let x: Result<u32, &str> = Err("Nothing here");
700 /// assert_eq!(x.ok(), None);
701 /// ```
702 #[inline]
703 #[stable(feature = "rust1", since = "1.0.0")]
704 #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
705 #[rustc_diagnostic_item = "result_ok_method"]
706 pub const fn ok(self) -> Option<T>
707 where
708 T: [const] Destruct,
709 E: [const] Destruct,
710 {
711 match self {
712 Ok(x) => Some(x),
713 Err(_) => None,
714 }
715 }
716
717 /// Converts from `Result<T, E>` to [`Option<E>`].
718 ///
719 /// Converts `self` into an [`Option<E>`], consuming `self`,
720 /// and discarding the success value, if any.
721 ///
722 /// # Examples
723 ///
724 /// ```
725 /// let x: Result<u32, &str> = Ok(2);
726 /// assert_eq!(x.err(), None);
727 ///
728 /// let x: Result<u32, &str> = Err("Nothing here");
729 /// assert_eq!(x.err(), Some("Nothing here"));
730 /// ```
731 #[inline]
732 #[stable(feature = "rust1", since = "1.0.0")]
733 #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
734 pub const fn err(self) -> Option<E>
735 where
736 T: [const] Destruct,
737 E: [const] Destruct,
738 {
739 match self {
740 Ok(_) => None,
741 Err(x) => Some(x),
742 }
743 }
744
745 /////////////////////////////////////////////////////////////////////////
746 // Adapter for working with references
747 /////////////////////////////////////////////////////////////////////////
748
749 /// Converts from `&Result<T, E>` to `Result<&T, &E>`.
750 ///
751 /// Produces a new `Result`, containing a reference
752 /// into the original, leaving the original in place.
753 ///
754 /// # Examples
755 ///
756 /// ```
757 /// let x: Result<u32, &str> = Ok(2);
758 /// assert_eq!(x.as_ref(), Ok(&2));
759 ///
760 /// let x: Result<u32, &str> = Err("Error");
761 /// assert_eq!(x.as_ref(), Err(&"Error"));
762 /// ```
763 #[inline]
764 #[rustc_const_stable(feature = "const_result_basics", since = "1.48.0")]
765 #[stable(feature = "rust1", since = "1.0.0")]
766 pub const fn as_ref(&self) -> Result<&T, &E> {
767 match *self {
768 Ok(ref x) => Ok(x),
769 Err(ref x) => Err(x),
770 }
771 }
772
773 /// Converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`.
774 ///
775 /// # Examples
776 ///
777 /// ```
778 /// fn mutate(r: &mut Result<i32, i32>) {
779 /// match r.as_mut() {
780 /// Ok(v) => *v = 42,
781 /// Err(e) => *e = 0,
782 /// }
783 /// }
784 ///
785 /// let mut x: Result<i32, i32> = Ok(2);
786 /// mutate(&mut x);
787 /// assert_eq!(x.unwrap(), 42);
788 ///
789 /// let mut x: Result<i32, i32> = Err(13);
790 /// mutate(&mut x);
791 /// assert_eq!(x.unwrap_err(), 0);
792 /// ```
793 #[inline]
794 #[stable(feature = "rust1", since = "1.0.0")]
795 #[rustc_const_stable(feature = "const_result", since = "1.83.0")]
796 pub const fn as_mut(&mut self) -> Result<&mut T, &mut E> {
797 match *self {
798 Ok(ref mut x) => Ok(x),
799 Err(ref mut x) => Err(x),
800 }
801 }
802
803 /////////////////////////////////////////////////////////////////////////
804 // Transforming contained values
805 /////////////////////////////////////////////////////////////////////////
806
807 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
808 /// contained [`Ok`] value, leaving an [`Err`] value untouched.
809 ///
810 /// This function can be used to compose the results of two functions.
811 ///
812 /// # Examples
813 ///
814 /// Print the numbers on each line of a string multiplied by two.
815 ///
816 /// ```
817 /// let line = "1\n2\n3\n4\n";
818 ///
819 /// for num in line.lines() {
820 /// match num.parse::<i32>().map(|i| i * 2) {
821 /// Ok(n) => println!("{n}"),
822 /// Err(..) => {}
823 /// }
824 /// }
825 /// ```
826 #[inline]
827 #[stable(feature = "rust1", since = "1.0.0")]
828 #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
829 pub const fn map<U, F>(self, op: F) -> Result<U, E>
830 where
831 F: [const] FnOnce(T) -> U + [const] Destruct,
832 {
833 match self {
834 Ok(t) => Ok(op(t)),
835 Err(e) => Err(e),
836 }
837 }
838
839 /// Returns the provided default (if [`Err`]), or
840 /// applies a function to the contained value (if [`Ok`]).
841 ///
842 /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
843 /// the result of a function call, it is recommended to use [`map_or_else`],
844 /// which is lazily evaluated.
845 ///
846 /// [`map_or_else`]: Result::map_or_else
847 ///
848 /// # Examples
849 ///
850 /// ```
851 /// let x: Result<_, &str> = Ok("foo");
852 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
853 ///
854 /// let x: Result<&str, _> = Err("bar");
855 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
856 /// ```
857 #[inline]
858 #[stable(feature = "result_map_or", since = "1.41.0")]
859 #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
860 #[must_use = "if you don't need the returned value, use `if let` instead"]
861 pub const fn map_or<U, F>(self, default: U, f: F) -> U
862 where
863 F: [const] FnOnce(T) -> U + [const] Destruct,
864 T: [const] Destruct,
865 E: [const] Destruct,
866 U: [const] Destruct,
867 {
868 match self {
869 Ok(t) => f(t),
870 Err(_) => default,
871 }
872 }
873
874 /// Maps a `Result<T, E>` to `U` by applying fallback function `default` to
875 /// a contained [`Err`] value, or function `f` to a contained [`Ok`] value.
876 ///
877 /// This function can be used to unpack a successful result
878 /// while handling an error.
879 ///
880 ///
881 /// # Examples
882 ///
883 /// ```
884 /// let k = 21;
885 ///
886 /// let x : Result<_, &str> = Ok("foo");
887 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);
888 ///
889 /// let x : Result<&str, _> = Err("bar");
890 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
891 /// ```
892 #[inline]
893 #[stable(feature = "result_map_or_else", since = "1.41.0")]
894 #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
895 pub const fn map_or_else<U, D, F>(self, default: D, f: F) -> U
896 where
897 D: [const] FnOnce(E) -> U + [const] Destruct,
898 F: [const] FnOnce(T) -> U + [const] Destruct,
899 {
900 match self {
901 Ok(t) => f(t),
902 Err(e) => default(e),
903 }
904 }
905
906 /// Maps a `Result<T, E>` to a `U` by applying function `f` to the contained
907 /// value if the result is [`Ok`], otherwise if [`Err`], returns the
908 /// [default value] for the type `U`.
909 ///
910 /// # Examples
911 ///
912 /// ```
913 /// #![feature(result_option_map_or_default)]
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 #[unstable(feature = "result_option_map_or_default", issue = "138099")]
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 // Ferrocene annotation: This function is thoroughly tested inside the `result_methods`
992 // test in `coretests`. Additionally, the `inspect_result` test guarantees that `f` is
993 // being called by panicking inside the `predicate` body and marking the test as
994 // `#[should_panic]`.
995 f(t);
996 }
997
998 self
999 }
1000
1001 /// Calls a function with a reference to the contained value if [`Err`].
1002 ///
1003 /// Returns the original result.
1004 ///
1005 /// # Examples
1006 ///
1007 /// ```
1008 /// use std::{fs, io};
1009 ///
1010 /// fn read() -> io::Result<String> {
1011 /// fs::read_to_string("address.txt")
1012 /// .inspect_err(|e| eprintln!("failed to read file: {e}"))
1013 /// }
1014 /// ```
1015 #[inline]
1016 #[stable(feature = "result_option_inspect", since = "1.76.0")]
1017 #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
1018 pub const fn inspect_err<F>(self, f: F) -> Self
1019 where
1020 F: [const] FnOnce(&E) + [const] Destruct,
1021 {
1022 if let Err(ref e) = self {
1023 // Ferrocene annotation: This function is thoroughly tested inside the `result_methods`
1024 // test in `coretests`. Additionally, the `inspect_result_err` test guarantees that `f`
1025 // is being called by panicking inside the `predicate` body and marking the test as
1026 // `#[should_panic]`.
1027 f(e);
1028 }
1029
1030 self
1031 }
1032
1033 /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&<T as Deref>::Target, &E>`.
1034 ///
1035 /// Coerces the [`Ok`] variant of the original [`Result`] via [`Deref`](crate::ops::Deref)
1036 /// and returns the new [`Result`].
1037 ///
1038 /// # Examples
1039 ///
1040 /// ```
1041 /// let x: Result<String, u32> = Ok("hello".to_string());
1042 /// let y: Result<&str, &u32> = Ok("hello");
1043 /// assert_eq!(x.as_deref(), y);
1044 ///
1045 /// let x: Result<String, u32> = Err(42);
1046 /// let y: Result<&str, &u32> = Err(&42);
1047 /// assert_eq!(x.as_deref(), y);
1048 /// ```
1049 #[inline]
1050 #[stable(feature = "inner_deref", since = "1.47.0")]
1051 #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1052 pub const fn as_deref(&self) -> Result<&T::Target, &E>
1053 where
1054 T: [const] Deref,
1055 {
1056 self.as_ref().map(Deref::deref)
1057 }
1058
1059 /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut <T as DerefMut>::Target, &mut E>`.
1060 ///
1061 /// Coerces the [`Ok`] variant of the original [`Result`] via [`DerefMut`](crate::ops::DerefMut)
1062 /// and returns the new [`Result`].
1063 ///
1064 /// # Examples
1065 ///
1066 /// ```
1067 /// let mut s = "HELLO".to_string();
1068 /// let mut x: Result<String, u32> = Ok("hello".to_string());
1069 /// let y: Result<&mut str, &mut u32> = Ok(&mut s);
1070 /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
1071 ///
1072 /// let mut i = 42;
1073 /// let mut x: Result<String, u32> = Err(42);
1074 /// let y: Result<&mut str, &mut u32> = Err(&mut i);
1075 /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
1076 /// ```
1077 #[inline]
1078 #[stable(feature = "inner_deref", since = "1.47.0")]
1079 #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1080 pub const fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E>
1081 where
1082 T: [const] DerefMut,
1083 {
1084 self.as_mut().map(DerefMut::deref_mut)
1085 }
1086
1087 /////////////////////////////////////////////////////////////////////////
1088 // Iterator constructors
1089 /////////////////////////////////////////////////////////////////////////
1090
1091 /// Returns an iterator over the possibly contained value.
1092 ///
1093 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
1094 ///
1095 /// # Examples
1096 ///
1097 /// ```
1098 /// let x: Result<u32, &str> = Ok(7);
1099 /// assert_eq!(x.iter().next(), Some(&7));
1100 ///
1101 /// let x: Result<u32, &str> = Err("nothing!");
1102 /// assert_eq!(x.iter().next(), None);
1103 /// ```
1104 #[inline]
1105 #[stable(feature = "rust1", since = "1.0.0")]
1106 #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
1107 // blocked on Iterator
1108 #[cfg(not(feature = "ferrocene_certified"))]
1109 pub const fn iter(&self) -> Iter<'_, T> {
1110 Iter { inner: self.as_ref().ok() }
1111 }
1112
1113 /// Returns a mutable iterator over the possibly contained value.
1114 ///
1115 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
1116 ///
1117 /// # Examples
1118 ///
1119 /// ```
1120 /// let mut x: Result<u32, &str> = Ok(7);
1121 /// match x.iter_mut().next() {
1122 /// Some(v) => *v = 40,
1123 /// None => {},
1124 /// }
1125 /// assert_eq!(x, Ok(40));
1126 ///
1127 /// let mut x: Result<u32, &str> = Err("nothing!");
1128 /// assert_eq!(x.iter_mut().next(), None);
1129 /// ```
1130 #[inline]
1131 #[stable(feature = "rust1", since = "1.0.0")]
1132 #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
1133 // blocked on Iterator
1134 #[cfg(not(feature = "ferrocene_certified"))]
1135 pub const fn iter_mut(&mut self) -> IterMut<'_, T> {
1136 IterMut { inner: self.as_mut().ok() }
1137 }
1138
1139 /////////////////////////////////////////////////////////////////////////
1140 // Extract a value
1141 /////////////////////////////////////////////////////////////////////////
1142
1143 /// Returns the contained [`Ok`] value, consuming the `self` value.
1144 ///
1145 /// Because this function may panic, its use is generally discouraged.
1146 /// Instead, prefer to use pattern matching and handle the [`Err`]
1147 /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
1148 /// [`unwrap_or_default`].
1149 ///
1150 /// [`unwrap_or`]: Result::unwrap_or
1151 /// [`unwrap_or_else`]: Result::unwrap_or_else
1152 /// [`unwrap_or_default`]: Result::unwrap_or_default
1153 ///
1154 /// # Panics
1155 ///
1156 /// Panics if the value is an [`Err`], with a panic message including the
1157 /// passed message, and the content of the [`Err`].
1158 ///
1159 ///
1160 /// # Examples
1161 ///
1162 /// ```should_panic
1163 /// let x: Result<u32, &str> = Err("emergency failure");
1164 /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
1165 /// ```
1166 ///
1167 /// # Recommended Message Style
1168 ///
1169 /// We recommend that `expect` messages are used to describe the reason you
1170 /// _expect_ the `Result` should be `Ok`.
1171 ///
1172 /// ```should_panic
1173 /// let path = std::env::var("IMPORTANT_PATH")
1174 /// .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`");
1175 /// ```
1176 ///
1177 /// **Hint**: If you're having trouble remembering how to phrase expect
1178 /// error messages remember to focus on the word "should" as in "env
1179 /// variable should be set by blah" or "the given binary should be available
1180 /// and executable by the current user".
1181 ///
1182 /// For more detail on expect message styles and the reasoning behind our recommendation please
1183 /// refer to the section on ["Common Message
1184 /// Styles"](../../std/error/index.html#common-message-styles) in the
1185 /// [`std::error`](../../std/error/index.html) module docs.
1186 #[inline]
1187 #[track_caller]
1188 #[stable(feature = "result_expect", since = "1.4.0")]
1189 // blocked on Debug
1190 #[cfg(not(feature = "ferrocene_certified"))]
1191 pub fn expect(self, msg: &str) -> T
1192 where
1193 E: fmt::Debug,
1194 {
1195 match self {
1196 Ok(t) => t,
1197 Err(e) => unwrap_failed(msg, &e),
1198 }
1199 }
1200
1201 /// Returns the contained [`Ok`] value, consuming the `self` value.
1202 ///
1203 /// Because this function may panic, its use is generally discouraged.
1204 /// Panics are meant for unrecoverable errors, and
1205 /// [may abort the entire program][panic-abort].
1206 ///
1207 /// Instead, prefer to use [the `?` (try) operator][try-operator], or pattern matching
1208 /// to handle the [`Err`] case explicitly, or call [`unwrap_or`],
1209 /// [`unwrap_or_else`], or [`unwrap_or_default`].
1210 ///
1211 /// [panic-abort]: https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html
1212 /// [try-operator]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator
1213 /// [`unwrap_or`]: Result::unwrap_or
1214 /// [`unwrap_or_else`]: Result::unwrap_or_else
1215 /// [`unwrap_or_default`]: Result::unwrap_or_default
1216 ///
1217 /// # Panics
1218 ///
1219 /// Panics if the value is an [`Err`], with a panic message provided by the
1220 /// [`Err`]'s value.
1221 ///
1222 ///
1223 /// # Examples
1224 ///
1225 /// Basic usage:
1226 ///
1227 /// ```
1228 /// let x: Result<u32, &str> = Ok(2);
1229 /// assert_eq!(x.unwrap(), 2);
1230 /// ```
1231 ///
1232 /// ```should_panic
1233 /// let x: Result<u32, &str> = Err("emergency failure");
1234 /// x.unwrap(); // panics with `emergency failure`
1235 /// ```
1236 #[inline(always)]
1237 #[track_caller]
1238 #[stable(feature = "rust1", since = "1.0.0")]
1239 // blocked on Debug
1240 #[cfg(not(feature = "ferrocene_certified"))]
1241 pub fn unwrap(self) -> T
1242 where
1243 E: fmt::Debug,
1244 {
1245 match self {
1246 Ok(t) => t,
1247 Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e),
1248 }
1249 }
1250
1251 /// Returns the contained [`Ok`] value or a default
1252 ///
1253 /// Consumes the `self` argument then, if [`Ok`], returns the contained
1254 /// value, otherwise if [`Err`], returns the default value for that
1255 /// type.
1256 ///
1257 /// # Examples
1258 ///
1259 /// Converts a string to an integer, turning poorly-formed strings
1260 /// into 0 (the default value for integers). [`parse`] converts
1261 /// a string to any other type that implements [`FromStr`], returning an
1262 /// [`Err`] on error.
1263 ///
1264 /// ```
1265 /// let good_year_from_input = "1909";
1266 /// let bad_year_from_input = "190blarg";
1267 /// let good_year = good_year_from_input.parse().unwrap_or_default();
1268 /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
1269 ///
1270 /// assert_eq!(1909, good_year);
1271 /// assert_eq!(0, bad_year);
1272 /// ```
1273 ///
1274 /// [`parse`]: str::parse
1275 /// [`FromStr`]: crate::str::FromStr
1276 #[inline]
1277 #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
1278 #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
1279 pub const fn unwrap_or_default(self) -> T
1280 where
1281 T: [const] Default + [const] Destruct,
1282 E: [const] Destruct,
1283 {
1284 match self {
1285 Ok(x) => x,
1286 Err(_) => Default::default(),
1287 }
1288 }
1289
1290 /// Returns the contained [`Err`] value, consuming the `self` value.
1291 ///
1292 /// # Panics
1293 ///
1294 /// Panics if the value is an [`Ok`], with a panic message including the
1295 /// passed message, and the content of the [`Ok`].
1296 ///
1297 ///
1298 /// # Examples
1299 ///
1300 /// ```should_panic
1301 /// let x: Result<u32, &str> = Ok(10);
1302 /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
1303 /// ```
1304 #[inline]
1305 #[track_caller]
1306 #[stable(feature = "result_expect_err", since = "1.17.0")]
1307 // blocked on Debug
1308 #[cfg(not(feature = "ferrocene_certified"))]
1309 pub fn expect_err(self, msg: &str) -> E
1310 where
1311 T: fmt::Debug,
1312 {
1313 match self {
1314 Ok(t) => unwrap_failed(msg, &t),
1315 Err(e) => e,
1316 }
1317 }
1318
1319 /// Returns the contained [`Err`] value, consuming the `self` value.
1320 ///
1321 /// # Panics
1322 ///
1323 /// Panics if the value is an [`Ok`], with a custom panic message provided
1324 /// by the [`Ok`]'s value.
1325 ///
1326 /// # Examples
1327 ///
1328 /// ```should_panic
1329 /// let x: Result<u32, &str> = Ok(2);
1330 /// x.unwrap_err(); // panics with `2`
1331 /// ```
1332 ///
1333 /// ```
1334 /// let x: Result<u32, &str> = Err("emergency failure");
1335 /// assert_eq!(x.unwrap_err(), "emergency failure");
1336 /// ```
1337 #[inline]
1338 #[track_caller]
1339 #[stable(feature = "rust1", since = "1.0.0")]
1340 // blocked on Debug
1341 #[cfg(not(feature = "ferrocene_certified"))]
1342 pub fn unwrap_err(self) -> E
1343 where
1344 T: fmt::Debug,
1345 {
1346 match self {
1347 Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t),
1348 Err(e) => e,
1349 }
1350 }
1351
1352 /// Returns the contained [`Ok`] value, but never panics.
1353 ///
1354 /// Unlike [`unwrap`], this method is known to never panic on the
1355 /// result types it is implemented for. Therefore, it can be used
1356 /// instead of `unwrap` as a maintainability safeguard that will fail
1357 /// to compile if the error type of the `Result` is later changed
1358 /// to an error that can actually occur.
1359 ///
1360 /// [`unwrap`]: Result::unwrap
1361 ///
1362 /// # Examples
1363 ///
1364 /// ```
1365 /// # #![feature(never_type)]
1366 /// # #![feature(unwrap_infallible)]
1367 ///
1368 /// fn only_good_news() -> Result<String, !> {
1369 /// Ok("this is fine".into())
1370 /// }
1371 ///
1372 /// let s: String = only_good_news().into_ok();
1373 /// println!("{s}");
1374 /// ```
1375 #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
1376 #[inline]
1377 #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
1378 #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1379 // blocked on !
1380 #[cfg(not(feature = "ferrocene_certified"))]
1381 pub const fn into_ok(self) -> T
1382 where
1383 E: [const] Into<!>,
1384 {
1385 match self {
1386 Ok(x) => x,
1387 Err(e) => e.into(),
1388 }
1389 }
1390
1391 /// Returns the contained [`Err`] value, but never panics.
1392 ///
1393 /// Unlike [`unwrap_err`], this method is known to never panic on the
1394 /// result types it is implemented for. Therefore, it can be used
1395 /// instead of `unwrap_err` as a maintainability safeguard that will fail
1396 /// to compile if the ok type of the `Result` is later changed
1397 /// to a type that can actually occur.
1398 ///
1399 /// [`unwrap_err`]: Result::unwrap_err
1400 ///
1401 /// # Examples
1402 ///
1403 /// ```
1404 /// # #![feature(never_type)]
1405 /// # #![feature(unwrap_infallible)]
1406 ///
1407 /// fn only_bad_news() -> Result<!, String> {
1408 /// Err("Oops, it failed".into())
1409 /// }
1410 ///
1411 /// let error: String = only_bad_news().into_err();
1412 /// println!("{error}");
1413 /// ```
1414 #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
1415 #[inline]
1416 #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
1417 #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1418 // blocked on !
1419 #[cfg(not(feature = "ferrocene_certified"))]
1420 pub const fn into_err(self) -> E
1421 where
1422 T: [const] Into<!>,
1423 {
1424 match self {
1425 Ok(x) => x.into(),
1426 Err(e) => e,
1427 }
1428 }
1429
1430 ////////////////////////////////////////////////////////////////////////
1431 // Boolean operations on the values, eager and lazy
1432 /////////////////////////////////////////////////////////////////////////
1433
1434 /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
1435 ///
1436 /// Arguments passed to `and` are eagerly evaluated; if you are passing the
1437 /// result of a function call, it is recommended to use [`and_then`], which is
1438 /// lazily evaluated.
1439 ///
1440 /// [`and_then`]: Result::and_then
1441 ///
1442 /// # Examples
1443 ///
1444 /// ```
1445 /// let x: Result<u32, &str> = Ok(2);
1446 /// let y: Result<&str, &str> = Err("late error");
1447 /// assert_eq!(x.and(y), Err("late error"));
1448 ///
1449 /// let x: Result<u32, &str> = Err("early error");
1450 /// let y: Result<&str, &str> = Ok("foo");
1451 /// assert_eq!(x.and(y), Err("early error"));
1452 ///
1453 /// let x: Result<u32, &str> = Err("not a 2");
1454 /// let y: Result<&str, &str> = Err("late error");
1455 /// assert_eq!(x.and(y), Err("not a 2"));
1456 ///
1457 /// let x: Result<u32, &str> = Ok(2);
1458 /// let y: Result<&str, &str> = Ok("different result type");
1459 /// assert_eq!(x.and(y), Ok("different result type"));
1460 /// ```
1461 #[inline]
1462 #[stable(feature = "rust1", since = "1.0.0")]
1463 #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
1464 pub const fn and<U>(self, res: Result<U, E>) -> Result<U, E>
1465 where
1466 T: [const] Destruct,
1467 E: [const] Destruct,
1468 U: [const] Destruct,
1469 {
1470 match self {
1471 Ok(_) => res,
1472 Err(e) => Err(e),
1473 }
1474 }
1475
1476 /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
1477 ///
1478 ///
1479 /// This function can be used for control flow based on `Result` values.
1480 ///
1481 /// # Examples
1482 ///
1483 /// ```
1484 /// fn sq_then_to_string(x: u32) -> Result<String, &'static str> {
1485 /// x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed")
1486 /// }
1487 ///
1488 /// assert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));
1489 /// assert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err("overflowed"));
1490 /// assert_eq!(Err("not a number").and_then(sq_then_to_string), Err("not a number"));
1491 /// ```
1492 ///
1493 /// Often used to chain fallible operations that may return [`Err`].
1494 ///
1495 /// ```
1496 /// use std::{io::ErrorKind, path::Path};
1497 ///
1498 /// // Note: on Windows "/" maps to "C:\"
1499 /// let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified());
1500 /// assert!(root_modified_time.is_ok());
1501 ///
1502 /// let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified());
1503 /// assert!(should_fail.is_err());
1504 /// assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
1505 /// ```
1506 #[inline]
1507 #[stable(feature = "rust1", since = "1.0.0")]
1508 #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
1509 #[rustc_confusables("flat_map", "flatmap")]
1510 pub const fn and_then<U, F>(self, op: F) -> Result<U, E>
1511 where
1512 F: [const] FnOnce(T) -> Result<U, E> + [const] Destruct,
1513 {
1514 match self {
1515 Ok(t) => op(t),
1516 Err(e) => Err(e),
1517 }
1518 }
1519
1520 /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
1521 ///
1522 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
1523 /// result of a function call, it is recommended to use [`or_else`], which is
1524 /// lazily evaluated.
1525 ///
1526 /// [`or_else`]: Result::or_else
1527 ///
1528 /// # Examples
1529 ///
1530 /// ```
1531 /// let x: Result<u32, &str> = Ok(2);
1532 /// let y: Result<u32, &str> = Err("late error");
1533 /// assert_eq!(x.or(y), Ok(2));
1534 ///
1535 /// let x: Result<u32, &str> = Err("early error");
1536 /// let y: Result<u32, &str> = Ok(2);
1537 /// assert_eq!(x.or(y), Ok(2));
1538 ///
1539 /// let x: Result<u32, &str> = Err("not a 2");
1540 /// let y: Result<u32, &str> = Err("late error");
1541 /// assert_eq!(x.or(y), Err("late error"));
1542 ///
1543 /// let x: Result<u32, &str> = Ok(2);
1544 /// let y: Result<u32, &str> = Ok(100);
1545 /// assert_eq!(x.or(y), Ok(2));
1546 /// ```
1547 #[inline]
1548 #[stable(feature = "rust1", since = "1.0.0")]
1549 #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
1550 pub const fn or<F>(self, res: Result<T, F>) -> Result<T, F>
1551 where
1552 T: [const] Destruct,
1553 E: [const] Destruct,
1554 F: [const] Destruct,
1555 {
1556 match self {
1557 Ok(v) => Ok(v),
1558 Err(_) => res,
1559 }
1560 }
1561
1562 /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
1563 ///
1564 /// This function can be used for control flow based on result values.
1565 ///
1566 ///
1567 /// # Examples
1568 ///
1569 /// ```
1570 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
1571 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
1572 ///
1573 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
1574 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
1575 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
1576 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
1577 /// ```
1578 #[inline]
1579 #[stable(feature = "rust1", since = "1.0.0")]
1580 #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
1581 pub const fn or_else<F, O>(self, op: O) -> Result<T, F>
1582 where
1583 O: [const] FnOnce(E) -> Result<T, F> + [const] Destruct,
1584 {
1585 match self {
1586 Ok(t) => Ok(t),
1587 Err(e) => op(e),
1588 }
1589 }
1590
1591 /// Returns the contained [`Ok`] value or a provided default.
1592 ///
1593 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
1594 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
1595 /// which is lazily evaluated.
1596 ///
1597 /// [`unwrap_or_else`]: Result::unwrap_or_else
1598 ///
1599 /// # Examples
1600 ///
1601 /// ```
1602 /// let default = 2;
1603 /// let x: Result<u32, &str> = Ok(9);
1604 /// assert_eq!(x.unwrap_or(default), 9);
1605 ///
1606 /// let x: Result<u32, &str> = Err("error");
1607 /// assert_eq!(x.unwrap_or(default), default);
1608 /// ```
1609 #[inline]
1610 #[stable(feature = "rust1", since = "1.0.0")]
1611 #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
1612 pub const fn unwrap_or(self, default: T) -> T
1613 where
1614 T: [const] Destruct,
1615 E: [const] Destruct,
1616 {
1617 match self {
1618 Ok(t) => t,
1619 Err(_) => default,
1620 }
1621 }
1622
1623 /// Returns the contained [`Ok`] value or computes it from a closure.
1624 ///
1625 ///
1626 /// # Examples
1627 ///
1628 /// ```
1629 /// fn count(x: &str) -> usize { x.len() }
1630 ///
1631 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
1632 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
1633 /// ```
1634 #[inline]
1635 #[track_caller]
1636 #[stable(feature = "rust1", since = "1.0.0")]
1637 #[rustc_const_unstable(feature = "const_result_trait_fn", issue = "144211")]
1638 pub const fn unwrap_or_else<F>(self, op: F) -> T
1639 where
1640 F: [const] FnOnce(E) -> T + [const] Destruct,
1641 {
1642 match self {
1643 Ok(t) => t,
1644 Err(e) => op(e),
1645 }
1646 }
1647
1648 /// Returns the contained [`Ok`] value, consuming the `self` value,
1649 /// without checking that the value is not an [`Err`].
1650 ///
1651 /// # Safety
1652 ///
1653 /// Calling this method on an [`Err`] is *[undefined behavior]*.
1654 ///
1655 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1656 ///
1657 /// # Examples
1658 ///
1659 /// ```
1660 /// let x: Result<u32, &str> = Ok(2);
1661 /// assert_eq!(unsafe { x.unwrap_unchecked() }, 2);
1662 /// ```
1663 ///
1664 /// ```no_run
1665 /// let x: Result<u32, &str> = Err("emergency failure");
1666 /// unsafe { x.unwrap_unchecked() }; // Undefined behavior!
1667 /// ```
1668 #[inline]
1669 #[track_caller]
1670 #[stable(feature = "option_result_unwrap_unchecked", since = "1.58.0")]
1671 // blocked on hint
1672 #[cfg(not(feature = "ferrocene_certified"))]
1673 pub unsafe fn unwrap_unchecked(self) -> T {
1674 match self {
1675 Ok(t) => t,
1676 // SAFETY: the safety contract must be upheld by the caller.
1677 Err(_) => unsafe { hint::unreachable_unchecked() },
1678 }
1679 }
1680
1681 /// Returns the contained [`Err`] value, consuming the `self` value,
1682 /// without checking that the value is not an [`Ok`].
1683 ///
1684 /// # Safety
1685 ///
1686 /// Calling this method on an [`Ok`] is *[undefined behavior]*.
1687 ///
1688 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1689 ///
1690 /// # Examples
1691 ///
1692 /// ```no_run
1693 /// let x: Result<u32, &str> = Ok(2);
1694 /// unsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
1695 /// ```
1696 ///
1697 /// ```
1698 /// let x: Result<u32, &str> = Err("emergency failure");
1699 /// assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure");
1700 /// ```
1701 #[inline]
1702 #[track_caller]
1703 #[stable(feature = "option_result_unwrap_unchecked", since = "1.58.0")]
1704 // blocked on hint
1705 #[cfg(not(feature = "ferrocene_certified"))]
1706 pub unsafe fn unwrap_err_unchecked(self) -> E {
1707 match self {
1708 // SAFETY: the safety contract must be upheld by the caller.
1709 Ok(_) => unsafe { hint::unreachable_unchecked() },
1710 Err(e) => e,
1711 }
1712 }
1713}
1714
1715impl<T, E> Result<&T, E> {
1716 /// Maps a `Result<&T, E>` to a `Result<T, E>` by copying the contents of the
1717 /// `Ok` part.
1718 ///
1719 /// # Examples
1720 ///
1721 /// ```
1722 /// let val = 12;
1723 /// let x: Result<&i32, i32> = Ok(&val);
1724 /// assert_eq!(x, Ok(&12));
1725 /// let copied = x.copied();
1726 /// assert_eq!(copied, Ok(12));
1727 /// ```
1728 #[inline]
1729 #[stable(feature = "result_copied", since = "1.59.0")]
1730 #[rustc_const_stable(feature = "const_result", since = "1.83.0")]
1731 #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
1732 pub const fn copied(self) -> Result<T, E>
1733 where
1734 T: Copy,
1735 {
1736 // FIXME(const-hack): this implementation, which sidesteps using `Result::map` since it's not const
1737 // ready yet, should be reverted when possible to avoid code repetition
1738 match self {
1739 Ok(&v) => Ok(v),
1740 Err(e) => Err(e),
1741 }
1742 }
1743
1744 /// Maps a `Result<&T, E>` to a `Result<T, E>` by cloning the contents of the
1745 /// `Ok` part.
1746 ///
1747 /// # Examples
1748 ///
1749 /// ```
1750 /// let val = 12;
1751 /// let x: Result<&i32, i32> = Ok(&val);
1752 /// assert_eq!(x, Ok(&12));
1753 /// let cloned = x.cloned();
1754 /// assert_eq!(cloned, Ok(12));
1755 /// ```
1756 #[inline]
1757 #[stable(feature = "result_cloned", since = "1.59.0")]
1758 pub fn cloned(self) -> Result<T, E>
1759 where
1760 T: Clone,
1761 {
1762 self.map(|t| t.clone())
1763 }
1764}
1765
1766impl<T, E> Result<&mut T, E> {
1767 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by copying the contents of the
1768 /// `Ok` part.
1769 ///
1770 /// # Examples
1771 ///
1772 /// ```
1773 /// let mut val = 12;
1774 /// let x: Result<&mut i32, i32> = Ok(&mut val);
1775 /// assert_eq!(x, Ok(&mut 12));
1776 /// let copied = x.copied();
1777 /// assert_eq!(copied, Ok(12));
1778 /// ```
1779 #[inline]
1780 #[stable(feature = "result_copied", since = "1.59.0")]
1781 #[rustc_const_stable(feature = "const_result", since = "1.83.0")]
1782 #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
1783 pub const fn copied(self) -> Result<T, E>
1784 where
1785 T: Copy,
1786 {
1787 // FIXME(const-hack): this implementation, which sidesteps using `Result::map` since it's not const
1788 // ready yet, should be reverted when possible to avoid code repetition
1789 match self {
1790 Ok(&mut v) => Ok(v),
1791 Err(e) => Err(e),
1792 }
1793 }
1794
1795 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by cloning the contents of the
1796 /// `Ok` part.
1797 ///
1798 /// # Examples
1799 ///
1800 /// ```
1801 /// let mut val = 12;
1802 /// let x: Result<&mut i32, i32> = Ok(&mut val);
1803 /// assert_eq!(x, Ok(&mut 12));
1804 /// let cloned = x.cloned();
1805 /// assert_eq!(cloned, Ok(12));
1806 /// ```
1807 #[inline]
1808 #[stable(feature = "result_cloned", since = "1.59.0")]
1809 pub fn cloned(self) -> Result<T, E>
1810 where
1811 T: Clone,
1812 {
1813 self.map(|t| t.clone())
1814 }
1815}
1816
1817impl<T, E> Result<Option<T>, E> {
1818 /// Transposes a `Result` of an `Option` into an `Option` of a `Result`.
1819 ///
1820 /// `Ok(None)` will be mapped to `None`.
1821 /// `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`.
1822 ///
1823 /// # Examples
1824 ///
1825 /// ```
1826 /// #[derive(Debug, Eq, PartialEq)]
1827 /// struct SomeErr;
1828 ///
1829 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1830 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1831 /// assert_eq!(x.transpose(), y);
1832 /// ```
1833 #[inline]
1834 #[stable(feature = "transpose_result", since = "1.33.0")]
1835 #[rustc_const_stable(feature = "const_result", since = "1.83.0")]
1836 #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
1837 pub const fn transpose(self) -> Option<Result<T, E>> {
1838 match self {
1839 Ok(Some(x)) => Some(Ok(x)),
1840 Ok(None) => None,
1841 Err(e) => Some(Err(e)),
1842 }
1843 }
1844}
1845
1846impl<T, E> Result<Result<T, E>, E> {
1847 /// Converts from `Result<Result<T, E>, E>` to `Result<T, E>`
1848 ///
1849 /// # Examples
1850 ///
1851 /// ```
1852 /// let x: Result<Result<&'static str, u32>, u32> = Ok(Ok("hello"));
1853 /// assert_eq!(Ok("hello"), x.flatten());
1854 ///
1855 /// let x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));
1856 /// assert_eq!(Err(6), x.flatten());
1857 ///
1858 /// let x: Result<Result<&'static str, u32>, u32> = Err(6);
1859 /// assert_eq!(Err(6), x.flatten());
1860 /// ```
1861 ///
1862 /// Flattening only removes one level of nesting at a time:
1863 ///
1864 /// ```
1865 /// let x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok("hello")));
1866 /// assert_eq!(Ok(Ok("hello")), x.flatten());
1867 /// assert_eq!(Ok("hello"), x.flatten().flatten());
1868 /// ```
1869 #[inline]
1870 #[stable(feature = "result_flattening", since = "1.89.0")]
1871 #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
1872 #[rustc_const_stable(feature = "result_flattening", since = "1.89.0")]
1873 // blocked on const impl Drop for Result<Result<T, E>>
1874 #[cfg(not(feature = "ferrocene_certified"))]
1875 pub const fn flatten(self) -> Result<T, E> {
1876 // FIXME(const-hack): could be written with `and_then`
1877 match self {
1878 Ok(inner) => inner,
1879 Err(e) => Err(e),
1880 }
1881 }
1882}
1883
1884// This is a separate function to reduce the code size of the methods
1885#[cfg(not(panic = "immediate-abort"))]
1886#[inline(never)]
1887#[cold]
1888#[track_caller]
1889// blocked on Debug
1890#[cfg(not(feature = "ferrocene_certified"))]
1891fn unwrap_failed(msg: &str, error: &dyn fmt::Debug) -> ! {
1892 panic!("{msg}: {error:?}");
1893}
1894
1895// This is a separate function to avoid constructing a `dyn Debug`
1896// that gets immediately thrown away, since vtables don't get cleaned up
1897// by dead code elimination if a trait object is constructed even if it goes
1898// unused
1899#[cfg(panic = "immediate-abort")]
1900#[inline]
1901#[cold]
1902#[track_caller]
1903// blocked on Debug
1904#[cfg(not(feature = "ferrocene_certified"))]
1905const fn unwrap_failed<T>(_msg: &str, _error: &T) -> ! {
1906 panic!()
1907}
1908
1909/////////////////////////////////////////////////////////////////////////////
1910// Trait implementations
1911/////////////////////////////////////////////////////////////////////////////
1912
1913#[stable(feature = "rust1", since = "1.0.0")]
1914#[cfg(not(feature = "ferrocene_certified"))]
1915impl<T, E> Clone for Result<T, E>
1916where
1917 T: Clone,
1918 E: Clone,
1919{
1920 #[inline]
1921 fn clone(&self) -> Self {
1922 match self {
1923 Ok(x) => Ok(x.clone()),
1924 Err(x) => Err(x.clone()),
1925 }
1926 }
1927
1928 #[inline]
1929 fn clone_from(&mut self, source: &Self) {
1930 match (self, source) {
1931 (Ok(to), Ok(from)) => to.clone_from(from),
1932 (Err(to), Err(from)) => to.clone_from(from),
1933 (to, from) => *to = from.clone(),
1934 }
1935 }
1936}
1937
1938#[unstable(feature = "ergonomic_clones", issue = "132290")]
1939#[cfg(not(feature = "ferrocene_certified"))]
1940impl<T, E> crate::clone::UseCloned for Result<T, E>
1941where
1942 T: crate::clone::UseCloned,
1943 E: crate::clone::UseCloned,
1944{
1945}
1946
1947#[stable(feature = "rust1", since = "1.0.0")]
1948#[cfg(not(feature = "ferrocene_certified"))]
1949impl<T, E> IntoIterator for Result<T, E> {
1950 type Item = T;
1951 type IntoIter = IntoIter<T>;
1952
1953 /// Returns a consuming iterator over the possibly contained value.
1954 ///
1955 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
1956 ///
1957 /// # Examples
1958 ///
1959 /// ```
1960 /// let x: Result<u32, &str> = Ok(5);
1961 /// let v: Vec<u32> = x.into_iter().collect();
1962 /// assert_eq!(v, [5]);
1963 ///
1964 /// let x: Result<u32, &str> = Err("nothing!");
1965 /// let v: Vec<u32> = x.into_iter().collect();
1966 /// assert_eq!(v, []);
1967 /// ```
1968 #[inline]
1969 fn into_iter(self) -> IntoIter<T> {
1970 IntoIter { inner: self.ok() }
1971 }
1972}
1973
1974#[stable(since = "1.4.0", feature = "result_iter")]
1975#[cfg(not(feature = "ferrocene_certified"))]
1976impl<'a, T, E> IntoIterator for &'a Result<T, E> {
1977 type Item = &'a T;
1978 type IntoIter = Iter<'a, T>;
1979
1980 fn into_iter(self) -> Iter<'a, T> {
1981 self.iter()
1982 }
1983}
1984
1985#[stable(since = "1.4.0", feature = "result_iter")]
1986#[cfg(not(feature = "ferrocene_certified"))]
1987impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
1988 type Item = &'a mut T;
1989 type IntoIter = IterMut<'a, T>;
1990
1991 fn into_iter(self) -> IterMut<'a, T> {
1992 self.iter_mut()
1993 }
1994}
1995
1996/////////////////////////////////////////////////////////////////////////////
1997// The Result Iterators
1998/////////////////////////////////////////////////////////////////////////////
1999
2000/// An iterator over a reference to the [`Ok`] variant of a [`Result`].
2001///
2002/// The iterator yields one value if the result is [`Ok`], otherwise none.
2003///
2004/// Created by [`Result::iter`].
2005#[derive(Debug)]
2006#[stable(feature = "rust1", since = "1.0.0")]
2007#[cfg(not(feature = "ferrocene_certified"))]
2008pub struct Iter<'a, T: 'a> {
2009 inner: Option<&'a T>,
2010}
2011
2012#[stable(feature = "rust1", since = "1.0.0")]
2013#[cfg(not(feature = "ferrocene_certified"))]
2014impl<'a, T> Iterator for Iter<'a, T> {
2015 type Item = &'a T;
2016
2017 #[inline]
2018 fn next(&mut self) -> Option<&'a 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")]
2029#[cfg(not(feature = "ferrocene_certified"))]
2030impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
2031 #[inline]
2032 fn next_back(&mut self) -> Option<&'a T> {
2033 self.inner.take()
2034 }
2035}
2036
2037#[stable(feature = "rust1", since = "1.0.0")]
2038#[cfg(not(feature = "ferrocene_certified"))]
2039impl<T> ExactSizeIterator for Iter<'_, T> {}
2040
2041#[stable(feature = "fused", since = "1.26.0")]
2042#[cfg(not(feature = "ferrocene_certified"))]
2043impl<T> FusedIterator for Iter<'_, T> {}
2044
2045#[unstable(feature = "trusted_len", issue = "37572")]
2046#[cfg(not(feature = "ferrocene_certified"))]
2047unsafe impl<A> TrustedLen for Iter<'_, A> {}
2048
2049#[stable(feature = "rust1", since = "1.0.0")]
2050#[cfg(not(feature = "ferrocene_certified"))]
2051impl<T> Clone for Iter<'_, T> {
2052 #[inline]
2053 fn clone(&self) -> Self {
2054 Iter { inner: self.inner }
2055 }
2056}
2057
2058/// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
2059///
2060/// Created by [`Result::iter_mut`].
2061#[derive(Debug)]
2062#[stable(feature = "rust1", since = "1.0.0")]
2063#[cfg(not(feature = "ferrocene_certified"))]
2064pub struct IterMut<'a, T: 'a> {
2065 inner: Option<&'a mut T>,
2066}
2067
2068#[stable(feature = "rust1", since = "1.0.0")]
2069#[cfg(not(feature = "ferrocene_certified"))]
2070impl<'a, T> Iterator for IterMut<'a, T> {
2071 type Item = &'a mut T;
2072
2073 #[inline]
2074 fn next(&mut self) -> Option<&'a mut T> {
2075 self.inner.take()
2076 }
2077 #[inline]
2078 fn size_hint(&self) -> (usize, Option<usize>) {
2079 let n = if self.inner.is_some() { 1 } else { 0 };
2080 (n, Some(n))
2081 }
2082}
2083
2084#[stable(feature = "rust1", since = "1.0.0")]
2085#[cfg(not(feature = "ferrocene_certified"))]
2086impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
2087 #[inline]
2088 fn next_back(&mut self) -> Option<&'a mut T> {
2089 self.inner.take()
2090 }
2091}
2092
2093#[stable(feature = "rust1", since = "1.0.0")]
2094#[cfg(not(feature = "ferrocene_certified"))]
2095impl<T> ExactSizeIterator for IterMut<'_, T> {}
2096
2097#[stable(feature = "fused", since = "1.26.0")]
2098#[cfg(not(feature = "ferrocene_certified"))]
2099impl<T> FusedIterator for IterMut<'_, T> {}
2100
2101#[unstable(feature = "trusted_len", issue = "37572")]
2102#[cfg(not(feature = "ferrocene_certified"))]
2103unsafe impl<A> TrustedLen for IterMut<'_, A> {}
2104
2105/// An iterator over the value in a [`Ok`] variant of a [`Result`].
2106///
2107/// The iterator yields one value if the result is [`Ok`], otherwise none.
2108///
2109/// This struct is created by the [`into_iter`] method on
2110/// [`Result`] (provided by the [`IntoIterator`] trait).
2111///
2112/// [`into_iter`]: IntoIterator::into_iter
2113#[derive(Clone, Debug)]
2114#[stable(feature = "rust1", since = "1.0.0")]
2115#[cfg(not(feature = "ferrocene_certified"))]
2116pub struct IntoIter<T> {
2117 inner: Option<T>,
2118}
2119
2120#[stable(feature = "rust1", since = "1.0.0")]
2121#[cfg(not(feature = "ferrocene_certified"))]
2122impl<T> Iterator for IntoIter<T> {
2123 type Item = T;
2124
2125 #[inline]
2126 fn next(&mut self) -> Option<T> {
2127 self.inner.take()
2128 }
2129 #[inline]
2130 fn size_hint(&self) -> (usize, Option<usize>) {
2131 let n = if self.inner.is_some() { 1 } else { 0 };
2132 (n, Some(n))
2133 }
2134}
2135
2136#[stable(feature = "rust1", since = "1.0.0")]
2137#[cfg(not(feature = "ferrocene_certified"))]
2138impl<T> DoubleEndedIterator for IntoIter<T> {
2139 #[inline]
2140 fn next_back(&mut self) -> Option<T> {
2141 self.inner.take()
2142 }
2143}
2144
2145#[stable(feature = "rust1", since = "1.0.0")]
2146#[cfg(not(feature = "ferrocene_certified"))]
2147impl<T> ExactSizeIterator for IntoIter<T> {}
2148
2149#[stable(feature = "fused", since = "1.26.0")]
2150#[cfg(not(feature = "ferrocene_certified"))]
2151impl<T> FusedIterator for IntoIter<T> {}
2152
2153#[unstable(feature = "trusted_len", issue = "37572")]
2154#[cfg(not(feature = "ferrocene_certified"))]
2155unsafe impl<A> TrustedLen for IntoIter<A> {}
2156
2157/////////////////////////////////////////////////////////////////////////////
2158// FromIterator
2159/////////////////////////////////////////////////////////////////////////////
2160
2161#[stable(feature = "rust1", since = "1.0.0")]
2162#[cfg(not(feature = "ferrocene_certified"))]
2163impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
2164 /// Takes each element in the `Iterator`: if it is an `Err`, no further
2165 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
2166 /// container with the values of each `Result` is returned.
2167 ///
2168 /// Here is an example which increments every integer in a vector,
2169 /// checking for overflow:
2170 ///
2171 /// ```
2172 /// let v = vec![1, 2];
2173 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
2174 /// x.checked_add(1).ok_or("Overflow!")
2175 /// ).collect();
2176 /// assert_eq!(res, Ok(vec![2, 3]));
2177 /// ```
2178 ///
2179 /// Here is another example that tries to subtract one from another list
2180 /// of integers, this time checking for underflow:
2181 ///
2182 /// ```
2183 /// let v = vec![1, 2, 0];
2184 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
2185 /// x.checked_sub(1).ok_or("Underflow!")
2186 /// ).collect();
2187 /// assert_eq!(res, Err("Underflow!"));
2188 /// ```
2189 ///
2190 /// Here is a variation on the previous example, showing that no
2191 /// further elements are taken from `iter` after the first `Err`.
2192 ///
2193 /// ```
2194 /// let v = vec![3, 2, 1, 10];
2195 /// let mut shared = 0;
2196 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {
2197 /// shared += x;
2198 /// x.checked_sub(2).ok_or("Underflow!")
2199 /// }).collect();
2200 /// assert_eq!(res, Err("Underflow!"));
2201 /// assert_eq!(shared, 6);
2202 /// ```
2203 ///
2204 /// Since the third element caused an underflow, no further elements were taken,
2205 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
2206 #[inline]
2207 fn from_iter<I: IntoIterator<Item = Result<A, E>>>(iter: I) -> Result<V, E> {
2208 iter::try_process(iter.into_iter(), |i| i.collect())
2209 }
2210}
2211
2212#[unstable(feature = "try_trait_v2", issue = "84277", old_name = "try_trait")]
2213#[rustc_const_unstable(feature = "const_try", issue = "74935")]
2214#[cfg(not(feature = "ferrocene_certified"))]
2215impl<T, E> const ops::Try for Result<T, E> {
2216 type Output = T;
2217 type Residual = Result<convert::Infallible, E>;
2218
2219 #[inline]
2220 fn from_output(output: Self::Output) -> Self {
2221 Ok(output)
2222 }
2223
2224 #[inline]
2225 fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
2226 match self {
2227 Ok(v) => ControlFlow::Continue(v),
2228 Err(e) => ControlFlow::Break(Err(e)),
2229 }
2230 }
2231}
2232
2233#[unstable(feature = "try_trait_v2", issue = "84277", old_name = "try_trait")]
2234#[rustc_const_unstable(feature = "const_try", issue = "74935")]
2235#[cfg(not(feature = "ferrocene_certified"))]
2236impl<T, E, F: [const] From<E>> const ops::FromResidual<Result<convert::Infallible, E>>
2237 for Result<T, F>
2238{
2239 #[inline]
2240 #[track_caller]
2241 fn from_residual(residual: Result<convert::Infallible, E>) -> Self {
2242 match residual {
2243 Err(e) => Err(From::from(e)),
2244 }
2245 }
2246}
2247#[diagnostic::do_not_recommend]
2248#[unstable(feature = "try_trait_v2_yeet", issue = "96374")]
2249#[rustc_const_unstable(feature = "const_try", issue = "74935")]
2250#[cfg(not(feature = "ferrocene_certified"))]
2251impl<T, E, F: [const] From<E>> const ops::FromResidual<ops::Yeet<E>> for Result<T, F> {
2252 #[inline]
2253 fn from_residual(ops::Yeet(e): ops::Yeet<E>) -> Self {
2254 Err(From::from(e))
2255 }
2256}
2257
2258#[unstable(feature = "try_trait_v2_residual", issue = "91285")]
2259#[rustc_const_unstable(feature = "const_try", issue = "74935")]
2260#[cfg(not(feature = "ferrocene_certified"))]
2261impl<T, E> const ops::Residual<T> for Result<convert::Infallible, E> {
2262 type TryType = Result<T, E>;
2263}