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 #[stable(feature = "rust1", since = "1.0.0")]
246 pub enum Result<T, E> {
247 /// Contains the success value
248 #[stable(feature = "rust1", since = "1.0.0")]
249 Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
251 /// Contains the error value
252 #[stable(feature = "rust1", since = "1.0.0")]
253 Err(#[stable(feature = "rust1", since = "1.0.0")] E),
256 /////////////////////////////////////////////////////////////////////////////
257 // Type implementation
258 /////////////////////////////////////////////////////////////////////////////
260 impl<T, E> Result<T, E> {
261 /////////////////////////////////////////////////////////////////////////
262 // Querying the contained values
263 /////////////////////////////////////////////////////////////////////////
265 /// Returns `true` if the result is [`Ok`].
267 /// [`Ok`]: enum.Result.html#variant.Ok
274 /// let x: Result<i32, &str> = Ok(-3);
275 /// assert_eq!(x.is_ok(), true);
277 /// let x: Result<i32, &str> = Err("Some error message");
278 /// assert_eq!(x.is_ok(), false);
280 #[must_use = "if you intended to assert that this is ok, consider `.unwrap()` instead"]
281 #[rustc_const_unstable(feature = "const_result", issue = "67520")]
283 #[stable(feature = "rust1", since = "1.0.0")]
284 pub const fn is_ok(&self) -> bool {
285 matches!(*self, Ok(_))
288 /// Returns `true` if the result is [`Err`].
290 /// [`Err`]: enum.Result.html#variant.Err
297 /// let x: Result<i32, &str> = Ok(-3);
298 /// assert_eq!(x.is_err(), false);
300 /// let x: Result<i32, &str> = Err("Some error message");
301 /// assert_eq!(x.is_err(), true);
303 #[must_use = "if you intended to assert that this is err, consider `.unwrap_err()` instead"]
304 #[rustc_const_unstable(feature = "const_result", issue = "67520")]
306 #[stable(feature = "rust1", since = "1.0.0")]
307 pub const fn is_err(&self) -> bool {
311 /// Returns `true` if the result is an [`Ok`] value containing the given value.
316 /// #![feature(option_result_contains)]
318 /// let x: Result<u32, &str> = Ok(2);
319 /// assert_eq!(x.contains(&2), true);
321 /// let x: Result<u32, &str> = Ok(3);
322 /// assert_eq!(x.contains(&2), false);
324 /// let x: Result<u32, &str> = Err("Some error message");
325 /// assert_eq!(x.contains(&2), false);
329 #[unstable(feature = "option_result_contains", issue = "62358")]
330 pub fn contains<U>(&self, x: &U) -> bool
340 /// Returns `true` if the result is an [`Err`] value containing the given value.
345 /// #![feature(result_contains_err)]
347 /// let x: Result<u32, &str> = Ok(2);
348 /// assert_eq!(x.contains_err(&"Some error message"), false);
350 /// let x: Result<u32, &str> = Err("Some error message");
351 /// assert_eq!(x.contains_err(&"Some error message"), true);
353 /// let x: Result<u32, &str> = Err("Some other error message");
354 /// assert_eq!(x.contains_err(&"Some error message"), false);
358 #[unstable(feature = "result_contains_err", issue = "62358")]
359 pub fn contains_err<F>(&self, f: &F) -> bool
369 /////////////////////////////////////////////////////////////////////////
370 // Adapter for each variant
371 /////////////////////////////////////////////////////////////////////////
373 /// Converts from `Result<T, E>` to [`Option<T>`].
375 /// Converts `self` into an [`Option<T>`], consuming `self`,
376 /// and discarding the error, if any.
378 /// [`Option<T>`]: ../../std/option/enum.Option.html
385 /// let x: Result<u32, &str> = Ok(2);
386 /// assert_eq!(x.ok(), Some(2));
388 /// let x: Result<u32, &str> = Err("Nothing here");
389 /// assert_eq!(x.ok(), None);
392 #[stable(feature = "rust1", since = "1.0.0")]
393 pub fn ok(self) -> Option<T> {
400 /// Converts from `Result<T, E>` to [`Option<E>`].
402 /// Converts `self` into an [`Option<E>`], consuming `self`,
403 /// and discarding the success value, if any.
405 /// [`Option<E>`]: ../../std/option/enum.Option.html
412 /// let x: Result<u32, &str> = Ok(2);
413 /// assert_eq!(x.err(), None);
415 /// let x: Result<u32, &str> = Err("Nothing here");
416 /// assert_eq!(x.err(), Some("Nothing here"));
419 #[stable(feature = "rust1", since = "1.0.0")]
420 pub fn err(self) -> Option<E> {
427 /////////////////////////////////////////////////////////////////////////
428 // Adapter for working with references
429 /////////////////////////////////////////////////////////////////////////
431 /// Converts from `&Result<T, E>` to `Result<&T, &E>`.
433 /// Produces a new `Result`, containing a reference
434 /// into the original, leaving the original in place.
441 /// let x: Result<u32, &str> = Ok(2);
442 /// assert_eq!(x.as_ref(), Ok(&2));
444 /// let x: Result<u32, &str> = Err("Error");
445 /// assert_eq!(x.as_ref(), Err(&"Error"));
448 #[rustc_const_unstable(feature = "const_result", issue = "67520")]
449 #[stable(feature = "rust1", since = "1.0.0")]
450 pub const fn as_ref(&self) -> Result<&T, &E> {
453 Err(ref x) => Err(x),
457 /// Converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`.
464 /// fn mutate(r: &mut Result<i32, i32>) {
465 /// match r.as_mut() {
466 /// Ok(v) => *v = 42,
467 /// Err(e) => *e = 0,
471 /// let mut x: Result<i32, i32> = Ok(2);
473 /// assert_eq!(x.unwrap(), 42);
475 /// let mut x: Result<i32, i32> = Err(13);
477 /// assert_eq!(x.unwrap_err(), 0);
480 #[stable(feature = "rust1", since = "1.0.0")]
481 pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
483 Ok(ref mut x) => Ok(x),
484 Err(ref mut x) => Err(x),
488 /////////////////////////////////////////////////////////////////////////
489 // Transforming contained values
490 /////////////////////////////////////////////////////////////////////////
492 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
493 /// contained [`Ok`] value, leaving an [`Err`] value untouched.
495 /// This function can be used to compose the results of two functions.
497 /// [`Ok`]: enum.Result.html#variant.Ok
498 /// [`Err`]: enum.Result.html#variant.Err
502 /// Print the numbers on each line of a string multiplied by two.
505 /// let line = "1\n2\n3\n4\n";
507 /// for num in line.lines() {
508 /// match num.parse::<i32>().map(|i| i * 2) {
509 /// Ok(n) => println!("{}", n),
515 #[stable(feature = "rust1", since = "1.0.0")]
516 pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U, E> {
523 /// Applies a function to the contained value (if any),
524 /// or returns the provided default (if not).
529 /// let x: Result<_, &str> = Ok("foo");
530 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
532 /// let x: Result<&str, _> = Err("bar");
533 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
536 #[stable(feature = "result_map_or", since = "1.41.0")]
537 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
544 /// Maps a `Result<T, E>` to `U` by applying a function to a
545 /// contained [`Ok`] value, or a fallback function to a
546 /// contained [`Err`] value.
548 /// This function can be used to unpack a successful result
549 /// while handling an error.
551 /// [`Ok`]: enum.Result.html#variant.Ok
552 /// [`Err`]: enum.Result.html#variant.Err
561 /// let x : Result<_, &str> = Ok("foo");
562 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);
564 /// let x : Result<&str, _> = Err("bar");
565 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
568 #[stable(feature = "result_map_or_else", since = "1.41.0")]
569 pub fn map_or_else<U, D: FnOnce(E) -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
572 Err(e) => default(e),
576 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
577 /// contained [`Err`] value, leaving an [`Ok`] value untouched.
579 /// This function can be used to pass through a successful result while handling
582 /// [`Ok`]: enum.Result.html#variant.Ok
583 /// [`Err`]: enum.Result.html#variant.Err
590 /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
592 /// let x: Result<u32, u32> = Ok(2);
593 /// assert_eq!(x.map_err(stringify), Ok(2));
595 /// let x: Result<u32, u32> = Err(13);
596 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
599 #[stable(feature = "rust1", since = "1.0.0")]
600 pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T, F> {
603 Err(e) => Err(op(e)),
607 /////////////////////////////////////////////////////////////////////////
608 // Iterator constructors
609 /////////////////////////////////////////////////////////////////////////
611 /// Returns an iterator over the possibly contained value.
613 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
620 /// let x: Result<u32, &str> = Ok(7);
621 /// assert_eq!(x.iter().next(), Some(&7));
623 /// let x: Result<u32, &str> = Err("nothing!");
624 /// assert_eq!(x.iter().next(), None);
627 #[stable(feature = "rust1", since = "1.0.0")]
628 pub fn iter(&self) -> Iter<'_, T> {
629 Iter { inner: self.as_ref().ok() }
632 /// Returns a mutable iterator over the possibly contained value.
634 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
641 /// let mut x: Result<u32, &str> = Ok(7);
642 /// match x.iter_mut().next() {
643 /// Some(v) => *v = 40,
646 /// assert_eq!(x, Ok(40));
648 /// let mut x: Result<u32, &str> = Err("nothing!");
649 /// assert_eq!(x.iter_mut().next(), None);
652 #[stable(feature = "rust1", since = "1.0.0")]
653 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
654 IterMut { inner: self.as_mut().ok() }
657 ////////////////////////////////////////////////////////////////////////
658 // Boolean operations on the values, eager and lazy
659 /////////////////////////////////////////////////////////////////////////
661 /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
663 /// [`Ok`]: enum.Result.html#variant.Ok
664 /// [`Err`]: enum.Result.html#variant.Err
671 /// let x: Result<u32, &str> = Ok(2);
672 /// let y: Result<&str, &str> = Err("late error");
673 /// assert_eq!(x.and(y), Err("late error"));
675 /// let x: Result<u32, &str> = Err("early error");
676 /// let y: Result<&str, &str> = Ok("foo");
677 /// assert_eq!(x.and(y), Err("early error"));
679 /// let x: Result<u32, &str> = Err("not a 2");
680 /// let y: Result<&str, &str> = Err("late error");
681 /// assert_eq!(x.and(y), Err("not a 2"));
683 /// let x: Result<u32, &str> = Ok(2);
684 /// let y: Result<&str, &str> = Ok("different result type");
685 /// assert_eq!(x.and(y), Ok("different result type"));
688 #[stable(feature = "rust1", since = "1.0.0")]
689 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
696 /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
698 /// [`Ok`]: enum.Result.html#variant.Ok
699 /// [`Err`]: enum.Result.html#variant.Err
701 /// This function can be used for control flow based on `Result` values.
708 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
709 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
711 /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
712 /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
713 /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
714 /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
717 #[stable(feature = "rust1", since = "1.0.0")]
718 pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
725 /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
727 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
728 /// result of a function call, it is recommended to use [`or_else`], which is
729 /// lazily evaluated.
731 /// [`Ok`]: enum.Result.html#variant.Ok
732 /// [`Err`]: enum.Result.html#variant.Err
733 /// [`or_else`]: #method.or_else
740 /// let x: Result<u32, &str> = Ok(2);
741 /// let y: Result<u32, &str> = Err("late error");
742 /// assert_eq!(x.or(y), Ok(2));
744 /// let x: Result<u32, &str> = Err("early error");
745 /// let y: Result<u32, &str> = Ok(2);
746 /// assert_eq!(x.or(y), Ok(2));
748 /// let x: Result<u32, &str> = Err("not a 2");
749 /// let y: Result<u32, &str> = Err("late error");
750 /// assert_eq!(x.or(y), Err("late error"));
752 /// let x: Result<u32, &str> = Ok(2);
753 /// let y: Result<u32, &str> = Ok(100);
754 /// assert_eq!(x.or(y), Ok(2));
757 #[stable(feature = "rust1", since = "1.0.0")]
758 pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
765 /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
767 /// This function can be used for control flow based on result values.
769 /// [`Ok`]: enum.Result.html#variant.Ok
770 /// [`Err`]: enum.Result.html#variant.Err
777 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
778 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
780 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
781 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
782 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
783 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
786 #[stable(feature = "rust1", since = "1.0.0")]
787 pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
794 /// Unwraps a result, yielding the content of an [`Ok`].
795 /// Else, it returns `optb`.
797 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
798 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
799 /// which is lazily evaluated.
801 /// [`Ok`]: enum.Result.html#variant.Ok
802 /// [`Err`]: enum.Result.html#variant.Err
803 /// [`unwrap_or_else`]: #method.unwrap_or_else
811 /// let x: Result<u32, &str> = Ok(9);
812 /// assert_eq!(x.unwrap_or(optb), 9);
814 /// let x: Result<u32, &str> = Err("error");
815 /// assert_eq!(x.unwrap_or(optb), optb);
818 #[stable(feature = "rust1", since = "1.0.0")]
819 pub fn unwrap_or(self, optb: T) -> T {
826 /// Unwraps a result, yielding the content of an [`Ok`].
827 /// If the value is an [`Err`] then it calls `op` with its value.
829 /// [`Ok`]: enum.Result.html#variant.Ok
830 /// [`Err`]: enum.Result.html#variant.Err
837 /// fn count(x: &str) -> usize { x.len() }
839 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
840 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
843 #[stable(feature = "rust1", since = "1.0.0")]
844 pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
852 impl<T: Copy, E> Result<&T, E> {
853 /// Maps a `Result<&T, E>` to a `Result<T, E>` by copying the contents of the
859 /// #![feature(result_copied)]
861 /// let x: Result<&i32, i32> = Ok(&val);
862 /// assert_eq!(x, Ok(&12));
863 /// let copied = x.copied();
864 /// assert_eq!(copied, Ok(12));
866 #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
867 pub fn copied(self) -> Result<T, E> {
872 impl<T: Copy, E> Result<&mut T, E> {
873 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by copying the contents of the
879 /// #![feature(result_copied)]
880 /// let mut val = 12;
881 /// let x: Result<&mut i32, i32> = Ok(&mut val);
882 /// assert_eq!(x, Ok(&mut 12));
883 /// let copied = x.copied();
884 /// assert_eq!(copied, Ok(12));
886 #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
887 pub fn copied(self) -> Result<T, E> {
892 impl<T: Clone, E> Result<&T, E> {
893 /// Maps a `Result<&T, E>` to a `Result<T, E>` by cloning the contents of the
899 /// #![feature(result_cloned)]
901 /// let x: Result<&i32, i32> = Ok(&val);
902 /// assert_eq!(x, Ok(&12));
903 /// let cloned = x.cloned();
904 /// assert_eq!(cloned, Ok(12));
906 #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
907 pub fn cloned(self) -> Result<T, E> {
908 self.map(|t| t.clone())
912 impl<T: Clone, E> Result<&mut T, E> {
913 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by cloning the contents of the
919 /// #![feature(result_cloned)]
920 /// let mut val = 12;
921 /// let x: Result<&mut i32, i32> = Ok(&mut val);
922 /// assert_eq!(x, Ok(&mut 12));
923 /// let cloned = x.cloned();
924 /// assert_eq!(cloned, Ok(12));
926 #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
927 pub fn cloned(self) -> Result<T, E> {
928 self.map(|t| t.clone())
932 impl<T, E: fmt::Debug> Result<T, E> {
933 /// Unwraps a result, yielding the content of an [`Ok`].
937 /// Panics if the value is an [`Err`], with a panic message provided by the
940 /// [`Ok`]: enum.Result.html#variant.Ok
941 /// [`Err`]: enum.Result.html#variant.Err
948 /// let x: Result<u32, &str> = Ok(2);
949 /// assert_eq!(x.unwrap(), 2);
952 /// ```{.should_panic}
953 /// let x: Result<u32, &str> = Err("emergency failure");
954 /// x.unwrap(); // panics with `emergency failure`
958 #[stable(feature = "rust1", since = "1.0.0")]
959 pub fn unwrap(self) -> T {
962 Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e),
966 /// Unwraps a result, yielding the content of an [`Ok`].
970 /// Panics if the value is an [`Err`], with a panic message including the
971 /// passed message, and the content of the [`Err`].
973 /// [`Ok`]: enum.Result.html#variant.Ok
974 /// [`Err`]: enum.Result.html#variant.Err
980 /// ```{.should_panic}
981 /// let x: Result<u32, &str> = Err("emergency failure");
982 /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
986 #[stable(feature = "result_expect", since = "1.4.0")]
987 pub fn expect(self, msg: &str) -> T {
990 Err(e) => unwrap_failed(msg, &e),
995 impl<T: fmt::Debug, E> Result<T, E> {
996 /// Unwraps a result, yielding the content of an [`Err`].
1000 /// Panics if the value is an [`Ok`], with a custom panic message provided
1001 /// by the [`Ok`]'s value.
1003 /// [`Ok`]: enum.Result.html#variant.Ok
1004 /// [`Err`]: enum.Result.html#variant.Err
1009 /// ```{.should_panic}
1010 /// let x: Result<u32, &str> = Ok(2);
1011 /// x.unwrap_err(); // panics with `2`
1015 /// let x: Result<u32, &str> = Err("emergency failure");
1016 /// assert_eq!(x.unwrap_err(), "emergency failure");
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 pub fn unwrap_err(self) -> E {
1023 Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t),
1028 /// Unwraps a result, yielding the content of an [`Err`].
1032 /// Panics if the value is an [`Ok`], with a panic message including the
1033 /// passed message, and the content of the [`Ok`].
1035 /// [`Ok`]: enum.Result.html#variant.Ok
1036 /// [`Err`]: enum.Result.html#variant.Err
1042 /// ```{.should_panic}
1043 /// let x: Result<u32, &str> = Ok(10);
1044 /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
1048 #[stable(feature = "result_expect_err", since = "1.17.0")]
1049 pub fn expect_err(self, msg: &str) -> E {
1051 Ok(t) => unwrap_failed(msg, &t),
1057 impl<T: Default, E> Result<T, E> {
1058 /// Returns the contained value or a default
1060 /// Consumes the `self` argument then, if [`Ok`], returns the contained
1061 /// value, otherwise if [`Err`], returns the default value for that
1066 /// Converts a string to an integer, turning poorly-formed strings
1067 /// into 0 (the default value for integers). [`parse`] converts
1068 /// a string to any other type that implements [`FromStr`], returning an
1069 /// [`Err`] on error.
1072 /// let good_year_from_input = "1909";
1073 /// let bad_year_from_input = "190blarg";
1074 /// let good_year = good_year_from_input.parse().unwrap_or_default();
1075 /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
1077 /// assert_eq!(1909, good_year);
1078 /// assert_eq!(0, bad_year);
1081 /// [`parse`]: ../../std/primitive.str.html#method.parse
1082 /// [`FromStr`]: ../../std/str/trait.FromStr.html
1083 /// [`Ok`]: enum.Result.html#variant.Ok
1084 /// [`Err`]: enum.Result.html#variant.Err
1086 #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
1087 pub fn unwrap_or_default(self) -> T {
1090 Err(_) => Default::default(),
1095 #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
1096 impl<T, E: Into<!>> Result<T, E> {
1097 /// Unwraps a result that can never be an [`Err`], yielding the content of the [`Ok`].
1099 /// Unlike [`unwrap`], this method is known to never panic on the
1100 /// result types it is implemented for. Therefore, it can be used
1101 /// instead of `unwrap` as a maintainability safeguard that will fail
1102 /// to compile if the error type of the `Result` is later changed
1103 /// to an error that can actually occur.
1105 /// [`Ok`]: enum.Result.html#variant.Ok
1106 /// [`Err`]: enum.Result.html#variant.Err
1107 /// [`unwrap`]: enum.Result.html#method.unwrap
1114 /// # #![feature(never_type)]
1115 /// # #![feature(unwrap_infallible)]
1117 /// fn only_good_news() -> Result<String, !> {
1118 /// Ok("this is fine".into())
1121 /// let s: String = only_good_news().into_ok();
1122 /// println!("{}", s);
1125 pub fn into_ok(self) -> T {
1133 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1134 impl<T: Deref, E> Result<T, E> {
1135 /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&T::Target, &E>`.
1137 /// Leaves the original `Result` in-place, creating a new one containing a reference to the
1138 /// `Ok` type's `Deref::Target` type.
1139 pub fn as_deref(&self) -> Result<&T::Target, &E> {
1140 self.as_ref().map(|t| t.deref())
1144 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1145 impl<T, E: Deref> Result<T, E> {
1146 /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&T, &E::Target>`.
1148 /// Leaves the original `Result` in-place, creating a new one containing a reference to the
1149 /// `Err` type's `Deref::Target` type.
1150 pub fn as_deref_err(&self) -> Result<&T, &E::Target> {
1151 self.as_ref().map_err(|e| e.deref())
1155 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1156 impl<T: DerefMut, E> Result<T, E> {
1157 /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut T::Target, &mut E>`.
1159 /// Leaves the original `Result` in-place, creating a new one containing a mutable reference to
1160 /// the `Ok` type's `Deref::Target` type.
1161 pub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E> {
1162 self.as_mut().map(|t| t.deref_mut())
1166 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1167 impl<T, E: DerefMut> Result<T, E> {
1168 /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut T, &mut E::Target>`.
1170 /// Leaves the original `Result` in-place, creating a new one containing a mutable reference to
1171 /// the `Err` type's `Deref::Target` type.
1172 pub fn as_deref_mut_err(&mut self) -> Result<&mut T, &mut E::Target> {
1173 self.as_mut().map_err(|e| e.deref_mut())
1177 impl<T, E> Result<Option<T>, E> {
1178 /// Transposes a `Result` of an `Option` into an `Option` of a `Result`.
1180 /// `Ok(None)` will be mapped to `None`.
1181 /// `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`.
1186 /// #[derive(Debug, Eq, PartialEq)]
1189 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1190 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1191 /// assert_eq!(x.transpose(), y);
1194 #[stable(feature = "transpose_result", since = "1.33.0")]
1195 pub fn transpose(self) -> Option<Result<T, E>> {
1197 Ok(Some(x)) => Some(Ok(x)),
1199 Err(e) => Some(Err(e)),
1204 // This is a separate function to reduce the code size of the methods
1208 fn unwrap_failed(msg: &str, error: &dyn fmt::Debug) -> ! {
1209 panic!("{}: {:?}", msg, error)
1212 /////////////////////////////////////////////////////////////////////////////
1213 // Trait implementations
1214 /////////////////////////////////////////////////////////////////////////////
1216 #[stable(feature = "rust1", since = "1.0.0")]
1217 impl<T: Clone, E: Clone> Clone for Result<T, E> {
1219 fn clone(&self) -> Self {
1221 Ok(x) => Ok(x.clone()),
1222 Err(x) => Err(x.clone()),
1227 fn clone_from(&mut self, source: &Self) {
1228 match (self, source) {
1229 (Ok(to), Ok(from)) => to.clone_from(from),
1230 (Err(to), Err(from)) => to.clone_from(from),
1231 (to, from) => *to = from.clone(),
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 impl<T, E> IntoIterator for Result<T, E> {
1239 type IntoIter = IntoIter<T>;
1241 /// Returns a consuming iterator over the possibly contained value.
1243 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
1250 /// let x: Result<u32, &str> = Ok(5);
1251 /// let v: Vec<u32> = x.into_iter().collect();
1252 /// assert_eq!(v, [5]);
1254 /// let x: Result<u32, &str> = Err("nothing!");
1255 /// let v: Vec<u32> = x.into_iter().collect();
1256 /// assert_eq!(v, []);
1259 fn into_iter(self) -> IntoIter<T> {
1260 IntoIter { inner: self.ok() }
1264 #[stable(since = "1.4.0", feature = "result_iter")]
1265 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
1267 type IntoIter = Iter<'a, T>;
1269 fn into_iter(self) -> Iter<'a, T> {
1274 #[stable(since = "1.4.0", feature = "result_iter")]
1275 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
1276 type Item = &'a mut T;
1277 type IntoIter = IterMut<'a, T>;
1279 fn into_iter(self) -> IterMut<'a, T> {
1284 /////////////////////////////////////////////////////////////////////////////
1285 // The Result Iterators
1286 /////////////////////////////////////////////////////////////////////////////
1288 /// An iterator over a reference to the [`Ok`] variant of a [`Result`].
1290 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1292 /// Created by [`Result::iter`].
1294 /// [`Ok`]: enum.Result.html#variant.Ok
1295 /// [`Result`]: enum.Result.html
1296 /// [`Result::iter`]: enum.Result.html#method.iter
1298 #[stable(feature = "rust1", since = "1.0.0")]
1299 pub struct Iter<'a, T: 'a> {
1300 inner: Option<&'a T>,
1303 #[stable(feature = "rust1", since = "1.0.0")]
1304 impl<'a, T> Iterator for Iter<'a, T> {
1308 fn next(&mut self) -> Option<&'a T> {
1312 fn size_hint(&self) -> (usize, Option<usize>) {
1313 let n = if self.inner.is_some() { 1 } else { 0 };
1318 #[stable(feature = "rust1", since = "1.0.0")]
1319 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1321 fn next_back(&mut self) -> Option<&'a T> {
1326 #[stable(feature = "rust1", since = "1.0.0")]
1327 impl<T> ExactSizeIterator for Iter<'_, T> {}
1329 #[stable(feature = "fused", since = "1.26.0")]
1330 impl<T> FusedIterator for Iter<'_, T> {}
1332 #[unstable(feature = "trusted_len", issue = "37572")]
1333 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1335 #[stable(feature = "rust1", since = "1.0.0")]
1336 impl<T> Clone for Iter<'_, T> {
1338 fn clone(&self) -> Self {
1339 Iter { inner: self.inner }
1343 /// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
1345 /// Created by [`Result::iter_mut`].
1347 /// [`Ok`]: enum.Result.html#variant.Ok
1348 /// [`Result`]: enum.Result.html
1349 /// [`Result::iter_mut`]: enum.Result.html#method.iter_mut
1351 #[stable(feature = "rust1", since = "1.0.0")]
1352 pub struct IterMut<'a, T: 'a> {
1353 inner: Option<&'a mut T>,
1356 #[stable(feature = "rust1", since = "1.0.0")]
1357 impl<'a, T> Iterator for IterMut<'a, T> {
1358 type Item = &'a mut T;
1361 fn next(&mut self) -> Option<&'a mut T> {
1365 fn size_hint(&self) -> (usize, Option<usize>) {
1366 let n = if self.inner.is_some() { 1 } else { 0 };
1371 #[stable(feature = "rust1", since = "1.0.0")]
1372 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1374 fn next_back(&mut self) -> Option<&'a mut T> {
1379 #[stable(feature = "rust1", since = "1.0.0")]
1380 impl<T> ExactSizeIterator for IterMut<'_, T> {}
1382 #[stable(feature = "fused", since = "1.26.0")]
1383 impl<T> FusedIterator for IterMut<'_, T> {}
1385 #[unstable(feature = "trusted_len", issue = "37572")]
1386 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1388 /// An iterator over the value in a [`Ok`] variant of a [`Result`].
1390 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1392 /// This struct is created by the [`into_iter`] method on
1393 /// [`Result`] (provided by the [`IntoIterator`] trait).
1395 /// [`Ok`]: enum.Result.html#variant.Ok
1396 /// [`Result`]: enum.Result.html
1397 /// [`into_iter`]: ../iter/trait.IntoIterator.html#tymethod.into_iter
1398 /// [`IntoIterator`]: ../iter/trait.IntoIterator.html
1399 #[derive(Clone, Debug)]
1400 #[stable(feature = "rust1", since = "1.0.0")]
1401 pub struct IntoIter<T> {
1405 #[stable(feature = "rust1", since = "1.0.0")]
1406 impl<T> Iterator for IntoIter<T> {
1410 fn next(&mut self) -> Option<T> {
1414 fn size_hint(&self) -> (usize, Option<usize>) {
1415 let n = if self.inner.is_some() { 1 } else { 0 };
1420 #[stable(feature = "rust1", since = "1.0.0")]
1421 impl<T> DoubleEndedIterator for IntoIter<T> {
1423 fn next_back(&mut self) -> Option<T> {
1428 #[stable(feature = "rust1", since = "1.0.0")]
1429 impl<T> ExactSizeIterator for IntoIter<T> {}
1431 #[stable(feature = "fused", since = "1.26.0")]
1432 impl<T> FusedIterator for IntoIter<T> {}
1434 #[unstable(feature = "trusted_len", issue = "37572")]
1435 unsafe impl<A> TrustedLen for IntoIter<A> {}
1437 /////////////////////////////////////////////////////////////////////////////
1439 /////////////////////////////////////////////////////////////////////////////
1441 #[stable(feature = "rust1", since = "1.0.0")]
1442 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
1443 /// Takes each element in the `Iterator`: if it is an `Err`, no further
1444 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
1445 /// container with the values of each `Result` is returned.
1447 /// Here is an example which increments every integer in a vector,
1448 /// checking for overflow:
1451 /// let v = vec![1, 2];
1452 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1453 /// x.checked_add(1).ok_or("Overflow!")
1455 /// assert_eq!(res, Ok(vec![2, 3]));
1458 /// Here is another example that tries to subtract one from another list
1459 /// of integers, this time checking for underflow:
1462 /// let v = vec![1, 2, 0];
1463 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1464 /// x.checked_sub(1).ok_or("Underflow!")
1466 /// assert_eq!(res, Err("Underflow!"));
1469 /// Here is a variation on the previous example, showing that no
1470 /// further elements are taken from `iter` after the first `Err`.
1473 /// let v = vec![3, 2, 1, 10];
1474 /// let mut shared = 0;
1475 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {
1477 /// x.checked_sub(2).ok_or("Underflow!")
1479 /// assert_eq!(res, Err("Underflow!"));
1480 /// assert_eq!(shared, 6);
1483 /// Since the third element caused an underflow, no further elements were taken,
1484 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1486 fn from_iter<I: IntoIterator<Item = Result<A, E>>>(iter: I) -> Result<V, E> {
1487 // FIXME(#11084): This could be replaced with Iterator::scan when this
1488 // performance bug is closed.
1490 iter::process_results(iter.into_iter(), |i| i.collect())
1494 #[unstable(feature = "try_trait", issue = "42327")]
1495 impl<T, E> ops::Try for Result<T, E> {
1500 fn into_result(self) -> Self {
1505 fn from_ok(v: T) -> Self {
1510 fn from_error(v: E) -> Self {