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