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