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