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