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