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