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