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")]
233 use crate::iter::{self, FromIterator, FusedIterator, TrustedLen};
234 use crate::ops::{self, Deref, DerefMut};
235 use crate::{convert, fmt};
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 [`Ok`]),
525 /// or returns the provided default (if [`Err`]).
527 /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
528 /// the result of a function call, it is recommended to use [`map_or_else`],
529 /// which is lazily evaluated.
531 /// [`map_or_else`]: #method.map_or_else
532 /// [`Ok`]: enum.Result.html#variant.Ok
533 /// [`Err`]: enum.Result.html#variant.Err
538 /// let x: Result<_, &str> = Ok("foo");
539 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
541 /// let x: Result<&str, _> = Err("bar");
542 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
545 #[stable(feature = "result_map_or", since = "1.41.0")]
546 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
553 /// Maps a `Result<T, E>` to `U` by applying a function to a
554 /// contained [`Ok`] value, or a fallback function to a
555 /// contained [`Err`] value.
557 /// This function can be used to unpack a successful result
558 /// while handling an error.
560 /// [`Ok`]: enum.Result.html#variant.Ok
561 /// [`Err`]: enum.Result.html#variant.Err
570 /// let x : Result<_, &str> = Ok("foo");
571 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);
573 /// let x : Result<&str, _> = Err("bar");
574 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
577 #[stable(feature = "result_map_or_else", since = "1.41.0")]
578 pub fn map_or_else<U, D: FnOnce(E) -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
581 Err(e) => default(e),
585 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
586 /// contained [`Err`] value, leaving an [`Ok`] value untouched.
588 /// This function can be used to pass through a successful result while handling
591 /// [`Ok`]: enum.Result.html#variant.Ok
592 /// [`Err`]: enum.Result.html#variant.Err
599 /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
601 /// let x: Result<u32, u32> = Ok(2);
602 /// assert_eq!(x.map_err(stringify), Ok(2));
604 /// let x: Result<u32, u32> = Err(13);
605 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
608 #[stable(feature = "rust1", since = "1.0.0")]
609 pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T, F> {
612 Err(e) => Err(op(e)),
616 /////////////////////////////////////////////////////////////////////////
617 // Iterator constructors
618 /////////////////////////////////////////////////////////////////////////
620 /// Returns an iterator over the possibly contained value.
622 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
629 /// let x: Result<u32, &str> = Ok(7);
630 /// assert_eq!(x.iter().next(), Some(&7));
632 /// let x: Result<u32, &str> = Err("nothing!");
633 /// assert_eq!(x.iter().next(), None);
636 #[stable(feature = "rust1", since = "1.0.0")]
637 pub fn iter(&self) -> Iter<'_, T> {
638 Iter { inner: self.as_ref().ok() }
641 /// Returns a mutable iterator over the possibly contained value.
643 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
650 /// let mut x: Result<u32, &str> = Ok(7);
651 /// match x.iter_mut().next() {
652 /// Some(v) => *v = 40,
655 /// assert_eq!(x, Ok(40));
657 /// let mut x: Result<u32, &str> = Err("nothing!");
658 /// assert_eq!(x.iter_mut().next(), None);
661 #[stable(feature = "rust1", since = "1.0.0")]
662 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
663 IterMut { inner: self.as_mut().ok() }
666 ////////////////////////////////////////////////////////////////////////
667 // Boolean operations on the values, eager and lazy
668 /////////////////////////////////////////////////////////////////////////
670 /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
672 /// [`Ok`]: enum.Result.html#variant.Ok
673 /// [`Err`]: enum.Result.html#variant.Err
680 /// let x: Result<u32, &str> = Ok(2);
681 /// let y: Result<&str, &str> = Err("late error");
682 /// assert_eq!(x.and(y), Err("late error"));
684 /// let x: Result<u32, &str> = Err("early error");
685 /// let y: Result<&str, &str> = Ok("foo");
686 /// assert_eq!(x.and(y), Err("early error"));
688 /// let x: Result<u32, &str> = Err("not a 2");
689 /// let y: Result<&str, &str> = Err("late error");
690 /// assert_eq!(x.and(y), Err("not a 2"));
692 /// let x: Result<u32, &str> = Ok(2);
693 /// let y: Result<&str, &str> = Ok("different result type");
694 /// assert_eq!(x.and(y), Ok("different result type"));
697 #[stable(feature = "rust1", since = "1.0.0")]
698 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
705 /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
707 /// [`Ok`]: enum.Result.html#variant.Ok
708 /// [`Err`]: enum.Result.html#variant.Err
710 /// This function can be used for control flow based on `Result` values.
717 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
718 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
720 /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
721 /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
722 /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
723 /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
726 #[stable(feature = "rust1", since = "1.0.0")]
727 pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
734 /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
736 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
737 /// result of a function call, it is recommended to use [`or_else`], which is
738 /// lazily evaluated.
740 /// [`Ok`]: enum.Result.html#variant.Ok
741 /// [`Err`]: enum.Result.html#variant.Err
742 /// [`or_else`]: #method.or_else
749 /// let x: Result<u32, &str> = Ok(2);
750 /// let y: Result<u32, &str> = Err("late error");
751 /// assert_eq!(x.or(y), Ok(2));
753 /// let x: Result<u32, &str> = Err("early error");
754 /// let y: Result<u32, &str> = Ok(2);
755 /// assert_eq!(x.or(y), Ok(2));
757 /// let x: Result<u32, &str> = Err("not a 2");
758 /// let y: Result<u32, &str> = Err("late error");
759 /// assert_eq!(x.or(y), Err("late error"));
761 /// let x: Result<u32, &str> = Ok(2);
762 /// let y: Result<u32, &str> = Ok(100);
763 /// assert_eq!(x.or(y), Ok(2));
766 #[stable(feature = "rust1", since = "1.0.0")]
767 pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
774 /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
776 /// This function can be used for control flow based on result values.
778 /// [`Ok`]: enum.Result.html#variant.Ok
779 /// [`Err`]: enum.Result.html#variant.Err
786 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
787 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
789 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
790 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
791 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
792 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
795 #[stable(feature = "rust1", since = "1.0.0")]
796 pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
803 /// Returns the contained [`Ok`] value or a provided default.
805 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
806 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
807 /// which is lazily evaluated.
809 /// [`Ok`]: enum.Result.html#variant.Ok
810 /// [`Err`]: enum.Result.html#variant.Err
811 /// [`unwrap_or_else`]: #method.unwrap_or_else
819 /// let x: Result<u32, &str> = Ok(9);
820 /// assert_eq!(x.unwrap_or(default), 9);
822 /// let x: Result<u32, &str> = Err("error");
823 /// assert_eq!(x.unwrap_or(default), default);
826 #[stable(feature = "rust1", since = "1.0.0")]
827 pub fn unwrap_or(self, default: T) -> T {
834 /// Returns the contained [`Ok`] value or computes it from a closure.
836 /// [`Ok`]: enum.Result.html#variant.Ok
843 /// fn count(x: &str) -> usize { x.len() }
845 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
846 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
849 #[stable(feature = "rust1", since = "1.0.0")]
850 pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
858 impl<T: Copy, E> Result<&T, E> {
859 /// Maps a `Result<&T, E>` to a `Result<T, E>` by copying the contents of the
865 /// #![feature(result_copied)]
867 /// let x: Result<&i32, i32> = Ok(&val);
868 /// assert_eq!(x, Ok(&12));
869 /// let copied = x.copied();
870 /// assert_eq!(copied, Ok(12));
872 #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
873 pub fn copied(self) -> Result<T, E> {
878 impl<T: Copy, E> Result<&mut T, E> {
879 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by copying the contents of the
885 /// #![feature(result_copied)]
886 /// let mut val = 12;
887 /// let x: Result<&mut i32, i32> = Ok(&mut val);
888 /// assert_eq!(x, Ok(&mut 12));
889 /// let copied = x.copied();
890 /// assert_eq!(copied, Ok(12));
892 #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
893 pub fn copied(self) -> Result<T, E> {
898 impl<T: Clone, E> Result<&T, E> {
899 /// Maps a `Result<&T, E>` to a `Result<T, E>` by cloning the contents of the
905 /// #![feature(result_cloned)]
907 /// let x: Result<&i32, i32> = Ok(&val);
908 /// assert_eq!(x, Ok(&12));
909 /// let cloned = x.cloned();
910 /// assert_eq!(cloned, Ok(12));
912 #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
913 pub fn cloned(self) -> Result<T, E> {
914 self.map(|t| t.clone())
918 impl<T: Clone, E> Result<&mut T, E> {
919 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by cloning the contents of the
925 /// #![feature(result_cloned)]
926 /// let mut val = 12;
927 /// let x: Result<&mut i32, i32> = Ok(&mut val);
928 /// assert_eq!(x, Ok(&mut 12));
929 /// let cloned = x.cloned();
930 /// assert_eq!(cloned, Ok(12));
932 #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
933 pub fn cloned(self) -> Result<T, E> {
934 self.map(|t| t.clone())
938 impl<T, E: fmt::Debug> Result<T, E> {
939 /// Returns the contained [`Ok`] value, consuming the `self` value.
943 /// Panics if the value is an [`Err`], with a panic message including the
944 /// passed message, and the content of the [`Err`].
946 /// [`Ok`]: enum.Result.html#variant.Ok
947 /// [`Err`]: enum.Result.html#variant.Err
953 /// ```{.should_panic}
954 /// let x: Result<u32, &str> = Err("emergency failure");
955 /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
959 #[stable(feature = "result_expect", since = "1.4.0")]
960 pub fn expect(self, msg: &str) -> T {
963 Err(e) => unwrap_failed(msg, &e),
967 /// Returns the contained [`Ok`] value, consuming the `self` value.
969 /// Because this function may panic, its use is generally discouraged.
970 /// Instead, prefer to use pattern matching and handle the [`Err`]
971 /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
972 /// [`unwrap_or_default`].
974 /// [`unwrap_or`]: #method.unwrap_or
975 /// [`unwrap_or_else`]: #method.unwrap_or_else
976 /// [`unwrap_or_default`]: #method.unwrap_or_default
980 /// Panics if the value is an [`Err`], with a panic message provided by the
983 /// [`Ok`]: enum.Result.html#variant.Ok
984 /// [`Err`]: enum.Result.html#variant.Err
991 /// let x: Result<u32, &str> = Ok(2);
992 /// assert_eq!(x.unwrap(), 2);
995 /// ```{.should_panic}
996 /// let x: Result<u32, &str> = Err("emergency failure");
997 /// x.unwrap(); // panics with `emergency failure`
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 pub fn unwrap(self) -> T {
1005 Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e),
1010 impl<T: fmt::Debug, E> Result<T, E> {
1011 /// Returns the contained [`Err`] value, consuming the `self` value.
1015 /// Panics if the value is an [`Ok`], with a panic message including the
1016 /// passed message, and the content of the [`Ok`].
1018 /// [`Ok`]: enum.Result.html#variant.Ok
1019 /// [`Err`]: enum.Result.html#variant.Err
1025 /// ```{.should_panic}
1026 /// let x: Result<u32, &str> = Ok(10);
1027 /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
1031 #[stable(feature = "result_expect_err", since = "1.17.0")]
1032 pub fn expect_err(self, msg: &str) -> E {
1034 Ok(t) => unwrap_failed(msg, &t),
1039 /// Returns the contained [`Err`] value, consuming the `self` value.
1043 /// Panics if the value is an [`Ok`], with a custom panic message provided
1044 /// by the [`Ok`]'s value.
1046 /// [`Ok`]: enum.Result.html#variant.Ok
1047 /// [`Err`]: enum.Result.html#variant.Err
1052 /// ```{.should_panic}
1053 /// let x: Result<u32, &str> = Ok(2);
1054 /// x.unwrap_err(); // panics with `2`
1058 /// let x: Result<u32, &str> = Err("emergency failure");
1059 /// assert_eq!(x.unwrap_err(), "emergency failure");
1063 #[stable(feature = "rust1", since = "1.0.0")]
1064 pub fn unwrap_err(self) -> E {
1066 Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t),
1072 impl<T: Default, E> Result<T, E> {
1073 /// Returns the contained [`Ok`] value or a default
1075 /// Consumes the `self` argument then, if [`Ok`], returns the contained
1076 /// value, otherwise if [`Err`], returns the default value for that
1081 /// Converts a string to an integer, turning poorly-formed strings
1082 /// into 0 (the default value for integers). [`parse`] converts
1083 /// a string to any other type that implements [`FromStr`], returning an
1084 /// [`Err`] on error.
1087 /// let good_year_from_input = "1909";
1088 /// let bad_year_from_input = "190blarg";
1089 /// let good_year = good_year_from_input.parse().unwrap_or_default();
1090 /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
1092 /// assert_eq!(1909, good_year);
1093 /// assert_eq!(0, bad_year);
1096 /// [`parse`]: ../../std/primitive.str.html#method.parse
1097 /// [`FromStr`]: ../../std/str/trait.FromStr.html
1098 /// [`Ok`]: enum.Result.html#variant.Ok
1099 /// [`Err`]: enum.Result.html#variant.Err
1101 #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
1102 pub fn unwrap_or_default(self) -> T {
1105 Err(_) => Default::default(),
1110 #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
1111 impl<T, E: Into<!>> Result<T, E> {
1112 /// Returns the contained [`Ok`] value, but never panics.
1114 /// Unlike [`unwrap`], this method is known to never panic on the
1115 /// result types it is implemented for. Therefore, it can be used
1116 /// instead of `unwrap` as a maintainability safeguard that will fail
1117 /// to compile if the error type of the `Result` is later changed
1118 /// to an error that can actually occur.
1120 /// [`Ok`]: enum.Result.html#variant.Ok
1121 /// [`Err`]: enum.Result.html#variant.Err
1122 /// [`unwrap`]: enum.Result.html#method.unwrap
1129 /// # #![feature(never_type)]
1130 /// # #![feature(unwrap_infallible)]
1132 /// fn only_good_news() -> Result<String, !> {
1133 /// Ok("this is fine".into())
1136 /// let s: String = only_good_news().into_ok();
1137 /// println!("{}", s);
1140 pub fn into_ok(self) -> T {
1148 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1149 impl<T: Deref, E> Result<T, E> {
1150 /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&T::Target, &E>`.
1152 /// Leaves the original `Result` in-place, creating a new one containing a reference to the
1153 /// `Ok` type's `Deref::Target` type.
1154 pub fn as_deref(&self) -> Result<&T::Target, &E> {
1155 self.as_ref().map(|t| t.deref())
1159 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1160 impl<T, E: Deref> Result<T, E> {
1161 /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&T, &E::Target>`.
1163 /// Leaves the original `Result` in-place, creating a new one containing a reference to the
1164 /// `Err` type's `Deref::Target` type.
1165 pub fn as_deref_err(&self) -> Result<&T, &E::Target> {
1166 self.as_ref().map_err(|e| e.deref())
1170 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1171 impl<T: DerefMut, E> Result<T, E> {
1172 /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut T::Target, &mut E>`.
1174 /// Leaves the original `Result` in-place, creating a new one containing a mutable reference to
1175 /// the `Ok` type's `Deref::Target` type.
1176 pub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E> {
1177 self.as_mut().map(|t| t.deref_mut())
1181 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1182 impl<T, E: DerefMut> Result<T, E> {
1183 /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut T, &mut E::Target>`.
1185 /// Leaves the original `Result` in-place, creating a new one containing a mutable reference to
1186 /// the `Err` type's `Deref::Target` type.
1187 pub fn as_deref_mut_err(&mut self) -> Result<&mut T, &mut E::Target> {
1188 self.as_mut().map_err(|e| e.deref_mut())
1192 impl<T, E> Result<Option<T>, E> {
1193 /// Transposes a `Result` of an `Option` into an `Option` of a `Result`.
1195 /// `Ok(None)` will be mapped to `None`.
1196 /// `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`.
1201 /// #[derive(Debug, Eq, PartialEq)]
1204 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1205 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1206 /// assert_eq!(x.transpose(), y);
1209 #[stable(feature = "transpose_result", since = "1.33.0")]
1210 pub fn transpose(self) -> Option<Result<T, E>> {
1212 Ok(Some(x)) => Some(Ok(x)),
1214 Err(e) => Some(Err(e)),
1219 impl<T, E> Result<Result<T, E>, E> {
1220 /// Converts from `Result<Result<T, E>, E>` to `Result<T, E>`
1225 /// #![feature(result_flattening)]
1226 /// let x: Result<Result<&'static str, u32>, u32> = Ok(Ok("hello"));
1227 /// assert_eq!(Ok("hello"), x.flatten());
1229 /// let x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));
1230 /// assert_eq!(Err(6), x.flatten());
1232 /// let x: Result<Result<&'static str, u32>, u32> = Err(6);
1233 /// assert_eq!(Err(6), x.flatten());
1236 /// Flattening once only removes one level of nesting:
1239 /// #![feature(result_flattening)]
1240 /// let x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok("hello")));
1241 /// assert_eq!(Ok(Ok("hello")), x.flatten());
1242 /// assert_eq!(Ok("hello"), x.flatten().flatten());
1245 #[unstable(feature = "result_flattening", issue = "70142")]
1246 pub fn flatten(self) -> Result<T, E> {
1247 self.and_then(convert::identity)
1251 // This is a separate function to reduce the code size of the methods
1255 fn unwrap_failed(msg: &str, error: &dyn fmt::Debug) -> ! {
1256 panic!("{}: {:?}", msg, error)
1259 /////////////////////////////////////////////////////////////////////////////
1260 // Trait implementations
1261 /////////////////////////////////////////////////////////////////////////////
1263 #[stable(feature = "rust1", since = "1.0.0")]
1264 impl<T: Clone, E: Clone> Clone for Result<T, E> {
1266 fn clone(&self) -> Self {
1268 Ok(x) => Ok(x.clone()),
1269 Err(x) => Err(x.clone()),
1274 fn clone_from(&mut self, source: &Self) {
1275 match (self, source) {
1276 (Ok(to), Ok(from)) => to.clone_from(from),
1277 (Err(to), Err(from)) => to.clone_from(from),
1278 (to, from) => *to = from.clone(),
1283 #[stable(feature = "rust1", since = "1.0.0")]
1284 impl<T, E> IntoIterator for Result<T, E> {
1286 type IntoIter = IntoIter<T>;
1288 /// Returns a consuming iterator over the possibly contained value.
1290 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
1297 /// let x: Result<u32, &str> = Ok(5);
1298 /// let v: Vec<u32> = x.into_iter().collect();
1299 /// assert_eq!(v, [5]);
1301 /// let x: Result<u32, &str> = Err("nothing!");
1302 /// let v: Vec<u32> = x.into_iter().collect();
1303 /// assert_eq!(v, []);
1306 fn into_iter(self) -> IntoIter<T> {
1307 IntoIter { inner: self.ok() }
1311 #[stable(since = "1.4.0", feature = "result_iter")]
1312 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
1314 type IntoIter = Iter<'a, T>;
1316 fn into_iter(self) -> Iter<'a, T> {
1321 #[stable(since = "1.4.0", feature = "result_iter")]
1322 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
1323 type Item = &'a mut T;
1324 type IntoIter = IterMut<'a, T>;
1326 fn into_iter(self) -> IterMut<'a, T> {
1331 /////////////////////////////////////////////////////////////////////////////
1332 // The Result Iterators
1333 /////////////////////////////////////////////////////////////////////////////
1335 /// An iterator over a reference to the [`Ok`] variant of a [`Result`].
1337 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1339 /// Created by [`Result::iter`].
1341 /// [`Ok`]: enum.Result.html#variant.Ok
1342 /// [`Result`]: enum.Result.html
1343 /// [`Result::iter`]: enum.Result.html#method.iter
1345 #[stable(feature = "rust1", since = "1.0.0")]
1346 pub struct Iter<'a, T: 'a> {
1347 inner: Option<&'a T>,
1350 #[stable(feature = "rust1", since = "1.0.0")]
1351 impl<'a, T> Iterator for Iter<'a, T> {
1355 fn next(&mut self) -> Option<&'a T> {
1359 fn size_hint(&self) -> (usize, Option<usize>) {
1360 let n = if self.inner.is_some() { 1 } else { 0 };
1365 #[stable(feature = "rust1", since = "1.0.0")]
1366 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1368 fn next_back(&mut self) -> Option<&'a T> {
1373 #[stable(feature = "rust1", since = "1.0.0")]
1374 impl<T> ExactSizeIterator for Iter<'_, T> {}
1376 #[stable(feature = "fused", since = "1.26.0")]
1377 impl<T> FusedIterator for Iter<'_, T> {}
1379 #[unstable(feature = "trusted_len", issue = "37572")]
1380 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1382 #[stable(feature = "rust1", since = "1.0.0")]
1383 impl<T> Clone for Iter<'_, T> {
1385 fn clone(&self) -> Self {
1386 Iter { inner: self.inner }
1390 /// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
1392 /// Created by [`Result::iter_mut`].
1394 /// [`Ok`]: enum.Result.html#variant.Ok
1395 /// [`Result`]: enum.Result.html
1396 /// [`Result::iter_mut`]: enum.Result.html#method.iter_mut
1398 #[stable(feature = "rust1", since = "1.0.0")]
1399 pub struct IterMut<'a, T: 'a> {
1400 inner: Option<&'a mut T>,
1403 #[stable(feature = "rust1", since = "1.0.0")]
1404 impl<'a, T> Iterator for IterMut<'a, T> {
1405 type Item = &'a mut T;
1408 fn next(&mut self) -> Option<&'a mut T> {
1412 fn size_hint(&self) -> (usize, Option<usize>) {
1413 let n = if self.inner.is_some() { 1 } else { 0 };
1418 #[stable(feature = "rust1", since = "1.0.0")]
1419 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1421 fn next_back(&mut self) -> Option<&'a mut T> {
1426 #[stable(feature = "rust1", since = "1.0.0")]
1427 impl<T> ExactSizeIterator for IterMut<'_, T> {}
1429 #[stable(feature = "fused", since = "1.26.0")]
1430 impl<T> FusedIterator for IterMut<'_, T> {}
1432 #[unstable(feature = "trusted_len", issue = "37572")]
1433 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1435 /// An iterator over the value in a [`Ok`] variant of a [`Result`].
1437 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1439 /// This struct is created by the [`into_iter`] method on
1440 /// [`Result`] (provided by the [`IntoIterator`] trait).
1442 /// [`Ok`]: enum.Result.html#variant.Ok
1443 /// [`Result`]: enum.Result.html
1444 /// [`into_iter`]: ../iter/trait.IntoIterator.html#tymethod.into_iter
1445 /// [`IntoIterator`]: ../iter/trait.IntoIterator.html
1446 #[derive(Clone, Debug)]
1447 #[stable(feature = "rust1", since = "1.0.0")]
1448 pub struct IntoIter<T> {
1452 #[stable(feature = "rust1", since = "1.0.0")]
1453 impl<T> Iterator for IntoIter<T> {
1457 fn next(&mut self) -> Option<T> {
1461 fn size_hint(&self) -> (usize, Option<usize>) {
1462 let n = if self.inner.is_some() { 1 } else { 0 };
1467 #[stable(feature = "rust1", since = "1.0.0")]
1468 impl<T> DoubleEndedIterator for IntoIter<T> {
1470 fn next_back(&mut self) -> Option<T> {
1475 #[stable(feature = "rust1", since = "1.0.0")]
1476 impl<T> ExactSizeIterator for IntoIter<T> {}
1478 #[stable(feature = "fused", since = "1.26.0")]
1479 impl<T> FusedIterator for IntoIter<T> {}
1481 #[unstable(feature = "trusted_len", issue = "37572")]
1482 unsafe impl<A> TrustedLen for IntoIter<A> {}
1484 /////////////////////////////////////////////////////////////////////////////
1486 /////////////////////////////////////////////////////////////////////////////
1488 #[stable(feature = "rust1", since = "1.0.0")]
1489 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
1490 /// Takes each element in the `Iterator`: if it is an `Err`, no further
1491 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
1492 /// container with the values of each `Result` is returned.
1494 /// Here is an example which increments every integer in a vector,
1495 /// checking for overflow:
1498 /// let v = vec![1, 2];
1499 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1500 /// x.checked_add(1).ok_or("Overflow!")
1502 /// assert_eq!(res, Ok(vec![2, 3]));
1505 /// Here is another example that tries to subtract one from another list
1506 /// of integers, this time checking for underflow:
1509 /// let v = vec![1, 2, 0];
1510 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1511 /// x.checked_sub(1).ok_or("Underflow!")
1513 /// assert_eq!(res, Err("Underflow!"));
1516 /// Here is a variation on the previous example, showing that no
1517 /// further elements are taken from `iter` after the first `Err`.
1520 /// let v = vec![3, 2, 1, 10];
1521 /// let mut shared = 0;
1522 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {
1524 /// x.checked_sub(2).ok_or("Underflow!")
1526 /// assert_eq!(res, Err("Underflow!"));
1527 /// assert_eq!(shared, 6);
1530 /// Since the third element caused an underflow, no further elements were taken,
1531 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1533 fn from_iter<I: IntoIterator<Item = Result<A, E>>>(iter: I) -> Result<V, E> {
1534 // FIXME(#11084): This could be replaced with Iterator::scan when this
1535 // performance bug is closed.
1537 iter::process_results(iter.into_iter(), |i| i.collect())
1541 #[unstable(feature = "try_trait", issue = "42327")]
1542 impl<T, E> ops::Try for Result<T, E> {
1547 fn into_result(self) -> Self {
1552 fn from_ok(v: T) -> Self {
1557 fn from_error(v: E) -> Self {