1 //! Error handling with the `Result` type.
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.
9 //! # #[allow(dead_code)]
10 //! enum Result<T, E> {
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).
20 //! A simple function returning [`Result`] might be
21 //! defined and used like so:
25 //! enum Version { Version1, Version2 }
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"),
36 //! let version = parse_version(&[1, 2, 3, 4]);
38 //! Ok(v) => println!("working with version: {v:?}"),
39 //! Err(e) => println!("error parsing header: {e:?}"),
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.
48 //! let good_result: Result<i32, i32> = Ok(10);
49 //! let bad_result: Result<i32, i32> = Err(10);
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());
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);
59 //! // Use `and_then` to continue the computation.
60 //! let good_result: Result<bool, i32> = good_result.and_then(|i| Ok(i == 11));
62 //! // Use `or_else` to handle the error.
63 //! let bad_result: Result<i32, i32> = bad_result.or_else(|i| Ok(i + 20));
65 //! // Consume the result and return the contents with `unwrap`.
66 //! let final_awesome_result = good_result.unwrap();
69 //! # Results must be used
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
79 //! Consider the [`write_all`] method defined for I/O types
80 //! by the [`Write`] trait:
86 //! fn write_all(&mut self, bytes: &[u8]) -> Result<(), io::Error>;
90 //! *Note: The actual definition of [`Write`] uses [`io::Result`], which
91 //! is just a synonym for <code>[Result]<T, [io::Error]></code>.*
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:
98 //! # #![allow(unused_must_use)] // \o/
99 //! use std::fs::File;
100 //! use std::io::prelude::*;
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");
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).
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:
116 //! use std::fs::File;
117 //! use std::io::prelude::*;
119 //! let mut file = File::create("valuable_data.txt").unwrap();
120 //! file.write_all(b"important message").expect("failed to write message");
123 //! You might also simply assert success:
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());
132 //! Or propagate the error up the call stack with [`?`]:
135 //! # use std::fs::File;
136 //! # use std::io::prelude::*;
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")?;
146 //! # The question mark operator, `?`
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.
153 //! It replaces this:
156 //! # #![allow(dead_code)]
157 //! use std::fs::File;
158 //! use std::io::prelude::*;
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),
173 //! if let Err(e) = file.write_all(format!("name: {}\n", info.name).as_bytes()) {
176 //! if let Err(e) = file.write_all(format!("age: {}\n", info.age).as_bytes()) {
179 //! if let Err(e) = file.write_all(format!("rating: {}\n", info.rating).as_bytes()) {
189 //! # #![allow(dead_code)]
190 //! use std::fs::File;
191 //! use std::io::prelude::*;
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())?;
210 //! *It's much nicer!*
212 //! Ending the expression with [`?`] will result in the unwrapped
213 //! success ([`Ok`]) value, unless the result is [`Err`], in which case
214 //! [`Err`] is returned early from the enclosing function.
216 //! [`?`] can only be used in functions that return [`Result`] because of the
217 //! early return of [`Err`] that it provides.
219 //! [`expect`]: Result::expect
220 //! [`Write`]: ../../std/io/trait.Write.html "io::Write"
221 //! [`write_all`]: ../../std/io/trait.Write.html#method.write_all "io::Write::write_all"
222 //! [`io::Result`]: ../../std/io/type.Result.html "io::Result"
223 //! [`?`]: crate::ops::Try
226 //! [io::Error]: ../../std/io/struct.Error.html "io::Error"
228 //! # Method overview
230 //! In addition to working with pattern matching, [`Result`] provides a
231 //! wide variety of different methods.
233 //! ## Querying the variant
235 //! The [`is_ok`] and [`is_err`] methods return [`true`] if the [`Result`]
236 //! is [`Ok`] or [`Err`], respectively.
238 //! [`is_err`]: Result::is_err
239 //! [`is_ok`]: Result::is_ok
241 //! ## Adapters for working with references
243 //! * [`as_ref`] converts from `&Result<T, E>` to `Result<&T, &E>`
244 //! * [`as_mut`] converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`
245 //! * [`as_deref`] converts from `&Result<T, E>` to `Result<&T::Target, &E>`
246 //! * [`as_deref_mut`] converts from `&mut Result<T, E>` to
247 //! `Result<&mut T::Target, &mut E>`
249 //! [`as_deref`]: Result::as_deref
250 //! [`as_deref_mut`]: Result::as_deref_mut
251 //! [`as_mut`]: Result::as_mut
252 //! [`as_ref`]: Result::as_ref
254 //! ## Extracting contained values
256 //! These methods extract the contained value in a [`Result<T, E>`] when it
257 //! is the [`Ok`] variant. If the [`Result`] is [`Err`]:
259 //! * [`expect`] panics with a provided custom message
260 //! * [`unwrap`] panics with a generic message
261 //! * [`unwrap_or`] returns the provided default value
262 //! * [`unwrap_or_default`] returns the default value of the type `T`
263 //! (which must implement the [`Default`] trait)
264 //! * [`unwrap_or_else`] returns the result of evaluating the provided
267 //! The panicking methods [`expect`] and [`unwrap`] require `E` to
268 //! implement the [`Debug`] trait.
270 //! [`Debug`]: crate::fmt::Debug
271 //! [`expect`]: Result::expect
272 //! [`unwrap`]: Result::unwrap
273 //! [`unwrap_or`]: Result::unwrap_or
274 //! [`unwrap_or_default`]: Result::unwrap_or_default
275 //! [`unwrap_or_else`]: Result::unwrap_or_else
277 //! These methods extract the contained value in a [`Result<T, E>`] when it
278 //! is the [`Err`] variant. They require `T` to implement the [`Debug`]
279 //! trait. If the [`Result`] is [`Ok`]:
281 //! * [`expect_err`] panics with a provided custom message
282 //! * [`unwrap_err`] panics with a generic message
284 //! [`Debug`]: crate::fmt::Debug
285 //! [`expect_err`]: Result::expect_err
286 //! [`unwrap_err`]: Result::unwrap_err
288 //! ## Transforming contained values
290 //! These methods transform [`Result`] to [`Option`]:
292 //! * [`err`][Result::err] transforms [`Result<T, E>`] into [`Option<E>`],
293 //! mapping [`Err(e)`] to [`Some(e)`] and [`Ok(v)`] to [`None`]
294 //! * [`ok`][Result::ok] transforms [`Result<T, E>`] into [`Option<T>`],
295 //! mapping [`Ok(v)`] to [`Some(v)`] and [`Err(e)`] to [`None`]
296 //! * [`transpose`] transposes a [`Result`] of an [`Option`] into an
297 //! [`Option`] of a [`Result`]
299 // Do NOT add link reference definitions for `err` or `ok`, because they
300 // will generate numerous incorrect URLs for `Err` and `Ok` elsewhere, due
305 //! [`Some(e)`]: Option::Some
306 //! [`Some(v)`]: Option::Some
307 //! [`transpose`]: Result::transpose
309 //! This method transforms the contained value of the [`Ok`] variant:
311 //! * [`map`] transforms [`Result<T, E>`] into [`Result<U, E>`] by applying
312 //! the provided function to the contained value of [`Ok`] and leaving
313 //! [`Err`] values unchanged
315 //! [`map`]: Result::map
317 //! This method transforms the contained value of the [`Err`] variant:
319 //! * [`map_err`] transforms [`Result<T, E>`] into [`Result<T, F>`] by
320 //! applying the provided function to the contained value of [`Err`] and
321 //! leaving [`Ok`] values unchanged
323 //! [`map_err`]: Result::map_err
325 //! These methods transform a [`Result<T, E>`] into a value of a possibly
326 //! different type `U`:
328 //! * [`map_or`] applies the provided function to the contained value of
329 //! [`Ok`], or returns the provided default value if the [`Result`] is
331 //! * [`map_or_else`] applies the provided function to the contained value
332 //! of [`Ok`], or applies the provided default fallback function to the
333 //! contained value of [`Err`]
335 //! [`map_or`]: Result::map_or
336 //! [`map_or_else`]: Result::map_or_else
338 //! ## Boolean operators
340 //! These methods treat the [`Result`] as a boolean value, where [`Ok`]
341 //! acts like [`true`] and [`Err`] acts like [`false`]. There are two
342 //! categories of these methods: ones that take a [`Result`] as input, and
343 //! ones that take a function as input (to be lazily evaluated).
345 //! The [`and`] and [`or`] methods take another [`Result`] as input, and
346 //! produce a [`Result`] as output. The [`and`] method can produce a
347 //! [`Result<U, E>`] value having a different inner type `U` than
348 //! [`Result<T, E>`]. The [`or`] method can produce a [`Result<T, F>`]
349 //! value having a different error type `F` than [`Result<T, E>`].
351 //! | method | self | input | output |
352 //! |---------|----------|-----------|----------|
353 //! | [`and`] | `Err(e)` | (ignored) | `Err(e)` |
354 //! | [`and`] | `Ok(x)` | `Err(d)` | `Err(d)` |
355 //! | [`and`] | `Ok(x)` | `Ok(y)` | `Ok(y)` |
356 //! | [`or`] | `Err(e)` | `Err(d)` | `Err(d)` |
357 //! | [`or`] | `Err(e)` | `Ok(y)` | `Ok(y)` |
358 //! | [`or`] | `Ok(x)` | (ignored) | `Ok(x)` |
360 //! [`and`]: Result::and
361 //! [`or`]: Result::or
363 //! The [`and_then`] and [`or_else`] methods take a function as input, and
364 //! only evaluate the function when they need to produce a new value. The
365 //! [`and_then`] method can produce a [`Result<U, E>`] value having a
366 //! different inner type `U` than [`Result<T, E>`]. The [`or_else`] method
367 //! can produce a [`Result<T, F>`] value having a different error type `F`
368 //! than [`Result<T, E>`].
370 //! | method | self | function input | function result | output |
371 //! |--------------|----------|----------------|-----------------|----------|
372 //! | [`and_then`] | `Err(e)` | (not provided) | (not evaluated) | `Err(e)` |
373 //! | [`and_then`] | `Ok(x)` | `x` | `Err(d)` | `Err(d)` |
374 //! | [`and_then`] | `Ok(x)` | `x` | `Ok(y)` | `Ok(y)` |
375 //! | [`or_else`] | `Err(e)` | `e` | `Err(d)` | `Err(d)` |
376 //! | [`or_else`] | `Err(e)` | `e` | `Ok(y)` | `Ok(y)` |
377 //! | [`or_else`] | `Ok(x)` | (not provided) | (not evaluated) | `Ok(x)` |
379 //! [`and_then`]: Result::and_then
380 //! [`or_else`]: Result::or_else
382 //! ## Comparison operators
384 //! If `T` and `E` both implement [`PartialOrd`] then [`Result<T, E>`] will
385 //! derive its [`PartialOrd`] implementation. With this order, an [`Ok`]
386 //! compares as less than any [`Err`], while two [`Ok`] or two [`Err`]
387 //! compare as their contained values would in `T` or `E` respectively. If `T`
388 //! and `E` both also implement [`Ord`], then so does [`Result<T, E>`].
391 //! assert!(Ok(1) < Err(0));
392 //! let x: Result<i32, ()> = Ok(0);
395 //! let x: Result<(), i32> = Err(0);
400 //! ## Iterating over `Result`
402 //! A [`Result`] can be iterated over. This can be helpful if you need an
403 //! iterator that is conditionally empty. The iterator will either produce
404 //! a single value (when the [`Result`] is [`Ok`]), or produce no values
405 //! (when the [`Result`] is [`Err`]). For example, [`into_iter`] acts like
406 //! [`once(v)`] if the [`Result`] is [`Ok(v)`], and like [`empty()`] if the
407 //! [`Result`] is [`Err`].
410 //! [`empty()`]: crate::iter::empty
411 //! [`once(v)`]: crate::iter::once
413 //! Iterators over [`Result<T, E>`] come in three types:
415 //! * [`into_iter`] consumes the [`Result`] and produces the contained
417 //! * [`iter`] produces an immutable reference of type `&T` to the
419 //! * [`iter_mut`] produces a mutable reference of type `&mut T` to the
422 //! See [Iterating over `Option`] for examples of how this can be useful.
424 //! [Iterating over `Option`]: crate::option#iterating-over-option
425 //! [`into_iter`]: Result::into_iter
426 //! [`iter`]: Result::iter
427 //! [`iter_mut`]: Result::iter_mut
429 //! You might want to use an iterator chain to do multiple instances of an
430 //! operation that can fail, but would like to ignore failures while
431 //! continuing to process the successful results. In this example, we take
432 //! advantage of the iterable nature of [`Result`] to select only the
433 //! [`Ok`] values using [`flatten`][Iterator::flatten].
436 //! # use std::str::FromStr;
437 //! let mut results = vec![];
438 //! let mut errs = vec![];
439 //! let nums: Vec<_> = ["17", "not a number", "99", "-27", "768"]
441 //! .map(u8::from_str)
442 //! // Save clones of the raw `Result` values to inspect
443 //! .inspect(|x| results.push(x.clone()))
444 //! // Challenge: explain how this captures only the `Err` values
445 //! .inspect(|x| errs.extend(x.clone().err()))
448 //! assert_eq!(errs.len(), 3);
449 //! assert_eq!(nums, [17, 99]);
450 //! println!("results {results:?}");
451 //! println!("errs {errs:?}");
452 //! println!("nums {nums:?}");
455 //! ## Collecting into `Result`
457 //! [`Result`] implements the [`FromIterator`][impl-FromIterator] trait,
458 //! which allows an iterator over [`Result`] values to be collected into a
459 //! [`Result`] of a collection of each contained value of the original
460 //! [`Result`] values, or [`Err`] if any of the elements was [`Err`].
462 //! [impl-FromIterator]: Result#impl-FromIterator%3CResult%3CA%2C%20E%3E%3E
465 //! let v = [Ok(2), Ok(4), Err("err!"), Ok(8)];
466 //! let res: Result<Vec<_>, &str> = v.into_iter().collect();
467 //! assert_eq!(res, Err("err!"));
468 //! let v = [Ok(2), Ok(4), Ok(8)];
469 //! let res: Result<Vec<_>, &str> = v.into_iter().collect();
470 //! assert_eq!(res, Ok(vec![2, 4, 8]));
473 //! [`Result`] also implements the [`Product`][impl-Product] and
474 //! [`Sum`][impl-Sum] traits, allowing an iterator over [`Result`] values
475 //! to provide the [`product`][Iterator::product] and
476 //! [`sum`][Iterator::sum] methods.
478 //! [impl-Product]: Result#impl-Product%3CResult%3CU%2C%20E%3E%3E
479 //! [impl-Sum]: Result#impl-Sum%3CResult%3CU%2C%20E%3E%3E
482 //! let v = [Err("error!"), Ok(1), Ok(2), Ok(3), Err("foo")];
483 //! let res: Result<i32, &str> = v.into_iter().sum();
484 //! assert_eq!(res, Err("error!"));
485 //! let v = [Ok(1), Ok(2), Ok(21)];
486 //! let res: Result<i32, &str> = v.into_iter().product();
487 //! assert_eq!(res, Ok(42));
490 #![stable(feature = "rust1", since = "1.0.0")]
492 use crate::iter::{self, FromIterator, FusedIterator, TrustedLen};
493 use crate::marker::Destruct;
494 use crate::ops::{self, ControlFlow, Deref, DerefMut};
495 use crate::{convert, fmt, hint};
497 /// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]).
499 /// See the [module documentation](self) for details.
500 #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
501 #[must_use = "this `Result` may be an `Err` variant, which should be handled"]
502 #[rustc_diagnostic_item = "Result"]
503 #[stable(feature = "rust1", since = "1.0.0")]
504 pub enum Result<T, E> {
505 /// Contains the success value
507 #[stable(feature = "rust1", since = "1.0.0")]
508 Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
510 /// Contains the error value
512 #[stable(feature = "rust1", since = "1.0.0")]
513 Err(#[stable(feature = "rust1", since = "1.0.0")] E),
516 /////////////////////////////////////////////////////////////////////////////
517 // Type implementation
518 /////////////////////////////////////////////////////////////////////////////
520 impl<T, E> Result<T, E> {
521 /////////////////////////////////////////////////////////////////////////
522 // Querying the contained values
523 /////////////////////////////////////////////////////////////////////////
525 /// Returns `true` if the result is [`Ok`].
532 /// let x: Result<i32, &str> = Ok(-3);
533 /// assert_eq!(x.is_ok(), true);
535 /// let x: Result<i32, &str> = Err("Some error message");
536 /// assert_eq!(x.is_ok(), false);
538 #[must_use = "if you intended to assert that this is ok, consider `.unwrap()` instead"]
539 #[rustc_const_stable(feature = "const_result_basics", since = "1.48.0")]
541 #[stable(feature = "rust1", since = "1.0.0")]
542 pub const fn is_ok(&self) -> bool {
543 matches!(*self, Ok(_))
546 /// Returns `true` if the result is [`Ok`] and the value inside of it matches a predicate.
551 /// #![feature(is_some_with)]
553 /// let x: Result<u32, &str> = Ok(2);
554 /// assert_eq!(x.is_ok_and(|&x| x > 1), true);
556 /// let x: Result<u32, &str> = Ok(0);
557 /// assert_eq!(x.is_ok_and(|&x| x > 1), false);
559 /// let x: Result<u32, &str> = Err("hey");
560 /// assert_eq!(x.is_ok_and(|&x| x > 1), false);
564 #[unstable(feature = "is_some_with", issue = "93050")]
565 pub fn is_ok_and(&self, f: impl FnOnce(&T) -> bool) -> bool {
566 matches!(self, Ok(x) if f(x))
569 /// Returns `true` if the result is [`Err`].
576 /// let x: Result<i32, &str> = Ok(-3);
577 /// assert_eq!(x.is_err(), false);
579 /// let x: Result<i32, &str> = Err("Some error message");
580 /// assert_eq!(x.is_err(), true);
582 #[must_use = "if you intended to assert that this is err, consider `.unwrap_err()` instead"]
583 #[rustc_const_stable(feature = "const_result_basics", since = "1.48.0")]
585 #[stable(feature = "rust1", since = "1.0.0")]
586 pub const fn is_err(&self) -> bool {
590 /// Returns `true` if the result is [`Err`] and the value inside of it matches a predicate.
595 /// #![feature(is_some_with)]
596 /// use std::io::{Error, ErrorKind};
598 /// let x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, "!"));
599 /// assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);
601 /// let x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, "!"));
602 /// assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
604 /// let x: Result<u32, Error> = Ok(123);
605 /// assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
609 #[unstable(feature = "is_some_with", issue = "93050")]
610 pub fn is_err_and(&self, f: impl FnOnce(&E) -> bool) -> bool {
611 matches!(self, Err(x) if f(x))
614 /////////////////////////////////////////////////////////////////////////
615 // Adapter for each variant
616 /////////////////////////////////////////////////////////////////////////
618 /// Converts from `Result<T, E>` to [`Option<T>`].
620 /// Converts `self` into an [`Option<T>`], consuming `self`,
621 /// and discarding the error, if any.
628 /// let x: Result<u32, &str> = Ok(2);
629 /// assert_eq!(x.ok(), Some(2));
631 /// let x: Result<u32, &str> = Err("Nothing here");
632 /// assert_eq!(x.ok(), None);
635 #[stable(feature = "rust1", since = "1.0.0")]
636 #[rustc_const_unstable(feature = "const_result_drop", issue = "92384")]
637 pub const fn ok(self) -> Option<T>
643 // FIXME: ~const Drop doesn't quite work right yet
644 #[allow(unused_variables)]
649 /// Converts from `Result<T, E>` to [`Option<E>`].
651 /// Converts `self` into an [`Option<E>`], consuming `self`,
652 /// and discarding the success value, if any.
659 /// let x: Result<u32, &str> = Ok(2);
660 /// assert_eq!(x.err(), None);
662 /// let x: Result<u32, &str> = Err("Nothing here");
663 /// assert_eq!(x.err(), Some("Nothing here"));
666 #[stable(feature = "rust1", since = "1.0.0")]
667 #[rustc_const_unstable(feature = "const_result_drop", issue = "92384")]
668 pub const fn err(self) -> Option<E>
673 // FIXME: ~const Drop doesn't quite work right yet
674 #[allow(unused_variables)]
680 /////////////////////////////////////////////////////////////////////////
681 // Adapter for working with references
682 /////////////////////////////////////////////////////////////////////////
684 /// Converts from `&Result<T, E>` to `Result<&T, &E>`.
686 /// Produces a new `Result`, containing a reference
687 /// into the original, leaving the original in place.
694 /// let x: Result<u32, &str> = Ok(2);
695 /// assert_eq!(x.as_ref(), Ok(&2));
697 /// let x: Result<u32, &str> = Err("Error");
698 /// assert_eq!(x.as_ref(), Err(&"Error"));
701 #[rustc_const_stable(feature = "const_result_basics", since = "1.48.0")]
702 #[stable(feature = "rust1", since = "1.0.0")]
703 pub const fn as_ref(&self) -> Result<&T, &E> {
706 Err(ref x) => Err(x),
710 /// Converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`.
717 /// fn mutate(r: &mut Result<i32, i32>) {
718 /// match r.as_mut() {
719 /// Ok(v) => *v = 42,
720 /// Err(e) => *e = 0,
724 /// let mut x: Result<i32, i32> = Ok(2);
726 /// assert_eq!(x.unwrap(), 42);
728 /// let mut x: Result<i32, i32> = Err(13);
730 /// assert_eq!(x.unwrap_err(), 0);
733 #[stable(feature = "rust1", since = "1.0.0")]
734 #[rustc_const_unstable(feature = "const_result", issue = "82814")]
735 pub const fn as_mut(&mut self) -> Result<&mut T, &mut E> {
737 Ok(ref mut x) => Ok(x),
738 Err(ref mut x) => Err(x),
742 /////////////////////////////////////////////////////////////////////////
743 // Transforming contained values
744 /////////////////////////////////////////////////////////////////////////
746 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
747 /// contained [`Ok`] value, leaving an [`Err`] value untouched.
749 /// This function can be used to compose the results of two functions.
753 /// Print the numbers on each line of a string multiplied by two.
756 /// let line = "1\n2\n3\n4\n";
758 /// for num in line.lines() {
759 /// match num.parse::<i32>().map(|i| i * 2) {
760 /// Ok(n) => println!("{n}"),
766 #[stable(feature = "rust1", since = "1.0.0")]
767 pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U, E> {
774 /// Returns the provided default (if [`Err`]), or
775 /// applies a function to the contained value (if [`Ok`]),
777 /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
778 /// the result of a function call, it is recommended to use [`map_or_else`],
779 /// which is lazily evaluated.
781 /// [`map_or_else`]: Result::map_or_else
786 /// let x: Result<_, &str> = Ok("foo");
787 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
789 /// let x: Result<&str, _> = Err("bar");
790 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
793 #[stable(feature = "result_map_or", since = "1.41.0")]
794 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
801 /// Maps a `Result<T, E>` to `U` by applying fallback function `default` to
802 /// a contained [`Err`] value, or function `f` to a contained [`Ok`] value.
804 /// This function can be used to unpack a successful result
805 /// while handling an error.
815 /// let x : Result<_, &str> = Ok("foo");
816 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);
818 /// let x : Result<&str, _> = Err("bar");
819 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
822 #[stable(feature = "result_map_or_else", since = "1.41.0")]
823 pub fn map_or_else<U, D: FnOnce(E) -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
826 Err(e) => default(e),
830 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
831 /// contained [`Err`] value, leaving an [`Ok`] value untouched.
833 /// This function can be used to pass through a successful result while handling
842 /// fn stringify(x: u32) -> String { format!("error code: {x}") }
844 /// let x: Result<u32, u32> = Ok(2);
845 /// assert_eq!(x.map_err(stringify), Ok(2));
847 /// let x: Result<u32, u32> = Err(13);
848 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
851 #[stable(feature = "rust1", since = "1.0.0")]
852 pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T, F> {
855 Err(e) => Err(op(e)),
859 /// Calls the provided closure with a reference to the contained value (if [`Ok`]).
864 /// #![feature(result_option_inspect)]
868 /// .inspect(|x| println!("original: {x}"))
869 /// .map(|x| x.pow(3))
870 /// .expect("failed to parse number");
873 #[unstable(feature = "result_option_inspect", issue = "91345")]
874 pub fn inspect<F: FnOnce(&T)>(self, f: F) -> Self {
875 if let Ok(ref t) = self {
882 /// Calls the provided closure with a reference to the contained error (if [`Err`]).
887 /// #![feature(result_option_inspect)]
889 /// use std::{fs, io};
891 /// fn read() -> io::Result<String> {
892 /// fs::read_to_string("address.txt")
893 /// .inspect_err(|e| eprintln!("failed to read file: {e}"))
897 #[unstable(feature = "result_option_inspect", issue = "91345")]
898 pub fn inspect_err<F: FnOnce(&E)>(self, f: F) -> Self {
899 if let Err(ref e) = self {
906 /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&<T as Deref>::Target, &E>`.
908 /// Coerces the [`Ok`] variant of the original [`Result`] via [`Deref`](crate::ops::Deref)
909 /// and returns the new [`Result`].
914 /// let x: Result<String, u32> = Ok("hello".to_string());
915 /// let y: Result<&str, &u32> = Ok("hello");
916 /// assert_eq!(x.as_deref(), y);
918 /// let x: Result<String, u32> = Err(42);
919 /// let y: Result<&str, &u32> = Err(&42);
920 /// assert_eq!(x.as_deref(), y);
922 #[stable(feature = "inner_deref", since = "1.47.0")]
923 pub fn as_deref(&self) -> Result<&T::Target, &E>
927 self.as_ref().map(|t| t.deref())
930 /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut <T as DerefMut>::Target, &mut E>`.
932 /// Coerces the [`Ok`] variant of the original [`Result`] via [`DerefMut`](crate::ops::DerefMut)
933 /// and returns the new [`Result`].
938 /// let mut s = "HELLO".to_string();
939 /// let mut x: Result<String, u32> = Ok("hello".to_string());
940 /// let y: Result<&mut str, &mut u32> = Ok(&mut s);
941 /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
944 /// let mut x: Result<String, u32> = Err(42);
945 /// let y: Result<&mut str, &mut u32> = Err(&mut i);
946 /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
948 #[stable(feature = "inner_deref", since = "1.47.0")]
949 pub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E>
953 self.as_mut().map(|t| t.deref_mut())
956 /////////////////////////////////////////////////////////////////////////
957 // Iterator constructors
958 /////////////////////////////////////////////////////////////////////////
960 /// Returns an iterator over the possibly contained value.
962 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
969 /// let x: Result<u32, &str> = Ok(7);
970 /// assert_eq!(x.iter().next(), Some(&7));
972 /// let x: Result<u32, &str> = Err("nothing!");
973 /// assert_eq!(x.iter().next(), None);
976 #[stable(feature = "rust1", since = "1.0.0")]
977 pub fn iter(&self) -> Iter<'_, T> {
978 Iter { inner: self.as_ref().ok() }
981 /// Returns a mutable iterator over the possibly contained value.
983 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
990 /// let mut x: Result<u32, &str> = Ok(7);
991 /// match x.iter_mut().next() {
992 /// Some(v) => *v = 40,
995 /// assert_eq!(x, Ok(40));
997 /// let mut x: Result<u32, &str> = Err("nothing!");
998 /// assert_eq!(x.iter_mut().next(), None);
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1003 IterMut { inner: self.as_mut().ok() }
1006 /////////////////////////////////////////////////////////////////////////
1008 /////////////////////////////////////////////////////////////////////////
1010 /// Returns the contained [`Ok`] value, consuming the `self` value.
1014 /// Panics if the value is an [`Err`], with a panic message including the
1015 /// passed message, and the content of the [`Err`].
1023 /// let x: Result<u32, &str> = Err("emergency failure");
1024 /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
1027 /// # Common Message Styles
1029 /// There are two common styles for how people word `expect` messages. Using the message to
1030 /// present information to users encountering a panic ("expect as error message") or using the
1031 /// message to present information to developers debugging the panic ("expect as
1034 /// In the former case the expect message is used to describe the error that has occurred which
1035 /// is considered a bug. Consider the following example:
1038 /// // Read environment variable, panic if it is not present
1039 /// let path = std::env::var("IMPORTANT_PATH").unwrap();
1042 /// In the "expect as error message" style we would use expect to describe that the environment
1043 /// variable was not set when it should have been:
1046 /// let path = std::env::var("IMPORTANT_PATH")
1047 /// .expect("env variable `IMPORTANT_PATH` is not set");
1050 /// In the latter style, we would instead describe the reason we _expect_ the `Result` will
1051 /// always be `Ok`. With this style we would instead write:
1054 /// let path = std::env::var("IMPORTANT_PATH")
1055 /// .expect("env variable `IMPORTANT_PATH` is always be set by `wrapper_script.sh`");
1058 /// The "expect as error message" style has the advantage of giving a more user friendly error
1059 /// message, and is more consistent with the default output of the [panic hook] provided by
1063 /// thread 'expect_as_error_message' panicked at 'env variable `IMPORTANT_PATH` is not set: NotPresent', src/lib.rs:4:10
1066 /// The "expect as precondition" style instead focuses on source code readability, making it
1067 /// easier to understand what must have gone wrong in situations where panics are being used to
1068 /// represent bugs exclusively. But this extra information often looks confusing when presented
1069 /// directly to users with the default `std` panic hook's report format:
1072 /// thread 'expect_as_precondition' panicked at 'env variable `IMPORTANT_PATH` is always set by `wrapper_script.sh`: NotPresent', src/lib.rs:4:10
1075 /// This style works best when paired with a custom [panic hook] like the one provided by the
1076 /// CLI working group library, [`human-panic`], which redirects panic messages to crash report
1077 /// files while showing users a more "Oops, something went wrong!" message with a suggestion to
1078 /// send the crash report file back to the developers.
1080 /// [panic hook]: https://doc.rust-lang.org/stable/std/panic/fn.set_hook.html
1081 /// [`human-panic`]: https://docs.rs/human-panic
1084 #[stable(feature = "result_expect", since = "1.4.0")]
1085 pub fn expect(self, msg: &str) -> T
1091 Err(e) => unwrap_failed(msg, &e),
1095 /// Returns the contained [`Ok`] value, consuming the `self` value.
1097 /// Because this function may panic, its use is generally discouraged.
1098 /// Instead, prefer to use pattern matching and handle the [`Err`]
1099 /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
1100 /// [`unwrap_or_default`].
1102 /// [`unwrap_or`]: Result::unwrap_or
1103 /// [`unwrap_or_else`]: Result::unwrap_or_else
1104 /// [`unwrap_or_default`]: Result::unwrap_or_default
1108 /// Panics if the value is an [`Err`], with a panic message provided by the
1109 /// [`Err`]'s value.
1117 /// let x: Result<u32, &str> = Ok(2);
1118 /// assert_eq!(x.unwrap(), 2);
1122 /// let x: Result<u32, &str> = Err("emergency failure");
1123 /// x.unwrap(); // panics with `emergency failure`
1127 #[stable(feature = "rust1", since = "1.0.0")]
1128 pub fn unwrap(self) -> T
1134 Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e),
1138 /// Returns the contained [`Ok`] value or a default
1140 /// Consumes the `self` argument then, if [`Ok`], returns the contained
1141 /// value, otherwise if [`Err`], returns the default value for that
1146 /// Converts a string to an integer, turning poorly-formed strings
1147 /// into 0 (the default value for integers). [`parse`] converts
1148 /// a string to any other type that implements [`FromStr`], returning an
1149 /// [`Err`] on error.
1152 /// let good_year_from_input = "1909";
1153 /// let bad_year_from_input = "190blarg";
1154 /// let good_year = good_year_from_input.parse().unwrap_or_default();
1155 /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
1157 /// assert_eq!(1909, good_year);
1158 /// assert_eq!(0, bad_year);
1161 /// [`parse`]: str::parse
1162 /// [`FromStr`]: crate::str::FromStr
1164 #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
1165 pub fn unwrap_or_default(self) -> T
1171 Err(_) => Default::default(),
1175 /// Returns the contained [`Err`] value, consuming the `self` value.
1179 /// Panics if the value is an [`Ok`], with a panic message including the
1180 /// passed message, and the content of the [`Ok`].
1188 /// let x: Result<u32, &str> = Ok(10);
1189 /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
1193 #[stable(feature = "result_expect_err", since = "1.17.0")]
1194 pub fn expect_err(self, msg: &str) -> E
1199 Ok(t) => unwrap_failed(msg, &t),
1204 /// Returns the contained [`Err`] value, consuming the `self` value.
1208 /// Panics if the value is an [`Ok`], with a custom panic message provided
1209 /// by the [`Ok`]'s value.
1214 /// let x: Result<u32, &str> = Ok(2);
1215 /// x.unwrap_err(); // panics with `2`
1219 /// let x: Result<u32, &str> = Err("emergency failure");
1220 /// assert_eq!(x.unwrap_err(), "emergency failure");
1224 #[stable(feature = "rust1", since = "1.0.0")]
1225 pub fn unwrap_err(self) -> E
1230 Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t),
1235 /// Returns the contained [`Ok`] value, but never panics.
1237 /// Unlike [`unwrap`], this method is known to never panic on the
1238 /// result types it is implemented for. Therefore, it can be used
1239 /// instead of `unwrap` as a maintainability safeguard that will fail
1240 /// to compile if the error type of the `Result` is later changed
1241 /// to an error that can actually occur.
1243 /// [`unwrap`]: Result::unwrap
1250 /// # #![feature(never_type)]
1251 /// # #![feature(unwrap_infallible)]
1253 /// fn only_good_news() -> Result<String, !> {
1254 /// Ok("this is fine".into())
1257 /// let s: String = only_good_news().into_ok();
1258 /// println!("{s}");
1260 #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
1262 pub fn into_ok(self) -> T
1272 /// Returns the contained [`Err`] value, but never panics.
1274 /// Unlike [`unwrap_err`], this method is known to never panic on the
1275 /// result types it is implemented for. Therefore, it can be used
1276 /// instead of `unwrap_err` as a maintainability safeguard that will fail
1277 /// to compile if the ok type of the `Result` is later changed
1278 /// to a type that can actually occur.
1280 /// [`unwrap_err`]: Result::unwrap_err
1287 /// # #![feature(never_type)]
1288 /// # #![feature(unwrap_infallible)]
1290 /// fn only_bad_news() -> Result<!, String> {
1291 /// Err("Oops, it failed".into())
1294 /// let error: String = only_bad_news().into_err();
1295 /// println!("{error}");
1297 #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
1299 pub fn into_err(self) -> E
1309 ////////////////////////////////////////////////////////////////////////
1310 // Boolean operations on the values, eager and lazy
1311 /////////////////////////////////////////////////////////////////////////
1313 /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
1321 /// let x: Result<u32, &str> = Ok(2);
1322 /// let y: Result<&str, &str> = Err("late error");
1323 /// assert_eq!(x.and(y), Err("late error"));
1325 /// let x: Result<u32, &str> = Err("early error");
1326 /// let y: Result<&str, &str> = Ok("foo");
1327 /// assert_eq!(x.and(y), Err("early error"));
1329 /// let x: Result<u32, &str> = Err("not a 2");
1330 /// let y: Result<&str, &str> = Err("late error");
1331 /// assert_eq!(x.and(y), Err("not a 2"));
1333 /// let x: Result<u32, &str> = Ok(2);
1334 /// let y: Result<&str, &str> = Ok("different result type");
1335 /// assert_eq!(x.and(y), Ok("different result type"));
1338 #[rustc_const_unstable(feature = "const_result_drop", issue = "92384")]
1339 #[stable(feature = "rust1", since = "1.0.0")]
1340 pub const fn and<U>(self, res: Result<U, E>) -> Result<U, E>
1347 // FIXME: ~const Drop doesn't quite work right yet
1348 #[allow(unused_variables)]
1354 /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
1357 /// This function can be used for control flow based on `Result` values.
1362 /// fn sq_then_to_string(x: u32) -> Result<String, &'static str> {
1363 /// x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed")
1366 /// assert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));
1367 /// assert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err("overflowed"));
1368 /// assert_eq!(Err("not a number").and_then(sq_then_to_string), Err("not a number"));
1371 /// Often used to chain fallible operations that may return [`Err`].
1374 /// use std::{io::ErrorKind, path::Path};
1376 /// // Note: on Windows "/" maps to "C:\"
1377 /// let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified());
1378 /// assert!(root_modified_time.is_ok());
1380 /// let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified());
1381 /// assert!(should_fail.is_err());
1382 /// assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
1385 #[stable(feature = "rust1", since = "1.0.0")]
1386 pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
1393 /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
1395 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
1396 /// result of a function call, it is recommended to use [`or_else`], which is
1397 /// lazily evaluated.
1399 /// [`or_else`]: Result::or_else
1406 /// let x: Result<u32, &str> = Ok(2);
1407 /// let y: Result<u32, &str> = Err("late error");
1408 /// assert_eq!(x.or(y), Ok(2));
1410 /// let x: Result<u32, &str> = Err("early error");
1411 /// let y: Result<u32, &str> = Ok(2);
1412 /// assert_eq!(x.or(y), Ok(2));
1414 /// let x: Result<u32, &str> = Err("not a 2");
1415 /// let y: Result<u32, &str> = Err("late error");
1416 /// assert_eq!(x.or(y), Err("late error"));
1418 /// let x: Result<u32, &str> = Ok(2);
1419 /// let y: Result<u32, &str> = Ok(100);
1420 /// assert_eq!(x.or(y), Ok(2));
1423 #[rustc_const_unstable(feature = "const_result_drop", issue = "92384")]
1424 #[stable(feature = "rust1", since = "1.0.0")]
1425 pub const fn or<F>(self, res: Result<T, F>) -> Result<T, F>
1433 // FIXME: ~const Drop doesn't quite work right yet
1434 #[allow(unused_variables)]
1439 /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
1441 /// This function can be used for control flow based on result values.
1449 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
1450 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
1452 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
1453 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
1454 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
1455 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
1458 #[stable(feature = "rust1", since = "1.0.0")]
1459 pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
1466 /// Returns the contained [`Ok`] value or a provided default.
1468 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
1469 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
1470 /// which is lazily evaluated.
1472 /// [`unwrap_or_else`]: Result::unwrap_or_else
1479 /// let default = 2;
1480 /// let x: Result<u32, &str> = Ok(9);
1481 /// assert_eq!(x.unwrap_or(default), 9);
1483 /// let x: Result<u32, &str> = Err("error");
1484 /// assert_eq!(x.unwrap_or(default), default);
1487 #[rustc_const_unstable(feature = "const_result_drop", issue = "92384")]
1488 #[stable(feature = "rust1", since = "1.0.0")]
1489 pub const fn unwrap_or(self, default: T) -> T
1496 // FIXME: ~const Drop doesn't quite work right yet
1497 #[allow(unused_variables)]
1502 /// Returns the contained [`Ok`] value or computes it from a closure.
1510 /// fn count(x: &str) -> usize { x.len() }
1512 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
1513 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
1516 #[stable(feature = "rust1", since = "1.0.0")]
1517 pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
1524 /// Returns the contained [`Ok`] value, consuming the `self` value,
1525 /// without checking that the value is not an [`Err`].
1529 /// Calling this method on an [`Err`] is *[undefined behavior]*.
1531 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1536 /// let x: Result<u32, &str> = Ok(2);
1537 /// assert_eq!(unsafe { x.unwrap_unchecked() }, 2);
1541 /// let x: Result<u32, &str> = Err("emergency failure");
1542 /// unsafe { x.unwrap_unchecked(); } // Undefined behavior!
1546 #[stable(feature = "option_result_unwrap_unchecked", since = "1.58.0")]
1547 pub unsafe fn unwrap_unchecked(self) -> T {
1548 debug_assert!(self.is_ok());
1551 // SAFETY: the safety contract must be upheld by the caller.
1552 Err(_) => unsafe { hint::unreachable_unchecked() },
1556 /// Returns the contained [`Err`] value, consuming the `self` value,
1557 /// without checking that the value is not an [`Ok`].
1561 /// Calling this method on an [`Ok`] is *[undefined behavior]*.
1563 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1568 /// let x: Result<u32, &str> = Ok(2);
1569 /// unsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
1573 /// let x: Result<u32, &str> = Err("emergency failure");
1574 /// assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure");
1578 #[stable(feature = "option_result_unwrap_unchecked", since = "1.58.0")]
1579 pub unsafe fn unwrap_err_unchecked(self) -> E {
1580 debug_assert!(self.is_err());
1582 // SAFETY: the safety contract must be upheld by the caller.
1583 Ok(_) => unsafe { hint::unreachable_unchecked() },
1588 /////////////////////////////////////////////////////////////////////////
1590 /////////////////////////////////////////////////////////////////////////
1592 /// Returns `true` if the result is an [`Ok`] value containing the given value.
1597 /// #![feature(option_result_contains)]
1599 /// let x: Result<u32, &str> = Ok(2);
1600 /// assert_eq!(x.contains(&2), true);
1602 /// let x: Result<u32, &str> = Ok(3);
1603 /// assert_eq!(x.contains(&2), false);
1605 /// let x: Result<u32, &str> = Err("Some error message");
1606 /// assert_eq!(x.contains(&2), false);
1610 #[unstable(feature = "option_result_contains", issue = "62358")]
1611 pub fn contains<U>(&self, x: &U) -> bool
1621 /// Returns `true` if the result is an [`Err`] value containing the given value.
1626 /// #![feature(result_contains_err)]
1628 /// let x: Result<u32, &str> = Ok(2);
1629 /// assert_eq!(x.contains_err(&"Some error message"), false);
1631 /// let x: Result<u32, &str> = Err("Some error message");
1632 /// assert_eq!(x.contains_err(&"Some error message"), true);
1634 /// let x: Result<u32, &str> = Err("Some other error message");
1635 /// assert_eq!(x.contains_err(&"Some error message"), false);
1639 #[unstable(feature = "result_contains_err", issue = "62358")]
1640 pub fn contains_err<F>(&self, f: &F) -> bool
1651 impl<T, E> Result<&T, E> {
1652 /// Maps a `Result<&T, E>` to a `Result<T, E>` by copying the contents of the
1659 /// let x: Result<&i32, i32> = Ok(&val);
1660 /// assert_eq!(x, Ok(&12));
1661 /// let copied = x.copied();
1662 /// assert_eq!(copied, Ok(12));
1665 #[stable(feature = "result_copied", since = "1.59.0")]
1666 pub fn copied(self) -> Result<T, E>
1673 /// Maps a `Result<&T, E>` to a `Result<T, E>` by cloning the contents of the
1680 /// let x: Result<&i32, i32> = Ok(&val);
1681 /// assert_eq!(x, Ok(&12));
1682 /// let cloned = x.cloned();
1683 /// assert_eq!(cloned, Ok(12));
1686 #[stable(feature = "result_cloned", since = "1.59.0")]
1687 pub fn cloned(self) -> Result<T, E>
1691 self.map(|t| t.clone())
1695 impl<T, E> Result<&mut T, E> {
1696 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by copying the contents of the
1702 /// let mut val = 12;
1703 /// let x: Result<&mut i32, i32> = Ok(&mut val);
1704 /// assert_eq!(x, Ok(&mut 12));
1705 /// let copied = x.copied();
1706 /// assert_eq!(copied, Ok(12));
1709 #[stable(feature = "result_copied", since = "1.59.0")]
1710 pub fn copied(self) -> Result<T, E>
1714 self.map(|&mut t| t)
1717 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by cloning the contents of the
1723 /// let mut val = 12;
1724 /// let x: Result<&mut i32, i32> = Ok(&mut val);
1725 /// assert_eq!(x, Ok(&mut 12));
1726 /// let cloned = x.cloned();
1727 /// assert_eq!(cloned, Ok(12));
1730 #[stable(feature = "result_cloned", since = "1.59.0")]
1731 pub fn cloned(self) -> Result<T, E>
1735 self.map(|t| t.clone())
1739 impl<T, E> Result<Option<T>, E> {
1740 /// Transposes a `Result` of an `Option` into an `Option` of a `Result`.
1742 /// `Ok(None)` will be mapped to `None`.
1743 /// `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`.
1748 /// #[derive(Debug, Eq, PartialEq)]
1751 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1752 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1753 /// assert_eq!(x.transpose(), y);
1756 #[stable(feature = "transpose_result", since = "1.33.0")]
1757 #[rustc_const_unstable(feature = "const_result", issue = "82814")]
1758 pub const fn transpose(self) -> Option<Result<T, E>> {
1760 Ok(Some(x)) => Some(Ok(x)),
1762 Err(e) => Some(Err(e)),
1767 impl<T, E> Result<Result<T, E>, E> {
1768 /// Converts from `Result<Result<T, E>, E>` to `Result<T, E>`
1775 /// #![feature(result_flattening)]
1776 /// let x: Result<Result<&'static str, u32>, u32> = Ok(Ok("hello"));
1777 /// assert_eq!(Ok("hello"), x.flatten());
1779 /// let x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));
1780 /// assert_eq!(Err(6), x.flatten());
1782 /// let x: Result<Result<&'static str, u32>, u32> = Err(6);
1783 /// assert_eq!(Err(6), x.flatten());
1786 /// Flattening only removes one level of nesting at a time:
1789 /// #![feature(result_flattening)]
1790 /// let x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok("hello")));
1791 /// assert_eq!(Ok(Ok("hello")), x.flatten());
1792 /// assert_eq!(Ok("hello"), x.flatten().flatten());
1795 #[unstable(feature = "result_flattening", issue = "70142")]
1796 pub fn flatten(self) -> Result<T, E> {
1797 self.and_then(convert::identity)
1801 impl<T> Result<T, T> {
1802 /// Returns the [`Ok`] value if `self` is `Ok`, and the [`Err`] value if
1803 /// `self` is `Err`.
1805 /// In other words, this function returns the value (the `T`) of a
1806 /// `Result<T, T>`, regardless of whether or not that result is `Ok` or
1809 /// This can be useful in conjunction with APIs such as
1810 /// [`Atomic*::compare_exchange`], or [`slice::binary_search`], but only in
1811 /// cases where you don't care if the result was `Ok` or not.
1813 /// [`Atomic*::compare_exchange`]: crate::sync::atomic::AtomicBool::compare_exchange
1818 /// #![feature(result_into_ok_or_err)]
1819 /// let ok: Result<u32, u32> = Ok(3);
1820 /// let err: Result<u32, u32> = Err(4);
1822 /// assert_eq!(ok.into_ok_or_err(), 3);
1823 /// assert_eq!(err.into_ok_or_err(), 4);
1826 #[unstable(feature = "result_into_ok_or_err", reason = "newly added", issue = "82223")]
1827 pub const fn into_ok_or_err(self) -> T {
1835 // This is a separate function to reduce the code size of the methods
1836 #[cfg(not(feature = "panic_immediate_abort"))]
1840 fn unwrap_failed(msg: &str, error: &dyn fmt::Debug) -> ! {
1841 panic!("{msg}: {error:?}")
1844 // This is a separate function to avoid constructing a `dyn Debug`
1845 // that gets immediately thrown away, since vtables don't get cleaned up
1846 // by dead code elimination if a trait object is constructed even if it goes
1848 #[cfg(feature = "panic_immediate_abort")]
1852 fn unwrap_failed<T>(_msg: &str, _error: &T) -> ! {
1856 /////////////////////////////////////////////////////////////////////////////
1857 // Trait implementations
1858 /////////////////////////////////////////////////////////////////////////////
1860 #[stable(feature = "rust1", since = "1.0.0")]
1861 #[rustc_const_unstable(feature = "const_clone", issue = "91805")]
1862 impl<T, E> const Clone for Result<T, E>
1864 T: ~const Clone + ~const Destruct,
1865 E: ~const Clone + ~const Destruct,
1868 fn clone(&self) -> Self {
1870 Ok(x) => Ok(x.clone()),
1871 Err(x) => Err(x.clone()),
1876 fn clone_from(&mut self, source: &Self) {
1877 match (self, source) {
1878 (Ok(to), Ok(from)) => to.clone_from(from),
1879 (Err(to), Err(from)) => to.clone_from(from),
1880 (to, from) => *to = from.clone(),
1885 #[stable(feature = "rust1", since = "1.0.0")]
1886 impl<T, E> IntoIterator for Result<T, E> {
1888 type IntoIter = IntoIter<T>;
1890 /// Returns a consuming iterator over the possibly contained value.
1892 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
1899 /// let x: Result<u32, &str> = Ok(5);
1900 /// let v: Vec<u32> = x.into_iter().collect();
1901 /// assert_eq!(v, [5]);
1903 /// let x: Result<u32, &str> = Err("nothing!");
1904 /// let v: Vec<u32> = x.into_iter().collect();
1905 /// assert_eq!(v, []);
1908 fn into_iter(self) -> IntoIter<T> {
1909 IntoIter { inner: self.ok() }
1913 #[stable(since = "1.4.0", feature = "result_iter")]
1914 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
1916 type IntoIter = Iter<'a, T>;
1918 fn into_iter(self) -> Iter<'a, T> {
1923 #[stable(since = "1.4.0", feature = "result_iter")]
1924 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
1925 type Item = &'a mut T;
1926 type IntoIter = IterMut<'a, T>;
1928 fn into_iter(self) -> IterMut<'a, T> {
1933 /////////////////////////////////////////////////////////////////////////////
1934 // The Result Iterators
1935 /////////////////////////////////////////////////////////////////////////////
1937 /// An iterator over a reference to the [`Ok`] variant of a [`Result`].
1939 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1941 /// Created by [`Result::iter`].
1943 #[stable(feature = "rust1", since = "1.0.0")]
1944 pub struct Iter<'a, T: 'a> {
1945 inner: Option<&'a T>,
1948 #[stable(feature = "rust1", since = "1.0.0")]
1949 impl<'a, T> Iterator for Iter<'a, T> {
1953 fn next(&mut self) -> Option<&'a T> {
1957 fn size_hint(&self) -> (usize, Option<usize>) {
1958 let n = if self.inner.is_some() { 1 } else { 0 };
1963 #[stable(feature = "rust1", since = "1.0.0")]
1964 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1966 fn next_back(&mut self) -> Option<&'a T> {
1971 #[stable(feature = "rust1", since = "1.0.0")]
1972 impl<T> ExactSizeIterator for Iter<'_, T> {}
1974 #[stable(feature = "fused", since = "1.26.0")]
1975 impl<T> FusedIterator for Iter<'_, T> {}
1977 #[unstable(feature = "trusted_len", issue = "37572")]
1978 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1980 #[stable(feature = "rust1", since = "1.0.0")]
1981 impl<T> Clone for Iter<'_, T> {
1983 fn clone(&self) -> Self {
1984 Iter { inner: self.inner }
1988 /// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
1990 /// Created by [`Result::iter_mut`].
1992 #[stable(feature = "rust1", since = "1.0.0")]
1993 pub struct IterMut<'a, T: 'a> {
1994 inner: Option<&'a mut T>,
1997 #[stable(feature = "rust1", since = "1.0.0")]
1998 impl<'a, T> Iterator for IterMut<'a, T> {
1999 type Item = &'a mut T;
2002 fn next(&mut self) -> Option<&'a mut T> {
2006 fn size_hint(&self) -> (usize, Option<usize>) {
2007 let n = if self.inner.is_some() { 1 } else { 0 };
2012 #[stable(feature = "rust1", since = "1.0.0")]
2013 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
2015 fn next_back(&mut self) -> Option<&'a mut T> {
2020 #[stable(feature = "rust1", since = "1.0.0")]
2021 impl<T> ExactSizeIterator for IterMut<'_, T> {}
2023 #[stable(feature = "fused", since = "1.26.0")]
2024 impl<T> FusedIterator for IterMut<'_, T> {}
2026 #[unstable(feature = "trusted_len", issue = "37572")]
2027 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
2029 /// An iterator over the value in a [`Ok`] variant of a [`Result`].
2031 /// The iterator yields one value if the result is [`Ok`], otherwise none.
2033 /// This struct is created by the [`into_iter`] method on
2034 /// [`Result`] (provided by the [`IntoIterator`] trait).
2036 /// [`into_iter`]: IntoIterator::into_iter
2037 #[derive(Clone, Debug)]
2038 #[stable(feature = "rust1", since = "1.0.0")]
2039 pub struct IntoIter<T> {
2043 #[stable(feature = "rust1", since = "1.0.0")]
2044 impl<T> Iterator for IntoIter<T> {
2048 fn next(&mut self) -> Option<T> {
2052 fn size_hint(&self) -> (usize, Option<usize>) {
2053 let n = if self.inner.is_some() { 1 } else { 0 };
2058 #[stable(feature = "rust1", since = "1.0.0")]
2059 impl<T> DoubleEndedIterator for IntoIter<T> {
2061 fn next_back(&mut self) -> Option<T> {
2066 #[stable(feature = "rust1", since = "1.0.0")]
2067 impl<T> ExactSizeIterator for IntoIter<T> {}
2069 #[stable(feature = "fused", since = "1.26.0")]
2070 impl<T> FusedIterator for IntoIter<T> {}
2072 #[unstable(feature = "trusted_len", issue = "37572")]
2073 unsafe impl<A> TrustedLen for IntoIter<A> {}
2075 /////////////////////////////////////////////////////////////////////////////
2077 /////////////////////////////////////////////////////////////////////////////
2079 #[stable(feature = "rust1", since = "1.0.0")]
2080 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
2081 /// Takes each element in the `Iterator`: if it is an `Err`, no further
2082 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
2083 /// container with the values of each `Result` is returned.
2085 /// Here is an example which increments every integer in a vector,
2086 /// checking for overflow:
2089 /// let v = vec![1, 2];
2090 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
2091 /// x.checked_add(1).ok_or("Overflow!")
2093 /// assert_eq!(res, Ok(vec![2, 3]));
2096 /// Here is another example that tries to subtract one from another list
2097 /// of integers, this time checking for underflow:
2100 /// let v = vec![1, 2, 0];
2101 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
2102 /// x.checked_sub(1).ok_or("Underflow!")
2104 /// assert_eq!(res, Err("Underflow!"));
2107 /// Here is a variation on the previous example, showing that no
2108 /// further elements are taken from `iter` after the first `Err`.
2111 /// let v = vec![3, 2, 1, 10];
2112 /// let mut shared = 0;
2113 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {
2115 /// x.checked_sub(2).ok_or("Underflow!")
2117 /// assert_eq!(res, Err("Underflow!"));
2118 /// assert_eq!(shared, 6);
2121 /// Since the third element caused an underflow, no further elements were taken,
2122 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
2124 fn from_iter<I: IntoIterator<Item = Result<A, E>>>(iter: I) -> Result<V, E> {
2125 // FIXME(#11084): This could be replaced with Iterator::scan when this
2126 // performance bug is closed.
2128 iter::try_process(iter.into_iter(), |i| i.collect())
2132 #[unstable(feature = "try_trait_v2", issue = "84277")]
2133 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
2134 impl<T, E> const ops::Try for Result<T, E> {
2136 type Residual = Result<convert::Infallible, E>;
2139 fn from_output(output: Self::Output) -> Self {
2144 fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
2146 Ok(v) => ControlFlow::Continue(v),
2147 Err(e) => ControlFlow::Break(Err(e)),
2152 #[unstable(feature = "try_trait_v2", issue = "84277")]
2153 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
2154 impl<T, E, F: ~const From<E>> const ops::FromResidual<Result<convert::Infallible, E>>
2159 fn from_residual(residual: Result<convert::Infallible, E>) -> Self {
2161 Err(e) => Err(From::from(e)),
2166 #[unstable(feature = "try_trait_v2_residual", issue = "91285")]
2167 impl<T, E> ops::Residual<T> for Result<convert::Infallible, E> {
2168 type TryType = Result<T, E>;