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 [`Result`]`<T, `[`io::Error`]`>`.*
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
221 //! [`write_all`]: ../../std/io/trait.Write.html#method.write_all
222 //! [`io::Result`]: ../../std/io/type.Result.html
223 //! [`?`]: crate::ops::Try
226 //! [`io::Error`]: ../../std/io/struct.Error.html
228 #![stable(feature = "rust1", since = "1.0.0")]
230 use crate::iter::{self, FromIterator, FusedIterator, TrustedLen};
231 use crate::ops::{self, Deref, DerefMut};
232 use crate::{convert, fmt};
234 /// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]).
236 /// See the [module documentation](self) for details.
237 #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
238 #[must_use = "this `Result` may be an `Err` variant, which should be handled"]
239 #[rustc_diagnostic_item = "result_type"]
240 #[stable(feature = "rust1", since = "1.0.0")]
241 pub enum Result<T, E> {
242 /// Contains the success value
244 #[stable(feature = "rust1", since = "1.0.0")]
245 Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
247 /// Contains the error value
249 #[stable(feature = "rust1", since = "1.0.0")]
250 Err(#[stable(feature = "rust1", since = "1.0.0")] E),
253 /////////////////////////////////////////////////////////////////////////////
254 // Type implementation
255 /////////////////////////////////////////////////////////////////////////////
257 impl<T, E> Result<T, E> {
258 /////////////////////////////////////////////////////////////////////////
259 // Querying the contained values
260 /////////////////////////////////////////////////////////////////////////
262 /// Returns `true` if the result is [`Ok`].
269 /// let x: Result<i32, &str> = Ok(-3);
270 /// assert_eq!(x.is_ok(), true);
272 /// let x: Result<i32, &str> = Err("Some error message");
273 /// assert_eq!(x.is_ok(), false);
275 #[must_use = "if you intended to assert that this is ok, consider `.unwrap()` instead"]
276 #[rustc_const_stable(feature = "const_result", since = "1.48.0")]
278 #[stable(feature = "rust1", since = "1.0.0")]
279 pub const fn is_ok(&self) -> bool {
280 matches!(*self, Ok(_))
283 /// Returns `true` if the result is [`Err`].
290 /// let x: Result<i32, &str> = Ok(-3);
291 /// assert_eq!(x.is_err(), false);
293 /// let x: Result<i32, &str> = Err("Some error message");
294 /// assert_eq!(x.is_err(), true);
296 #[must_use = "if you intended to assert that this is err, consider `.unwrap_err()` instead"]
297 #[rustc_const_stable(feature = "const_result", since = "1.48.0")]
299 #[stable(feature = "rust1", since = "1.0.0")]
300 pub const fn is_err(&self) -> bool {
304 /// Returns `true` if the result is an [`Ok`] value containing the given value.
309 /// #![feature(option_result_contains)]
311 /// let x: Result<u32, &str> = Ok(2);
312 /// assert_eq!(x.contains(&2), true);
314 /// let x: Result<u32, &str> = Ok(3);
315 /// assert_eq!(x.contains(&2), false);
317 /// let x: Result<u32, &str> = Err("Some error message");
318 /// assert_eq!(x.contains(&2), false);
322 #[unstable(feature = "option_result_contains", issue = "62358")]
323 pub fn contains<U>(&self, x: &U) -> bool
333 /// Returns `true` if the result is an [`Err`] value containing the given value.
338 /// #![feature(result_contains_err)]
340 /// let x: Result<u32, &str> = Ok(2);
341 /// assert_eq!(x.contains_err(&"Some error message"), false);
343 /// let x: Result<u32, &str> = Err("Some error message");
344 /// assert_eq!(x.contains_err(&"Some error message"), true);
346 /// let x: Result<u32, &str> = Err("Some other error message");
347 /// assert_eq!(x.contains_err(&"Some error message"), false);
351 #[unstable(feature = "result_contains_err", issue = "62358")]
352 pub fn contains_err<F>(&self, f: &F) -> bool
362 /////////////////////////////////////////////////////////////////////////
363 // Adapter for each variant
364 /////////////////////////////////////////////////////////////////////////
366 /// Converts from `Result<T, E>` to [`Option<T>`].
368 /// Converts `self` into an [`Option<T>`], consuming `self`,
369 /// and discarding the error, if any.
376 /// let x: Result<u32, &str> = Ok(2);
377 /// assert_eq!(x.ok(), Some(2));
379 /// let x: Result<u32, &str> = Err("Nothing here");
380 /// assert_eq!(x.ok(), None);
383 #[stable(feature = "rust1", since = "1.0.0")]
384 pub fn ok(self) -> Option<T> {
391 /// Converts from `Result<T, E>` to [`Option<E>`].
393 /// Converts `self` into an [`Option<E>`], consuming `self`,
394 /// and discarding the success value, if any.
401 /// let x: Result<u32, &str> = Ok(2);
402 /// assert_eq!(x.err(), None);
404 /// let x: Result<u32, &str> = Err("Nothing here");
405 /// assert_eq!(x.err(), Some("Nothing here"));
408 #[stable(feature = "rust1", since = "1.0.0")]
409 pub fn err(self) -> Option<E> {
416 /////////////////////////////////////////////////////////////////////////
417 // Adapter for working with references
418 /////////////////////////////////////////////////////////////////////////
420 /// Converts from `&Result<T, E>` to `Result<&T, &E>`.
422 /// Produces a new `Result`, containing a reference
423 /// into the original, leaving the original in place.
430 /// let x: Result<u32, &str> = Ok(2);
431 /// assert_eq!(x.as_ref(), Ok(&2));
433 /// let x: Result<u32, &str> = Err("Error");
434 /// assert_eq!(x.as_ref(), Err(&"Error"));
437 #[rustc_const_stable(feature = "const_result", since = "1.48.0")]
438 #[stable(feature = "rust1", since = "1.0.0")]
439 pub const fn as_ref(&self) -> Result<&T, &E> {
442 Err(ref x) => Err(x),
446 /// Converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`.
453 /// fn mutate(r: &mut Result<i32, i32>) {
454 /// match r.as_mut() {
455 /// Ok(v) => *v = 42,
456 /// Err(e) => *e = 0,
460 /// let mut x: Result<i32, i32> = Ok(2);
462 /// assert_eq!(x.unwrap(), 42);
464 /// let mut x: Result<i32, i32> = Err(13);
466 /// assert_eq!(x.unwrap_err(), 0);
469 #[stable(feature = "rust1", since = "1.0.0")]
470 pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
472 Ok(ref mut x) => Ok(x),
473 Err(ref mut x) => Err(x),
477 /////////////////////////////////////////////////////////////////////////
478 // Transforming contained values
479 /////////////////////////////////////////////////////////////////////////
481 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
482 /// contained [`Ok`] value, leaving an [`Err`] value untouched.
484 /// This function can be used to compose the results of two functions.
488 /// Print the numbers on each line of a string multiplied by two.
491 /// let line = "1\n2\n3\n4\n";
493 /// for num in line.lines() {
494 /// match num.parse::<i32>().map(|i| i * 2) {
495 /// Ok(n) => println!("{}", n),
501 #[stable(feature = "rust1", since = "1.0.0")]
502 pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U, E> {
509 /// Applies a function to the contained value (if [`Ok`]),
510 /// or returns the provided default (if [`Err`]).
512 /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
513 /// the result of a function call, it is recommended to use [`map_or_else`],
514 /// which is lazily evaluated.
516 /// [`map_or_else`]: Result::map_or_else
521 /// let x: Result<_, &str> = Ok("foo");
522 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
524 /// let x: Result<&str, _> = Err("bar");
525 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
528 #[stable(feature = "result_map_or", since = "1.41.0")]
529 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
536 /// Maps a `Result<T, E>` to `U` by applying a function to a
537 /// contained [`Ok`] value, or a fallback function to a
538 /// contained [`Err`] value.
540 /// This function can be used to unpack a successful result
541 /// while handling an error.
551 /// let x : Result<_, &str> = Ok("foo");
552 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);
554 /// let x : Result<&str, _> = Err("bar");
555 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
558 #[stable(feature = "result_map_or_else", since = "1.41.0")]
559 pub fn map_or_else<U, D: FnOnce(E) -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
562 Err(e) => default(e),
566 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
567 /// contained [`Err`] value, leaving an [`Ok`] value untouched.
569 /// This function can be used to pass through a successful result while handling
578 /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
580 /// let x: Result<u32, u32> = Ok(2);
581 /// assert_eq!(x.map_err(stringify), Ok(2));
583 /// let x: Result<u32, u32> = Err(13);
584 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
587 #[stable(feature = "rust1", since = "1.0.0")]
588 pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T, F> {
591 Err(e) => Err(op(e)),
595 /////////////////////////////////////////////////////////////////////////
596 // Iterator constructors
597 /////////////////////////////////////////////////////////////////////////
599 /// Returns an iterator over the possibly contained value.
601 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
608 /// let x: Result<u32, &str> = Ok(7);
609 /// assert_eq!(x.iter().next(), Some(&7));
611 /// let x: Result<u32, &str> = Err("nothing!");
612 /// assert_eq!(x.iter().next(), None);
615 #[stable(feature = "rust1", since = "1.0.0")]
616 pub fn iter(&self) -> Iter<'_, T> {
617 Iter { inner: self.as_ref().ok() }
620 /// Returns a mutable iterator over the possibly contained value.
622 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
629 /// let mut x: Result<u32, &str> = Ok(7);
630 /// match x.iter_mut().next() {
631 /// Some(v) => *v = 40,
634 /// assert_eq!(x, Ok(40));
636 /// let mut x: Result<u32, &str> = Err("nothing!");
637 /// assert_eq!(x.iter_mut().next(), None);
640 #[stable(feature = "rust1", since = "1.0.0")]
641 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
642 IterMut { inner: self.as_mut().ok() }
645 ////////////////////////////////////////////////////////////////////////
646 // Boolean operations on the values, eager and lazy
647 /////////////////////////////////////////////////////////////////////////
649 /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
657 /// let x: Result<u32, &str> = Ok(2);
658 /// let y: Result<&str, &str> = Err("late error");
659 /// assert_eq!(x.and(y), Err("late error"));
661 /// let x: Result<u32, &str> = Err("early error");
662 /// let y: Result<&str, &str> = Ok("foo");
663 /// assert_eq!(x.and(y), Err("early error"));
665 /// let x: Result<u32, &str> = Err("not a 2");
666 /// let y: Result<&str, &str> = Err("late error");
667 /// assert_eq!(x.and(y), Err("not a 2"));
669 /// let x: Result<u32, &str> = Ok(2);
670 /// let y: Result<&str, &str> = Ok("different result type");
671 /// assert_eq!(x.and(y), Ok("different result type"));
674 #[stable(feature = "rust1", since = "1.0.0")]
675 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
682 /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
685 /// This function can be used for control flow based on `Result` values.
692 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
693 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
695 /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
696 /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
697 /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
698 /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
701 #[stable(feature = "rust1", since = "1.0.0")]
702 pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
709 /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
711 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
712 /// result of a function call, it is recommended to use [`or_else`], which is
713 /// lazily evaluated.
715 /// [`or_else`]: Result::or_else
722 /// let x: Result<u32, &str> = Ok(2);
723 /// let y: Result<u32, &str> = Err("late error");
724 /// assert_eq!(x.or(y), Ok(2));
726 /// let x: Result<u32, &str> = Err("early error");
727 /// let y: Result<u32, &str> = Ok(2);
728 /// assert_eq!(x.or(y), Ok(2));
730 /// let x: Result<u32, &str> = Err("not a 2");
731 /// let y: Result<u32, &str> = Err("late error");
732 /// assert_eq!(x.or(y), Err("late error"));
734 /// let x: Result<u32, &str> = Ok(2);
735 /// let y: Result<u32, &str> = Ok(100);
736 /// assert_eq!(x.or(y), Ok(2));
739 #[stable(feature = "rust1", since = "1.0.0")]
740 pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
747 /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
749 /// This function can be used for control flow based on result values.
757 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
758 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
760 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
761 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
762 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
763 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
766 #[stable(feature = "rust1", since = "1.0.0")]
767 pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
774 /// Returns the contained [`Ok`] value or a provided default.
776 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
777 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
778 /// which is lazily evaluated.
780 /// [`unwrap_or_else`]: Result::unwrap_or_else
788 /// let x: Result<u32, &str> = Ok(9);
789 /// assert_eq!(x.unwrap_or(default), 9);
791 /// let x: Result<u32, &str> = Err("error");
792 /// assert_eq!(x.unwrap_or(default), default);
795 #[stable(feature = "rust1", since = "1.0.0")]
796 pub fn unwrap_or(self, default: T) -> T {
803 /// Returns the contained [`Ok`] value or computes it from a closure.
811 /// fn count(x: &str) -> usize { x.len() }
813 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
814 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
817 #[stable(feature = "rust1", since = "1.0.0")]
818 pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
826 impl<T: Copy, E> Result<&T, E> {
827 /// Maps a `Result<&T, E>` to a `Result<T, E>` by copying the contents of the
833 /// #![feature(result_copied)]
835 /// let x: Result<&i32, i32> = Ok(&val);
836 /// assert_eq!(x, Ok(&12));
837 /// let copied = x.copied();
838 /// assert_eq!(copied, Ok(12));
840 #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
841 pub fn copied(self) -> Result<T, E> {
846 impl<T: Copy, E> Result<&mut T, E> {
847 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by copying the contents of the
853 /// #![feature(result_copied)]
854 /// let mut val = 12;
855 /// let x: Result<&mut i32, i32> = Ok(&mut val);
856 /// assert_eq!(x, Ok(&mut 12));
857 /// let copied = x.copied();
858 /// assert_eq!(copied, Ok(12));
860 #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
861 pub fn copied(self) -> Result<T, E> {
866 impl<T: Clone, E> Result<&T, E> {
867 /// Maps a `Result<&T, E>` to a `Result<T, E>` by cloning the contents of the
873 /// #![feature(result_cloned)]
875 /// let x: Result<&i32, i32> = Ok(&val);
876 /// assert_eq!(x, Ok(&12));
877 /// let cloned = x.cloned();
878 /// assert_eq!(cloned, Ok(12));
880 #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
881 pub fn cloned(self) -> Result<T, E> {
882 self.map(|t| t.clone())
886 impl<T: Clone, E> Result<&mut T, E> {
887 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by cloning the contents of the
893 /// #![feature(result_cloned)]
894 /// let mut val = 12;
895 /// let x: Result<&mut i32, i32> = Ok(&mut val);
896 /// assert_eq!(x, Ok(&mut 12));
897 /// let cloned = x.cloned();
898 /// assert_eq!(cloned, Ok(12));
900 #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
901 pub fn cloned(self) -> Result<T, E> {
902 self.map(|t| t.clone())
906 impl<T, E: fmt::Debug> Result<T, E> {
907 /// Returns the contained [`Ok`] value, consuming the `self` value.
911 /// Panics if the value is an [`Err`], with a panic message including the
912 /// passed message, and the content of the [`Err`].
919 /// ```{.should_panic}
920 /// let x: Result<u32, &str> = Err("emergency failure");
921 /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
925 #[stable(feature = "result_expect", since = "1.4.0")]
926 pub fn expect(self, msg: &str) -> T {
929 Err(e) => unwrap_failed(msg, &e),
933 /// Returns the contained [`Ok`] value, consuming the `self` value.
935 /// Because this function may panic, its use is generally discouraged.
936 /// Instead, prefer to use pattern matching and handle the [`Err`]
937 /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
938 /// [`unwrap_or_default`].
940 /// [`unwrap_or`]: Result::unwrap_or
941 /// [`unwrap_or_else`]: Result::unwrap_or_else
942 /// [`unwrap_or_default`]: Result::unwrap_or_default
946 /// Panics if the value is an [`Err`], with a panic message provided by the
955 /// let x: Result<u32, &str> = Ok(2);
956 /// assert_eq!(x.unwrap(), 2);
959 /// ```{.should_panic}
960 /// let x: Result<u32, &str> = Err("emergency failure");
961 /// x.unwrap(); // panics with `emergency failure`
965 #[stable(feature = "rust1", since = "1.0.0")]
966 pub fn unwrap(self) -> T {
969 Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e),
974 impl<T: fmt::Debug, E> Result<T, E> {
975 /// Returns the contained [`Err`] value, consuming the `self` value.
979 /// Panics if the value is an [`Ok`], with a panic message including the
980 /// passed message, and the content of the [`Ok`].
987 /// ```{.should_panic}
988 /// let x: Result<u32, &str> = Ok(10);
989 /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
993 #[stable(feature = "result_expect_err", since = "1.17.0")]
994 pub fn expect_err(self, msg: &str) -> E {
996 Ok(t) => unwrap_failed(msg, &t),
1001 /// Returns the contained [`Err`] value, consuming the `self` value.
1005 /// Panics if the value is an [`Ok`], with a custom panic message provided
1006 /// by the [`Ok`]'s value.
1010 /// ```{.should_panic}
1011 /// let x: Result<u32, &str> = Ok(2);
1012 /// x.unwrap_err(); // panics with `2`
1016 /// let x: Result<u32, &str> = Err("emergency failure");
1017 /// assert_eq!(x.unwrap_err(), "emergency failure");
1021 #[stable(feature = "rust1", since = "1.0.0")]
1022 pub fn unwrap_err(self) -> E {
1024 Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t),
1030 impl<T: Default, E> Result<T, E> {
1031 /// Returns the contained [`Ok`] value or a default
1033 /// Consumes the `self` argument then, if [`Ok`], returns the contained
1034 /// value, otherwise if [`Err`], returns the default value for that
1039 /// Converts a string to an integer, turning poorly-formed strings
1040 /// into 0 (the default value for integers). [`parse`] converts
1041 /// a string to any other type that implements [`FromStr`], returning an
1042 /// [`Err`] on error.
1045 /// let good_year_from_input = "1909";
1046 /// let bad_year_from_input = "190blarg";
1047 /// let good_year = good_year_from_input.parse().unwrap_or_default();
1048 /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
1050 /// assert_eq!(1909, good_year);
1051 /// assert_eq!(0, bad_year);
1054 /// [`parse`]: str::parse
1055 /// [`FromStr`]: crate::str::FromStr
1057 #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
1058 pub fn unwrap_or_default(self) -> T {
1061 Err(_) => Default::default(),
1066 #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
1067 impl<T, E: Into<!>> Result<T, E> {
1068 /// Returns the contained [`Ok`] value, but never panics.
1070 /// Unlike [`unwrap`], this method is known to never panic on the
1071 /// result types it is implemented for. Therefore, it can be used
1072 /// instead of `unwrap` as a maintainability safeguard that will fail
1073 /// to compile if the error type of the `Result` is later changed
1074 /// to an error that can actually occur.
1076 /// [`unwrap`]: Result::unwrap
1083 /// # #![feature(never_type)]
1084 /// # #![feature(unwrap_infallible)]
1086 /// fn only_good_news() -> Result<String, !> {
1087 /// Ok("this is fine".into())
1090 /// let s: String = only_good_news().into_ok();
1091 /// println!("{}", s);
1094 pub fn into_ok(self) -> T {
1102 impl<T: Deref, E> Result<T, E> {
1103 /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&<T as Deref>::Target, &E>`.
1105 /// Coerces the [`Ok`] variant of the original [`Result`] via [`Deref`](crate::ops::Deref)
1106 /// and returns the new [`Result`].
1111 /// let x: Result<String, u32> = Ok("hello".to_string());
1112 /// let y: Result<&str, &u32> = Ok("hello");
1113 /// assert_eq!(x.as_deref(), y);
1115 /// let x: Result<String, u32> = Err(42);
1116 /// let y: Result<&str, &u32> = Err(&42);
1117 /// assert_eq!(x.as_deref(), y);
1119 #[stable(feature = "inner_deref", since = "1.47.0")]
1120 pub fn as_deref(&self) -> Result<&T::Target, &E> {
1121 self.as_ref().map(|t| t.deref())
1125 impl<T: DerefMut, E> Result<T, E> {
1126 /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut <T as DerefMut>::Target, &mut E>`.
1128 /// Coerces the [`Ok`] variant of the original [`Result`] via [`DerefMut`](crate::ops::DerefMut)
1129 /// and returns the new [`Result`].
1134 /// let mut s = "HELLO".to_string();
1135 /// let mut x: Result<String, u32> = Ok("hello".to_string());
1136 /// let y: Result<&mut str, &mut u32> = Ok(&mut s);
1137 /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
1140 /// let mut x: Result<String, u32> = Err(42);
1141 /// let y: Result<&mut str, &mut u32> = Err(&mut i);
1142 /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
1144 #[stable(feature = "inner_deref", since = "1.47.0")]
1145 pub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E> {
1146 self.as_mut().map(|t| t.deref_mut())
1150 impl<T, E> Result<Option<T>, E> {
1151 /// Transposes a `Result` of an `Option` into an `Option` of a `Result`.
1153 /// `Ok(None)` will be mapped to `None`.
1154 /// `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`.
1159 /// #[derive(Debug, Eq, PartialEq)]
1162 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1163 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1164 /// assert_eq!(x.transpose(), y);
1167 #[stable(feature = "transpose_result", since = "1.33.0")]
1168 pub fn transpose(self) -> Option<Result<T, E>> {
1170 Ok(Some(x)) => Some(Ok(x)),
1172 Err(e) => Some(Err(e)),
1177 impl<T, E> Result<Result<T, E>, E> {
1178 /// Converts from `Result<Result<T, E>, E>` to `Result<T, E>`
1185 /// #![feature(result_flattening)]
1186 /// let x: Result<Result<&'static str, u32>, u32> = Ok(Ok("hello"));
1187 /// assert_eq!(Ok("hello"), x.flatten());
1189 /// let x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));
1190 /// assert_eq!(Err(6), x.flatten());
1192 /// let x: Result<Result<&'static str, u32>, u32> = Err(6);
1193 /// assert_eq!(Err(6), x.flatten());
1196 /// Flattening only removes one level of nesting at a time:
1199 /// #![feature(result_flattening)]
1200 /// let x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok("hello")));
1201 /// assert_eq!(Ok(Ok("hello")), x.flatten());
1202 /// assert_eq!(Ok("hello"), x.flatten().flatten());
1205 #[unstable(feature = "result_flattening", issue = "70142")]
1206 pub fn flatten(self) -> Result<T, E> {
1207 self.and_then(convert::identity)
1211 // This is a separate function to reduce the code size of the methods
1215 fn unwrap_failed(msg: &str, error: &dyn fmt::Debug) -> ! {
1216 panic!("{}: {:?}", msg, error)
1219 /////////////////////////////////////////////////////////////////////////////
1220 // Trait implementations
1221 /////////////////////////////////////////////////////////////////////////////
1223 #[stable(feature = "rust1", since = "1.0.0")]
1224 impl<T: Clone, E: Clone> Clone for Result<T, E> {
1226 fn clone(&self) -> Self {
1228 Ok(x) => Ok(x.clone()),
1229 Err(x) => Err(x.clone()),
1234 fn clone_from(&mut self, source: &Self) {
1235 match (self, source) {
1236 (Ok(to), Ok(from)) => to.clone_from(from),
1237 (Err(to), Err(from)) => to.clone_from(from),
1238 (to, from) => *to = from.clone(),
1243 #[stable(feature = "rust1", since = "1.0.0")]
1244 impl<T, E> IntoIterator for Result<T, E> {
1246 type IntoIter = IntoIter<T>;
1248 /// Returns a consuming iterator over the possibly contained value.
1250 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
1257 /// let x: Result<u32, &str> = Ok(5);
1258 /// let v: Vec<u32> = x.into_iter().collect();
1259 /// assert_eq!(v, [5]);
1261 /// let x: Result<u32, &str> = Err("nothing!");
1262 /// let v: Vec<u32> = x.into_iter().collect();
1263 /// assert_eq!(v, []);
1266 fn into_iter(self) -> IntoIter<T> {
1267 IntoIter { inner: self.ok() }
1271 #[stable(since = "1.4.0", feature = "result_iter")]
1272 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
1274 type IntoIter = Iter<'a, T>;
1276 fn into_iter(self) -> Iter<'a, T> {
1281 #[stable(since = "1.4.0", feature = "result_iter")]
1282 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
1283 type Item = &'a mut T;
1284 type IntoIter = IterMut<'a, T>;
1286 fn into_iter(self) -> IterMut<'a, T> {
1291 /////////////////////////////////////////////////////////////////////////////
1292 // The Result Iterators
1293 /////////////////////////////////////////////////////////////////////////////
1295 /// An iterator over a reference to the [`Ok`] variant of a [`Result`].
1297 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1299 /// Created by [`Result::iter`].
1301 #[stable(feature = "rust1", since = "1.0.0")]
1302 pub struct Iter<'a, T: 'a> {
1303 inner: Option<&'a T>,
1306 #[stable(feature = "rust1", since = "1.0.0")]
1307 impl<'a, T> Iterator for Iter<'a, T> {
1311 fn next(&mut self) -> Option<&'a T> {
1315 fn size_hint(&self) -> (usize, Option<usize>) {
1316 let n = if self.inner.is_some() { 1 } else { 0 };
1321 #[stable(feature = "rust1", since = "1.0.0")]
1322 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1324 fn next_back(&mut self) -> Option<&'a T> {
1329 #[stable(feature = "rust1", since = "1.0.0")]
1330 impl<T> ExactSizeIterator for Iter<'_, T> {}
1332 #[stable(feature = "fused", since = "1.26.0")]
1333 impl<T> FusedIterator for Iter<'_, T> {}
1335 #[unstable(feature = "trusted_len", issue = "37572")]
1336 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1338 #[stable(feature = "rust1", since = "1.0.0")]
1339 impl<T> Clone for Iter<'_, T> {
1341 fn clone(&self) -> Self {
1342 Iter { inner: self.inner }
1346 /// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
1348 /// Created by [`Result::iter_mut`].
1350 #[stable(feature = "rust1", since = "1.0.0")]
1351 pub struct IterMut<'a, T: 'a> {
1352 inner: Option<&'a mut T>,
1355 #[stable(feature = "rust1", since = "1.0.0")]
1356 impl<'a, T> Iterator for IterMut<'a, T> {
1357 type Item = &'a mut T;
1360 fn next(&mut self) -> Option<&'a mut T> {
1364 fn size_hint(&self) -> (usize, Option<usize>) {
1365 let n = if self.inner.is_some() { 1 } else { 0 };
1370 #[stable(feature = "rust1", since = "1.0.0")]
1371 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1373 fn next_back(&mut self) -> Option<&'a mut T> {
1378 #[stable(feature = "rust1", since = "1.0.0")]
1379 impl<T> ExactSizeIterator for IterMut<'_, T> {}
1381 #[stable(feature = "fused", since = "1.26.0")]
1382 impl<T> FusedIterator for IterMut<'_, T> {}
1384 #[unstable(feature = "trusted_len", issue = "37572")]
1385 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1387 /// An iterator over the value in a [`Ok`] variant of a [`Result`].
1389 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1391 /// This struct is created by the [`into_iter`] method on
1392 /// [`Result`] (provided by the [`IntoIterator`] trait).
1394 /// [`into_iter`]: IntoIterator::into_iter
1395 #[derive(Clone, Debug)]
1396 #[stable(feature = "rust1", since = "1.0.0")]
1397 pub struct IntoIter<T> {
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 impl<T> Iterator for IntoIter<T> {
1406 fn next(&mut self) -> Option<T> {
1410 fn size_hint(&self) -> (usize, Option<usize>) {
1411 let n = if self.inner.is_some() { 1 } else { 0 };
1416 #[stable(feature = "rust1", since = "1.0.0")]
1417 impl<T> DoubleEndedIterator for IntoIter<T> {
1419 fn next_back(&mut self) -> Option<T> {
1424 #[stable(feature = "rust1", since = "1.0.0")]
1425 impl<T> ExactSizeIterator for IntoIter<T> {}
1427 #[stable(feature = "fused", since = "1.26.0")]
1428 impl<T> FusedIterator for IntoIter<T> {}
1430 #[unstable(feature = "trusted_len", issue = "37572")]
1431 unsafe impl<A> TrustedLen for IntoIter<A> {}
1433 /////////////////////////////////////////////////////////////////////////////
1435 /////////////////////////////////////////////////////////////////////////////
1437 #[stable(feature = "rust1", since = "1.0.0")]
1438 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
1439 /// Takes each element in the `Iterator`: if it is an `Err`, no further
1440 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
1441 /// container with the values of each `Result` is returned.
1443 /// Here is an example which increments every integer in a vector,
1444 /// checking for overflow:
1447 /// let v = vec![1, 2];
1448 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1449 /// x.checked_add(1).ok_or("Overflow!")
1451 /// assert_eq!(res, Ok(vec![2, 3]));
1454 /// Here is another example that tries to subtract one from another list
1455 /// of integers, this time checking for underflow:
1458 /// let v = vec![1, 2, 0];
1459 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1460 /// x.checked_sub(1).ok_or("Underflow!")
1462 /// assert_eq!(res, Err("Underflow!"));
1465 /// Here is a variation on the previous example, showing that no
1466 /// further elements are taken from `iter` after the first `Err`.
1469 /// let v = vec![3, 2, 1, 10];
1470 /// let mut shared = 0;
1471 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {
1473 /// x.checked_sub(2).ok_or("Underflow!")
1475 /// assert_eq!(res, Err("Underflow!"));
1476 /// assert_eq!(shared, 6);
1479 /// Since the third element caused an underflow, no further elements were taken,
1480 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1482 fn from_iter<I: IntoIterator<Item = Result<A, E>>>(iter: I) -> Result<V, E> {
1483 // FIXME(#11084): This could be replaced with Iterator::scan when this
1484 // performance bug is closed.
1486 iter::process_results(iter.into_iter(), |i| i.collect())
1490 #[unstable(feature = "try_trait", issue = "42327")]
1491 impl<T, E> ops::Try for Result<T, E> {
1496 fn into_result(self) -> Self {
1501 fn from_ok(v: T) -> Self {
1506 fn from_error(v: E) -> Self {