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`]: enum.Result.html#method.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 //! [`?`]: ../../std/macro.try.html
224 //! [`Result`]: enum.Result.html
225 //! [`Ok(T)`]: enum.Result.html#variant.Ok
226 //! [`Err(E)`]: enum.Result.html#variant.Err
227 //! [`io::Error`]: ../../std/io/struct.Error.html
228 //! [`Ok`]: enum.Result.html#variant.Ok
229 //! [`Err`]: enum.Result.html#variant.Err
231 #![stable(feature = "rust1", since = "1.0.0")]
234 use crate::iter::{self, FromIterator, FusedIterator, TrustedLen};
235 use crate::ops::{self, Deref, DerefMut};
237 /// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]).
239 /// See the [`std::result`](index.html) module documentation for details.
241 /// [`Ok`]: enum.Result.html#variant.Ok
242 /// [`Err`]: enum.Result.html#variant.Err
243 #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
244 #[must_use = "this `Result` may be an `Err` variant, which should be handled"]
245 #[rustc_diagnostic_item = "result_type"]
246 #[stable(feature = "rust1", since = "1.0.0")]
247 pub enum Result<T, E> {
248 /// Contains the success value
249 #[stable(feature = "rust1", since = "1.0.0")]
250 Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
252 /// Contains the error value
253 #[stable(feature = "rust1", since = "1.0.0")]
254 Err(#[stable(feature = "rust1", since = "1.0.0")] E),
257 /////////////////////////////////////////////////////////////////////////////
258 // Type implementation
259 /////////////////////////////////////////////////////////////////////////////
261 impl<T, E> Result<T, E> {
262 /////////////////////////////////////////////////////////////////////////
263 // Querying the contained values
264 /////////////////////////////////////////////////////////////////////////
266 /// Returns `true` if the result is [`Ok`].
268 /// [`Ok`]: enum.Result.html#variant.Ok
275 /// let x: Result<i32, &str> = Ok(-3);
276 /// assert_eq!(x.is_ok(), true);
278 /// let x: Result<i32, &str> = Err("Some error message");
279 /// assert_eq!(x.is_ok(), false);
281 #[must_use = "if you intended to assert that this is ok, consider `.unwrap()` instead"]
282 #[rustc_const_unstable(feature = "const_result", issue = "67520")]
284 #[stable(feature = "rust1", since = "1.0.0")]
285 pub const fn is_ok(&self) -> bool {
286 matches!(*self, Ok(_))
289 /// Returns `true` if the result is [`Err`].
291 /// [`Err`]: enum.Result.html#variant.Err
298 /// let x: Result<i32, &str> = Ok(-3);
299 /// assert_eq!(x.is_err(), false);
301 /// let x: Result<i32, &str> = Err("Some error message");
302 /// assert_eq!(x.is_err(), true);
304 #[must_use = "if you intended to assert that this is err, consider `.unwrap_err()` instead"]
305 #[rustc_const_unstable(feature = "const_result", issue = "67520")]
307 #[stable(feature = "rust1", since = "1.0.0")]
308 pub const fn is_err(&self) -> bool {
312 /// Returns `true` if the result is an [`Ok`] value containing the given value.
317 /// #![feature(option_result_contains)]
319 /// let x: Result<u32, &str> = Ok(2);
320 /// assert_eq!(x.contains(&2), true);
322 /// let x: Result<u32, &str> = Ok(3);
323 /// assert_eq!(x.contains(&2), false);
325 /// let x: Result<u32, &str> = Err("Some error message");
326 /// assert_eq!(x.contains(&2), false);
330 #[unstable(feature = "option_result_contains", issue = "62358")]
331 pub fn contains<U>(&self, x: &U) -> bool
341 /// Returns `true` if the result is an [`Err`] value containing the given value.
346 /// #![feature(result_contains_err)]
348 /// let x: Result<u32, &str> = Ok(2);
349 /// assert_eq!(x.contains_err(&"Some error message"), false);
351 /// let x: Result<u32, &str> = Err("Some error message");
352 /// assert_eq!(x.contains_err(&"Some error message"), true);
354 /// let x: Result<u32, &str> = Err("Some other error message");
355 /// assert_eq!(x.contains_err(&"Some error message"), false);
359 #[unstable(feature = "result_contains_err", issue = "62358")]
360 pub fn contains_err<F>(&self, f: &F) -> bool
370 /////////////////////////////////////////////////////////////////////////
371 // Adapter for each variant
372 /////////////////////////////////////////////////////////////////////////
374 /// Converts from `Result<T, E>` to [`Option<T>`].
376 /// Converts `self` into an [`Option<T>`], consuming `self`,
377 /// and discarding the error, if any.
379 /// [`Option<T>`]: ../../std/option/enum.Option.html
386 /// let x: Result<u32, &str> = Ok(2);
387 /// assert_eq!(x.ok(), Some(2));
389 /// let x: Result<u32, &str> = Err("Nothing here");
390 /// assert_eq!(x.ok(), None);
393 #[stable(feature = "rust1", since = "1.0.0")]
394 pub fn ok(self) -> Option<T> {
401 /// Converts from `Result<T, E>` to [`Option<E>`].
403 /// Converts `self` into an [`Option<E>`], consuming `self`,
404 /// and discarding the success value, if any.
406 /// [`Option<E>`]: ../../std/option/enum.Option.html
413 /// let x: Result<u32, &str> = Ok(2);
414 /// assert_eq!(x.err(), None);
416 /// let x: Result<u32, &str> = Err("Nothing here");
417 /// assert_eq!(x.err(), Some("Nothing here"));
420 #[stable(feature = "rust1", since = "1.0.0")]
421 pub fn err(self) -> Option<E> {
428 /////////////////////////////////////////////////////////////////////////
429 // Adapter for working with references
430 /////////////////////////////////////////////////////////////////////////
432 /// Converts from `&Result<T, E>` to `Result<&T, &E>`.
434 /// Produces a new `Result`, containing a reference
435 /// into the original, leaving the original in place.
442 /// let x: Result<u32, &str> = Ok(2);
443 /// assert_eq!(x.as_ref(), Ok(&2));
445 /// let x: Result<u32, &str> = Err("Error");
446 /// assert_eq!(x.as_ref(), Err(&"Error"));
449 #[rustc_const_unstable(feature = "const_result", issue = "67520")]
450 #[stable(feature = "rust1", since = "1.0.0")]
451 pub const fn as_ref(&self) -> Result<&T, &E> {
454 Err(ref x) => Err(x),
458 /// Converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`.
465 /// fn mutate(r: &mut Result<i32, i32>) {
466 /// match r.as_mut() {
467 /// Ok(v) => *v = 42,
468 /// Err(e) => *e = 0,
472 /// let mut x: Result<i32, i32> = Ok(2);
474 /// assert_eq!(x.unwrap(), 42);
476 /// let mut x: Result<i32, i32> = Err(13);
478 /// assert_eq!(x.unwrap_err(), 0);
481 #[stable(feature = "rust1", since = "1.0.0")]
482 pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
484 Ok(ref mut x) => Ok(x),
485 Err(ref mut x) => Err(x),
489 /////////////////////////////////////////////////////////////////////////
490 // Transforming contained values
491 /////////////////////////////////////////////////////////////////////////
493 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
494 /// contained [`Ok`] value, leaving an [`Err`] value untouched.
496 /// This function can be used to compose the results of two functions.
498 /// [`Ok`]: enum.Result.html#variant.Ok
499 /// [`Err`]: enum.Result.html#variant.Err
503 /// Print the numbers on each line of a string multiplied by two.
506 /// let line = "1\n2\n3\n4\n";
508 /// for num in line.lines() {
509 /// match num.parse::<i32>().map(|i| i * 2) {
510 /// Ok(n) => println!("{}", n),
516 #[stable(feature = "rust1", since = "1.0.0")]
517 pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U, E> {
524 /// Applies a function to the contained value (if any),
525 /// or returns the provided default (if not).
530 /// let x: Result<_, &str> = Ok("foo");
531 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
533 /// let x: Result<&str, _> = Err("bar");
534 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
537 #[stable(feature = "result_map_or", since = "1.41.0")]
538 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
545 /// Maps a `Result<T, E>` to `U` by applying a function to a
546 /// contained [`Ok`] value, or a fallback function to a
547 /// contained [`Err`] value.
549 /// This function can be used to unpack a successful result
550 /// while handling an error.
552 /// [`Ok`]: enum.Result.html#variant.Ok
553 /// [`Err`]: enum.Result.html#variant.Err
562 /// let x : Result<_, &str> = Ok("foo");
563 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);
565 /// let x : Result<&str, _> = Err("bar");
566 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
569 #[stable(feature = "result_map_or_else", since = "1.41.0")]
570 pub fn map_or_else<U, D: FnOnce(E) -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
573 Err(e) => default(e),
577 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
578 /// contained [`Err`] value, leaving an [`Ok`] value untouched.
580 /// This function can be used to pass through a successful result while handling
583 /// [`Ok`]: enum.Result.html#variant.Ok
584 /// [`Err`]: enum.Result.html#variant.Err
591 /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
593 /// let x: Result<u32, u32> = Ok(2);
594 /// assert_eq!(x.map_err(stringify), Ok(2));
596 /// let x: Result<u32, u32> = Err(13);
597 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
600 #[stable(feature = "rust1", since = "1.0.0")]
601 pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T, F> {
604 Err(e) => Err(op(e)),
608 /////////////////////////////////////////////////////////////////////////
609 // Iterator constructors
610 /////////////////////////////////////////////////////////////////////////
612 /// Returns an iterator over the possibly contained value.
614 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
621 /// let x: Result<u32, &str> = Ok(7);
622 /// assert_eq!(x.iter().next(), Some(&7));
624 /// let x: Result<u32, &str> = Err("nothing!");
625 /// assert_eq!(x.iter().next(), None);
628 #[stable(feature = "rust1", since = "1.0.0")]
629 pub fn iter(&self) -> Iter<'_, T> {
630 Iter { inner: self.as_ref().ok() }
633 /// Returns a mutable iterator over the possibly contained value.
635 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
642 /// let mut x: Result<u32, &str> = Ok(7);
643 /// match x.iter_mut().next() {
644 /// Some(v) => *v = 40,
647 /// assert_eq!(x, Ok(40));
649 /// let mut x: Result<u32, &str> = Err("nothing!");
650 /// assert_eq!(x.iter_mut().next(), None);
653 #[stable(feature = "rust1", since = "1.0.0")]
654 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
655 IterMut { inner: self.as_mut().ok() }
658 ////////////////////////////////////////////////////////////////////////
659 // Boolean operations on the values, eager and lazy
660 /////////////////////////////////////////////////////////////////////////
662 /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
664 /// [`Ok`]: enum.Result.html#variant.Ok
665 /// [`Err`]: enum.Result.html#variant.Err
672 /// let x: Result<u32, &str> = Ok(2);
673 /// let y: Result<&str, &str> = Err("late error");
674 /// assert_eq!(x.and(y), Err("late error"));
676 /// let x: Result<u32, &str> = Err("early error");
677 /// let y: Result<&str, &str> = Ok("foo");
678 /// assert_eq!(x.and(y), Err("early error"));
680 /// let x: Result<u32, &str> = Err("not a 2");
681 /// let y: Result<&str, &str> = Err("late error");
682 /// assert_eq!(x.and(y), Err("not a 2"));
684 /// let x: Result<u32, &str> = Ok(2);
685 /// let y: Result<&str, &str> = Ok("different result type");
686 /// assert_eq!(x.and(y), Ok("different result type"));
689 #[stable(feature = "rust1", since = "1.0.0")]
690 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
697 /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
699 /// [`Ok`]: enum.Result.html#variant.Ok
700 /// [`Err`]: enum.Result.html#variant.Err
702 /// This function can be used for control flow based on `Result` values.
709 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
710 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
712 /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
713 /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
714 /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
715 /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
718 #[stable(feature = "rust1", since = "1.0.0")]
719 pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
726 /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
728 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
729 /// result of a function call, it is recommended to use [`or_else`], which is
730 /// lazily evaluated.
732 /// [`Ok`]: enum.Result.html#variant.Ok
733 /// [`Err`]: enum.Result.html#variant.Err
734 /// [`or_else`]: #method.or_else
741 /// let x: Result<u32, &str> = Ok(2);
742 /// let y: Result<u32, &str> = Err("late error");
743 /// assert_eq!(x.or(y), Ok(2));
745 /// let x: Result<u32, &str> = Err("early error");
746 /// let y: Result<u32, &str> = Ok(2);
747 /// assert_eq!(x.or(y), Ok(2));
749 /// let x: Result<u32, &str> = Err("not a 2");
750 /// let y: Result<u32, &str> = Err("late error");
751 /// assert_eq!(x.or(y), Err("late error"));
753 /// let x: Result<u32, &str> = Ok(2);
754 /// let y: Result<u32, &str> = Ok(100);
755 /// assert_eq!(x.or(y), Ok(2));
758 #[stable(feature = "rust1", since = "1.0.0")]
759 pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
766 /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
768 /// This function can be used for control flow based on result values.
770 /// [`Ok`]: enum.Result.html#variant.Ok
771 /// [`Err`]: enum.Result.html#variant.Err
778 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
779 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
781 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
782 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
783 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
784 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
787 #[stable(feature = "rust1", since = "1.0.0")]
788 pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
795 /// Unwraps a result, yielding the content of an [`Ok`].
796 /// Else, it returns `optb`.
798 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
799 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
800 /// which is lazily evaluated.
802 /// [`Ok`]: enum.Result.html#variant.Ok
803 /// [`Err`]: enum.Result.html#variant.Err
804 /// [`unwrap_or_else`]: #method.unwrap_or_else
812 /// let x: Result<u32, &str> = Ok(9);
813 /// assert_eq!(x.unwrap_or(optb), 9);
815 /// let x: Result<u32, &str> = Err("error");
816 /// assert_eq!(x.unwrap_or(optb), optb);
819 #[stable(feature = "rust1", since = "1.0.0")]
820 pub fn unwrap_or(self, optb: T) -> T {
827 /// Unwraps a result, yielding the content of an [`Ok`].
828 /// If the value is an [`Err`] then it calls `op` with its value.
830 /// [`Ok`]: enum.Result.html#variant.Ok
831 /// [`Err`]: enum.Result.html#variant.Err
838 /// fn count(x: &str) -> usize { x.len() }
840 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
841 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
844 #[stable(feature = "rust1", since = "1.0.0")]
845 pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
853 impl<T: Copy, E> Result<&T, E> {
854 /// Maps a `Result<&T, E>` to a `Result<T, E>` by copying the contents of the
860 /// #![feature(result_copied)]
862 /// let x: Result<&i32, i32> = Ok(&val);
863 /// assert_eq!(x, Ok(&12));
864 /// let copied = x.copied();
865 /// assert_eq!(copied, Ok(12));
867 #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
868 pub fn copied(self) -> Result<T, E> {
873 impl<T: Copy, E> Result<&mut T, E> {
874 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by copying the contents of the
880 /// #![feature(result_copied)]
881 /// let mut val = 12;
882 /// let x: Result<&mut i32, i32> = Ok(&mut val);
883 /// assert_eq!(x, Ok(&mut 12));
884 /// let copied = x.copied();
885 /// assert_eq!(copied, Ok(12));
887 #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
888 pub fn copied(self) -> Result<T, E> {
893 impl<T: Clone, E> Result<&T, E> {
894 /// Maps a `Result<&T, E>` to a `Result<T, E>` by cloning the contents of the
900 /// #![feature(result_cloned)]
902 /// let x: Result<&i32, i32> = Ok(&val);
903 /// assert_eq!(x, Ok(&12));
904 /// let cloned = x.cloned();
905 /// assert_eq!(cloned, Ok(12));
907 #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
908 pub fn cloned(self) -> Result<T, E> {
909 self.map(|t| t.clone())
913 impl<T: Clone, E> Result<&mut T, E> {
914 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by cloning the contents of the
920 /// #![feature(result_cloned)]
921 /// let mut val = 12;
922 /// let x: Result<&mut i32, i32> = Ok(&mut val);
923 /// assert_eq!(x, Ok(&mut 12));
924 /// let cloned = x.cloned();
925 /// assert_eq!(cloned, Ok(12));
927 #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
928 pub fn cloned(self) -> Result<T, E> {
929 self.map(|t| t.clone())
933 impl<T, E: fmt::Debug> Result<T, E> {
934 /// Unwraps a result, yielding the content of an [`Ok`].
938 /// Panics if the value is an [`Err`], with a panic message provided by the
941 /// [`Ok`]: enum.Result.html#variant.Ok
942 /// [`Err`]: enum.Result.html#variant.Err
949 /// let x: Result<u32, &str> = Ok(2);
950 /// assert_eq!(x.unwrap(), 2);
953 /// ```{.should_panic}
954 /// let x: Result<u32, &str> = Err("emergency failure");
955 /// x.unwrap(); // panics with `emergency failure`
959 #[stable(feature = "rust1", since = "1.0.0")]
960 pub fn unwrap(self) -> T {
963 Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e),
967 /// Unwraps a result, yielding the content of an [`Ok`].
971 /// Panics if the value is an [`Err`], with a panic message including the
972 /// passed message, and the content of the [`Err`].
974 /// [`Ok`]: enum.Result.html#variant.Ok
975 /// [`Err`]: enum.Result.html#variant.Err
981 /// ```{.should_panic}
982 /// let x: Result<u32, &str> = Err("emergency failure");
983 /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
987 #[stable(feature = "result_expect", since = "1.4.0")]
988 pub fn expect(self, msg: &str) -> T {
991 Err(e) => unwrap_failed(msg, &e),
996 impl<T: fmt::Debug, E> Result<T, E> {
997 /// Unwraps a result, yielding the content of an [`Err`].
1001 /// Panics if the value is an [`Ok`], with a custom panic message provided
1002 /// by the [`Ok`]'s value.
1004 /// [`Ok`]: enum.Result.html#variant.Ok
1005 /// [`Err`]: enum.Result.html#variant.Err
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),
1029 /// Unwraps a result, yielding the content of an [`Err`].
1033 /// Panics if the value is an [`Ok`], with a panic message including the
1034 /// passed message, and the content of the [`Ok`].
1036 /// [`Ok`]: enum.Result.html#variant.Ok
1037 /// [`Err`]: enum.Result.html#variant.Err
1043 /// ```{.should_panic}
1044 /// let x: Result<u32, &str> = Ok(10);
1045 /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
1049 #[stable(feature = "result_expect_err", since = "1.17.0")]
1050 pub fn expect_err(self, msg: &str) -> E {
1052 Ok(t) => unwrap_failed(msg, &t),
1058 impl<T: Default, E> Result<T, E> {
1059 /// Returns the contained value or a default
1061 /// Consumes the `self` argument then, if [`Ok`], returns the contained
1062 /// value, otherwise if [`Err`], returns the default value for that
1067 /// Converts a string to an integer, turning poorly-formed strings
1068 /// into 0 (the default value for integers). [`parse`] converts
1069 /// a string to any other type that implements [`FromStr`], returning an
1070 /// [`Err`] on error.
1073 /// let good_year_from_input = "1909";
1074 /// let bad_year_from_input = "190blarg";
1075 /// let good_year = good_year_from_input.parse().unwrap_or_default();
1076 /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
1078 /// assert_eq!(1909, good_year);
1079 /// assert_eq!(0, bad_year);
1082 /// [`parse`]: ../../std/primitive.str.html#method.parse
1083 /// [`FromStr`]: ../../std/str/trait.FromStr.html
1084 /// [`Ok`]: enum.Result.html#variant.Ok
1085 /// [`Err`]: enum.Result.html#variant.Err
1087 #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
1088 pub fn unwrap_or_default(self) -> T {
1091 Err(_) => Default::default(),
1096 #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
1097 impl<T, E: Into<!>> Result<T, E> {
1098 /// Unwraps a result that can never be an [`Err`], yielding the content of the [`Ok`].
1100 /// Unlike [`unwrap`], this method is known to never panic on the
1101 /// result types it is implemented for. Therefore, it can be used
1102 /// instead of `unwrap` as a maintainability safeguard that will fail
1103 /// to compile if the error type of the `Result` is later changed
1104 /// to an error that can actually occur.
1106 /// [`Ok`]: enum.Result.html#variant.Ok
1107 /// [`Err`]: enum.Result.html#variant.Err
1108 /// [`unwrap`]: enum.Result.html#method.unwrap
1115 /// # #![feature(never_type)]
1116 /// # #![feature(unwrap_infallible)]
1118 /// fn only_good_news() -> Result<String, !> {
1119 /// Ok("this is fine".into())
1122 /// let s: String = only_good_news().into_ok();
1123 /// println!("{}", s);
1126 pub fn into_ok(self) -> T {
1134 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1135 impl<T: Deref, E> Result<T, E> {
1136 /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&T::Target, &E>`.
1138 /// Leaves the original `Result` in-place, creating a new one containing a reference to the
1139 /// `Ok` type's `Deref::Target` type.
1140 pub fn as_deref(&self) -> Result<&T::Target, &E> {
1141 self.as_ref().map(|t| t.deref())
1145 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1146 impl<T, E: Deref> Result<T, E> {
1147 /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&T, &E::Target>`.
1149 /// Leaves the original `Result` in-place, creating a new one containing a reference to the
1150 /// `Err` type's `Deref::Target` type.
1151 pub fn as_deref_err(&self) -> Result<&T, &E::Target> {
1152 self.as_ref().map_err(|e| e.deref())
1156 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1157 impl<T: DerefMut, E> Result<T, E> {
1158 /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut T::Target, &mut E>`.
1160 /// Leaves the original `Result` in-place, creating a new one containing a mutable reference to
1161 /// the `Ok` type's `Deref::Target` type.
1162 pub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E> {
1163 self.as_mut().map(|t| t.deref_mut())
1167 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1168 impl<T, E: DerefMut> Result<T, E> {
1169 /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut T, &mut E::Target>`.
1171 /// Leaves the original `Result` in-place, creating a new one containing a mutable reference to
1172 /// the `Err` type's `Deref::Target` type.
1173 pub fn as_deref_mut_err(&mut self) -> Result<&mut T, &mut E::Target> {
1174 self.as_mut().map_err(|e| e.deref_mut())
1178 impl<T, E> Result<Option<T>, E> {
1179 /// Transposes a `Result` of an `Option` into an `Option` of a `Result`.
1181 /// `Ok(None)` will be mapped to `None`.
1182 /// `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`.
1187 /// #[derive(Debug, Eq, PartialEq)]
1190 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1191 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1192 /// assert_eq!(x.transpose(), y);
1195 #[stable(feature = "transpose_result", since = "1.33.0")]
1196 pub fn transpose(self) -> Option<Result<T, E>> {
1198 Ok(Some(x)) => Some(Ok(x)),
1200 Err(e) => Some(Err(e)),
1205 // This is a separate function to reduce the code size of the methods
1209 fn unwrap_failed(msg: &str, error: &dyn fmt::Debug) -> ! {
1210 panic!("{}: {:?}", msg, error)
1213 /////////////////////////////////////////////////////////////////////////////
1214 // Trait implementations
1215 /////////////////////////////////////////////////////////////////////////////
1217 #[stable(feature = "rust1", since = "1.0.0")]
1218 impl<T: Clone, E: Clone> Clone for Result<T, E> {
1220 fn clone(&self) -> Self {
1222 Ok(x) => Ok(x.clone()),
1223 Err(x) => Err(x.clone()),
1228 fn clone_from(&mut self, source: &Self) {
1229 match (self, source) {
1230 (Ok(to), Ok(from)) => to.clone_from(from),
1231 (Err(to), Err(from)) => to.clone_from(from),
1232 (to, from) => *to = from.clone(),
1237 #[stable(feature = "rust1", since = "1.0.0")]
1238 impl<T, E> IntoIterator for Result<T, E> {
1240 type IntoIter = IntoIter<T>;
1242 /// Returns a consuming iterator over the possibly contained value.
1244 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
1251 /// let x: Result<u32, &str> = Ok(5);
1252 /// let v: Vec<u32> = x.into_iter().collect();
1253 /// assert_eq!(v, [5]);
1255 /// let x: Result<u32, &str> = Err("nothing!");
1256 /// let v: Vec<u32> = x.into_iter().collect();
1257 /// assert_eq!(v, []);
1260 fn into_iter(self) -> IntoIter<T> {
1261 IntoIter { inner: self.ok() }
1265 #[stable(since = "1.4.0", feature = "result_iter")]
1266 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
1268 type IntoIter = Iter<'a, T>;
1270 fn into_iter(self) -> Iter<'a, T> {
1275 #[stable(since = "1.4.0", feature = "result_iter")]
1276 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
1277 type Item = &'a mut T;
1278 type IntoIter = IterMut<'a, T>;
1280 fn into_iter(self) -> IterMut<'a, T> {
1285 /////////////////////////////////////////////////////////////////////////////
1286 // The Result Iterators
1287 /////////////////////////////////////////////////////////////////////////////
1289 /// An iterator over a reference to the [`Ok`] variant of a [`Result`].
1291 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1293 /// Created by [`Result::iter`].
1295 /// [`Ok`]: enum.Result.html#variant.Ok
1296 /// [`Result`]: enum.Result.html
1297 /// [`Result::iter`]: enum.Result.html#method.iter
1299 #[stable(feature = "rust1", since = "1.0.0")]
1300 pub struct Iter<'a, T: 'a> {
1301 inner: Option<&'a T>,
1304 #[stable(feature = "rust1", since = "1.0.0")]
1305 impl<'a, T> Iterator for Iter<'a, T> {
1309 fn next(&mut self) -> Option<&'a T> {
1313 fn size_hint(&self) -> (usize, Option<usize>) {
1314 let n = if self.inner.is_some() { 1 } else { 0 };
1319 #[stable(feature = "rust1", since = "1.0.0")]
1320 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1322 fn next_back(&mut self) -> Option<&'a T> {
1327 #[stable(feature = "rust1", since = "1.0.0")]
1328 impl<T> ExactSizeIterator for Iter<'_, T> {}
1330 #[stable(feature = "fused", since = "1.26.0")]
1331 impl<T> FusedIterator for Iter<'_, T> {}
1333 #[unstable(feature = "trusted_len", issue = "37572")]
1334 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1336 #[stable(feature = "rust1", since = "1.0.0")]
1337 impl<T> Clone for Iter<'_, T> {
1339 fn clone(&self) -> Self {
1340 Iter { inner: self.inner }
1344 /// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
1346 /// Created by [`Result::iter_mut`].
1348 /// [`Ok`]: enum.Result.html#variant.Ok
1349 /// [`Result`]: enum.Result.html
1350 /// [`Result::iter_mut`]: enum.Result.html#method.iter_mut
1352 #[stable(feature = "rust1", since = "1.0.0")]
1353 pub struct IterMut<'a, T: 'a> {
1354 inner: Option<&'a mut T>,
1357 #[stable(feature = "rust1", since = "1.0.0")]
1358 impl<'a, T> Iterator for IterMut<'a, T> {
1359 type Item = &'a mut T;
1362 fn next(&mut self) -> Option<&'a mut T> {
1366 fn size_hint(&self) -> (usize, Option<usize>) {
1367 let n = if self.inner.is_some() { 1 } else { 0 };
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1375 fn next_back(&mut self) -> Option<&'a mut T> {
1380 #[stable(feature = "rust1", since = "1.0.0")]
1381 impl<T> ExactSizeIterator for IterMut<'_, T> {}
1383 #[stable(feature = "fused", since = "1.26.0")]
1384 impl<T> FusedIterator for IterMut<'_, T> {}
1386 #[unstable(feature = "trusted_len", issue = "37572")]
1387 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1389 /// An iterator over the value in a [`Ok`] variant of a [`Result`].
1391 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1393 /// This struct is created by the [`into_iter`] method on
1394 /// [`Result`] (provided by the [`IntoIterator`] trait).
1396 /// [`Ok`]: enum.Result.html#variant.Ok
1397 /// [`Result`]: enum.Result.html
1398 /// [`into_iter`]: ../iter/trait.IntoIterator.html#tymethod.into_iter
1399 /// [`IntoIterator`]: ../iter/trait.IntoIterator.html
1400 #[derive(Clone, Debug)]
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 pub struct IntoIter<T> {
1406 #[stable(feature = "rust1", since = "1.0.0")]
1407 impl<T> Iterator for IntoIter<T> {
1411 fn next(&mut self) -> Option<T> {
1415 fn size_hint(&self) -> (usize, Option<usize>) {
1416 let n = if self.inner.is_some() { 1 } else { 0 };
1421 #[stable(feature = "rust1", since = "1.0.0")]
1422 impl<T> DoubleEndedIterator for IntoIter<T> {
1424 fn next_back(&mut self) -> Option<T> {
1429 #[stable(feature = "rust1", since = "1.0.0")]
1430 impl<T> ExactSizeIterator for IntoIter<T> {}
1432 #[stable(feature = "fused", since = "1.26.0")]
1433 impl<T> FusedIterator for IntoIter<T> {}
1435 #[unstable(feature = "trusted_len", issue = "37572")]
1436 unsafe impl<A> TrustedLen for IntoIter<A> {}
1438 /////////////////////////////////////////////////////////////////////////////
1440 /////////////////////////////////////////////////////////////////////////////
1442 #[stable(feature = "rust1", since = "1.0.0")]
1443 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
1444 /// Takes each element in the `Iterator`: if it is an `Err`, no further
1445 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
1446 /// container with the values of each `Result` is returned.
1448 /// Here is an example which increments every integer in a vector,
1449 /// checking for overflow:
1452 /// let v = vec![1, 2];
1453 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1454 /// x.checked_add(1).ok_or("Overflow!")
1456 /// assert_eq!(res, Ok(vec![2, 3]));
1459 /// Here is another example that tries to subtract one from another list
1460 /// of integers, this time checking for underflow:
1463 /// let v = vec![1, 2, 0];
1464 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1465 /// x.checked_sub(1).ok_or("Underflow!")
1467 /// assert_eq!(res, Err("Underflow!"));
1470 /// Here is a variation on the previous example, showing that no
1471 /// further elements are taken from `iter` after the first `Err`.
1474 /// let v = vec![3, 2, 1, 10];
1475 /// let mut shared = 0;
1476 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {
1478 /// x.checked_sub(2).ok_or("Underflow!")
1480 /// assert_eq!(res, Err("Underflow!"));
1481 /// assert_eq!(shared, 6);
1484 /// Since the third element caused an underflow, no further elements were taken,
1485 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1487 fn from_iter<I: IntoIterator<Item = Result<A, E>>>(iter: I) -> Result<V, E> {
1488 // FIXME(#11084): This could be replaced with Iterator::scan when this
1489 // performance bug is closed.
1491 iter::process_results(iter.into_iter(), |i| i.collect())
1495 #[unstable(feature = "try_trait", issue = "42327")]
1496 impl<T, E> ops::Try for Result<T, E> {
1501 fn into_result(self) -> Self {
1506 fn from_ok(v: T) -> Self {
1511 fn from_error(v: E) -> Self {