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).
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
536 /// let x: Result<_, &str> = Ok("foo");
537 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
539 /// let x: Result<&str, _> = Err("bar");
540 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
543 #[stable(feature = "result_map_or", since = "1.41.0")]
544 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
551 /// Maps a `Result<T, E>` to `U` by applying a function to a
552 /// contained [`Ok`] value, or a fallback function to a
553 /// contained [`Err`] value.
555 /// This function can be used to unpack a successful result
556 /// while handling an error.
558 /// [`Ok`]: enum.Result.html#variant.Ok
559 /// [`Err`]: enum.Result.html#variant.Err
568 /// let x : Result<_, &str> = Ok("foo");
569 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);
571 /// let x : Result<&str, _> = Err("bar");
572 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
575 #[stable(feature = "result_map_or_else", since = "1.41.0")]
576 pub fn map_or_else<U, D: FnOnce(E) -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
579 Err(e) => default(e),
583 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
584 /// contained [`Err`] value, leaving an [`Ok`] value untouched.
586 /// This function can be used to pass through a successful result while handling
589 /// [`Ok`]: enum.Result.html#variant.Ok
590 /// [`Err`]: enum.Result.html#variant.Err
597 /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
599 /// let x: Result<u32, u32> = Ok(2);
600 /// assert_eq!(x.map_err(stringify), Ok(2));
602 /// let x: Result<u32, u32> = Err(13);
603 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
606 #[stable(feature = "rust1", since = "1.0.0")]
607 pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T, F> {
610 Err(e) => Err(op(e)),
614 /////////////////////////////////////////////////////////////////////////
615 // Iterator constructors
616 /////////////////////////////////////////////////////////////////////////
618 /// Returns an iterator over the possibly contained value.
620 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
627 /// let x: Result<u32, &str> = Ok(7);
628 /// assert_eq!(x.iter().next(), Some(&7));
630 /// let x: Result<u32, &str> = Err("nothing!");
631 /// assert_eq!(x.iter().next(), None);
634 #[stable(feature = "rust1", since = "1.0.0")]
635 pub fn iter(&self) -> Iter<'_, T> {
636 Iter { inner: self.as_ref().ok() }
639 /// Returns a mutable iterator over the possibly contained value.
641 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
648 /// let mut x: Result<u32, &str> = Ok(7);
649 /// match x.iter_mut().next() {
650 /// Some(v) => *v = 40,
653 /// assert_eq!(x, Ok(40));
655 /// let mut x: Result<u32, &str> = Err("nothing!");
656 /// assert_eq!(x.iter_mut().next(), None);
659 #[stable(feature = "rust1", since = "1.0.0")]
660 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
661 IterMut { inner: self.as_mut().ok() }
664 ////////////////////////////////////////////////////////////////////////
665 // Boolean operations on the values, eager and lazy
666 /////////////////////////////////////////////////////////////////////////
668 /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
670 /// [`Ok`]: enum.Result.html#variant.Ok
671 /// [`Err`]: enum.Result.html#variant.Err
678 /// let x: Result<u32, &str> = Ok(2);
679 /// let y: Result<&str, &str> = Err("late error");
680 /// assert_eq!(x.and(y), Err("late error"));
682 /// let x: Result<u32, &str> = Err("early error");
683 /// let y: Result<&str, &str> = Ok("foo");
684 /// assert_eq!(x.and(y), Err("early error"));
686 /// let x: Result<u32, &str> = Err("not a 2");
687 /// let y: Result<&str, &str> = Err("late error");
688 /// assert_eq!(x.and(y), Err("not a 2"));
690 /// let x: Result<u32, &str> = Ok(2);
691 /// let y: Result<&str, &str> = Ok("different result type");
692 /// assert_eq!(x.and(y), Ok("different result type"));
695 #[stable(feature = "rust1", since = "1.0.0")]
696 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
703 /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
705 /// [`Ok`]: enum.Result.html#variant.Ok
706 /// [`Err`]: enum.Result.html#variant.Err
708 /// This function can be used for control flow based on `Result` values.
715 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
716 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
718 /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
719 /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
720 /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
721 /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
724 #[stable(feature = "rust1", since = "1.0.0")]
725 pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
732 /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
734 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
735 /// result of a function call, it is recommended to use [`or_else`], which is
736 /// lazily evaluated.
738 /// [`Ok`]: enum.Result.html#variant.Ok
739 /// [`Err`]: enum.Result.html#variant.Err
740 /// [`or_else`]: #method.or_else
747 /// let x: Result<u32, &str> = Ok(2);
748 /// let y: Result<u32, &str> = Err("late error");
749 /// assert_eq!(x.or(y), Ok(2));
751 /// let x: Result<u32, &str> = Err("early error");
752 /// let y: Result<u32, &str> = Ok(2);
753 /// assert_eq!(x.or(y), Ok(2));
755 /// let x: Result<u32, &str> = Err("not a 2");
756 /// let y: Result<u32, &str> = Err("late error");
757 /// assert_eq!(x.or(y), Err("late error"));
759 /// let x: Result<u32, &str> = Ok(2);
760 /// let y: Result<u32, &str> = Ok(100);
761 /// assert_eq!(x.or(y), Ok(2));
764 #[stable(feature = "rust1", since = "1.0.0")]
765 pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
772 /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
774 /// This function can be used for control flow based on result values.
776 /// [`Ok`]: enum.Result.html#variant.Ok
777 /// [`Err`]: enum.Result.html#variant.Err
784 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
785 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
787 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
788 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
789 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
790 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
793 #[stable(feature = "rust1", since = "1.0.0")]
794 pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
801 /// Returns the contained [`Ok`] value or a provided default.
803 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
804 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
805 /// which is lazily evaluated.
807 /// [`Ok`]: enum.Result.html#variant.Ok
808 /// [`Err`]: enum.Result.html#variant.Err
809 /// [`unwrap_or_else`]: #method.unwrap_or_else
817 /// let x: Result<u32, &str> = Ok(9);
818 /// assert_eq!(x.unwrap_or(default), 9);
820 /// let x: Result<u32, &str> = Err("error");
821 /// assert_eq!(x.unwrap_or(default), default);
824 #[stable(feature = "rust1", since = "1.0.0")]
825 pub fn unwrap_or(self, default: T) -> T {
832 /// Returns the contained [`Ok`] value or computes it from a closure.
834 /// [`Ok`]: enum.Result.html#variant.Ok
841 /// fn count(x: &str) -> usize { x.len() }
843 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
844 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
847 #[stable(feature = "rust1", since = "1.0.0")]
848 pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
856 impl<T: Copy, E> Result<&T, E> {
857 /// Maps a `Result<&T, E>` to a `Result<T, E>` by copying the contents of the
863 /// #![feature(result_copied)]
865 /// let x: Result<&i32, i32> = Ok(&val);
866 /// assert_eq!(x, Ok(&12));
867 /// let copied = x.copied();
868 /// assert_eq!(copied, Ok(12));
870 #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
871 pub fn copied(self) -> Result<T, E> {
876 impl<T: Copy, E> Result<&mut T, E> {
877 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by copying the contents of the
883 /// #![feature(result_copied)]
884 /// let mut val = 12;
885 /// let x: Result<&mut i32, i32> = Ok(&mut val);
886 /// assert_eq!(x, Ok(&mut 12));
887 /// let copied = x.copied();
888 /// assert_eq!(copied, Ok(12));
890 #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
891 pub fn copied(self) -> Result<T, E> {
896 impl<T: Clone, E> Result<&T, E> {
897 /// Maps a `Result<&T, E>` to a `Result<T, E>` by cloning the contents of the
903 /// #![feature(result_cloned)]
905 /// let x: Result<&i32, i32> = Ok(&val);
906 /// assert_eq!(x, Ok(&12));
907 /// let cloned = x.cloned();
908 /// assert_eq!(cloned, Ok(12));
910 #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
911 pub fn cloned(self) -> Result<T, E> {
912 self.map(|t| t.clone())
916 impl<T: Clone, E> Result<&mut T, E> {
917 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by cloning the contents of the
923 /// #![feature(result_cloned)]
924 /// let mut val = 12;
925 /// let x: Result<&mut i32, i32> = Ok(&mut val);
926 /// assert_eq!(x, Ok(&mut 12));
927 /// let cloned = x.cloned();
928 /// assert_eq!(cloned, Ok(12));
930 #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
931 pub fn cloned(self) -> Result<T, E> {
932 self.map(|t| t.clone())
936 impl<T, E: fmt::Debug> Result<T, E> {
937 /// Returns the contained [`Ok`] value, consuming the `self` value.
941 /// Panics if the value is an [`Err`], with a panic message including the
942 /// passed message, and the content of the [`Err`].
944 /// [`Ok`]: enum.Result.html#variant.Ok
945 /// [`Err`]: enum.Result.html#variant.Err
951 /// ```{.should_panic}
952 /// let x: Result<u32, &str> = Err("emergency failure");
953 /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
957 #[stable(feature = "result_expect", since = "1.4.0")]
958 pub fn expect(self, msg: &str) -> T {
961 Err(e) => unwrap_failed(msg, &e),
965 /// Returns the contained [`Ok`] value, consuming the `self` value.
967 /// Because this function may panic, its use is generally discouraged.
968 /// Instead, prefer to use pattern matching and handle the [`Err`]
969 /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
970 /// [`unwrap_or_default`].
972 /// [`unwrap_or`]: #method.unwrap_or
973 /// [`unwrap_or_else`]: #method.unwrap_or_else
974 /// [`unwrap_or_default`]: #method.unwrap_or_default
978 /// Panics if the value is an [`Err`], with a panic message provided by the
981 /// [`Ok`]: enum.Result.html#variant.Ok
982 /// [`Err`]: enum.Result.html#variant.Err
989 /// let x: Result<u32, &str> = Ok(2);
990 /// assert_eq!(x.unwrap(), 2);
993 /// ```{.should_panic}
994 /// let x: Result<u32, &str> = Err("emergency failure");
995 /// x.unwrap(); // panics with `emergency failure`
999 #[stable(feature = "rust1", since = "1.0.0")]
1000 pub fn unwrap(self) -> T {
1003 Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e),
1008 impl<T: fmt::Debug, E> Result<T, E> {
1009 /// Returns the contained [`Err`] value, consuming the `self` value.
1013 /// Panics if the value is an [`Ok`], with a panic message including the
1014 /// passed message, and the content of the [`Ok`].
1016 /// [`Ok`]: enum.Result.html#variant.Ok
1017 /// [`Err`]: enum.Result.html#variant.Err
1023 /// ```{.should_panic}
1024 /// let x: Result<u32, &str> = Ok(10);
1025 /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
1029 #[stable(feature = "result_expect_err", since = "1.17.0")]
1030 pub fn expect_err(self, msg: &str) -> E {
1032 Ok(t) => unwrap_failed(msg, &t),
1037 /// Returns the contained [`Err`] value, consuming the `self` value.
1041 /// Panics if the value is an [`Ok`], with a custom panic message provided
1042 /// by the [`Ok`]'s value.
1044 /// [`Ok`]: enum.Result.html#variant.Ok
1045 /// [`Err`]: enum.Result.html#variant.Err
1050 /// ```{.should_panic}
1051 /// let x: Result<u32, &str> = Ok(2);
1052 /// x.unwrap_err(); // panics with `2`
1056 /// let x: Result<u32, &str> = Err("emergency failure");
1057 /// assert_eq!(x.unwrap_err(), "emergency failure");
1061 #[stable(feature = "rust1", since = "1.0.0")]
1062 pub fn unwrap_err(self) -> E {
1064 Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t),
1070 impl<T: Default, E> Result<T, E> {
1071 /// Returns the contained [`Ok`] value or a default
1073 /// Consumes the `self` argument then, if [`Ok`], returns the contained
1074 /// value, otherwise if [`Err`], returns the default value for that
1079 /// Converts a string to an integer, turning poorly-formed strings
1080 /// into 0 (the default value for integers). [`parse`] converts
1081 /// a string to any other type that implements [`FromStr`], returning an
1082 /// [`Err`] on error.
1085 /// let good_year_from_input = "1909";
1086 /// let bad_year_from_input = "190blarg";
1087 /// let good_year = good_year_from_input.parse().unwrap_or_default();
1088 /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
1090 /// assert_eq!(1909, good_year);
1091 /// assert_eq!(0, bad_year);
1094 /// [`parse`]: ../../std/primitive.str.html#method.parse
1095 /// [`FromStr`]: ../../std/str/trait.FromStr.html
1096 /// [`Ok`]: enum.Result.html#variant.Ok
1097 /// [`Err`]: enum.Result.html#variant.Err
1099 #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
1100 pub fn unwrap_or_default(self) -> T {
1103 Err(_) => Default::default(),
1108 #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
1109 impl<T, E: Into<!>> Result<T, E> {
1110 /// Returns the contained [`Ok`] value, but never panics.
1112 /// Unlike [`unwrap`], this method is known to never panic on the
1113 /// result types it is implemented for. Therefore, it can be used
1114 /// instead of `unwrap` as a maintainability safeguard that will fail
1115 /// to compile if the error type of the `Result` is later changed
1116 /// to an error that can actually occur.
1118 /// [`Ok`]: enum.Result.html#variant.Ok
1119 /// [`Err`]: enum.Result.html#variant.Err
1120 /// [`unwrap`]: enum.Result.html#method.unwrap
1127 /// # #![feature(never_type)]
1128 /// # #![feature(unwrap_infallible)]
1130 /// fn only_good_news() -> Result<String, !> {
1131 /// Ok("this is fine".into())
1134 /// let s: String = only_good_news().into_ok();
1135 /// println!("{}", s);
1138 pub fn into_ok(self) -> T {
1146 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1147 impl<T: Deref, E> Result<T, E> {
1148 /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&T::Target, &E>`.
1150 /// Leaves the original `Result` in-place, creating a new one containing a reference to the
1151 /// `Ok` type's `Deref::Target` type.
1152 pub fn as_deref(&self) -> Result<&T::Target, &E> {
1153 self.as_ref().map(|t| t.deref())
1157 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1158 impl<T, E: Deref> Result<T, E> {
1159 /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&T, &E::Target>`.
1161 /// Leaves the original `Result` in-place, creating a new one containing a reference to the
1162 /// `Err` type's `Deref::Target` type.
1163 pub fn as_deref_err(&self) -> Result<&T, &E::Target> {
1164 self.as_ref().map_err(|e| e.deref())
1168 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1169 impl<T: DerefMut, E> Result<T, E> {
1170 /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut T::Target, &mut E>`.
1172 /// Leaves the original `Result` in-place, creating a new one containing a mutable reference to
1173 /// the `Ok` type's `Deref::Target` type.
1174 pub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E> {
1175 self.as_mut().map(|t| t.deref_mut())
1179 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1180 impl<T, E: DerefMut> Result<T, E> {
1181 /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut T, &mut E::Target>`.
1183 /// Leaves the original `Result` in-place, creating a new one containing a mutable reference to
1184 /// the `Err` type's `Deref::Target` type.
1185 pub fn as_deref_mut_err(&mut self) -> Result<&mut T, &mut E::Target> {
1186 self.as_mut().map_err(|e| e.deref_mut())
1190 impl<T, E> Result<Option<T>, E> {
1191 /// Transposes a `Result` of an `Option` into an `Option` of a `Result`.
1193 /// `Ok(None)` will be mapped to `None`.
1194 /// `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`.
1199 /// #[derive(Debug, Eq, PartialEq)]
1202 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1203 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1204 /// assert_eq!(x.transpose(), y);
1207 #[stable(feature = "transpose_result", since = "1.33.0")]
1208 pub fn transpose(self) -> Option<Result<T, E>> {
1210 Ok(Some(x)) => Some(Ok(x)),
1212 Err(e) => Some(Err(e)),
1217 // This is a separate function to reduce the code size of the methods
1221 fn unwrap_failed(msg: &str, error: &dyn fmt::Debug) -> ! {
1222 panic!("{}: {:?}", msg, error)
1225 /////////////////////////////////////////////////////////////////////////////
1226 // Trait implementations
1227 /////////////////////////////////////////////////////////////////////////////
1229 #[stable(feature = "rust1", since = "1.0.0")]
1230 impl<T: Clone, E: Clone> Clone for Result<T, E> {
1232 fn clone(&self) -> Self {
1234 Ok(x) => Ok(x.clone()),
1235 Err(x) => Err(x.clone()),
1240 fn clone_from(&mut self, source: &Self) {
1241 match (self, source) {
1242 (Ok(to), Ok(from)) => to.clone_from(from),
1243 (Err(to), Err(from)) => to.clone_from(from),
1244 (to, from) => *to = from.clone(),
1249 #[stable(feature = "rust1", since = "1.0.0")]
1250 impl<T, E> IntoIterator for Result<T, E> {
1252 type IntoIter = IntoIter<T>;
1254 /// Returns a consuming iterator over the possibly contained value.
1256 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
1263 /// let x: Result<u32, &str> = Ok(5);
1264 /// let v: Vec<u32> = x.into_iter().collect();
1265 /// assert_eq!(v, [5]);
1267 /// let x: Result<u32, &str> = Err("nothing!");
1268 /// let v: Vec<u32> = x.into_iter().collect();
1269 /// assert_eq!(v, []);
1272 fn into_iter(self) -> IntoIter<T> {
1273 IntoIter { inner: self.ok() }
1277 #[stable(since = "1.4.0", feature = "result_iter")]
1278 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
1280 type IntoIter = Iter<'a, T>;
1282 fn into_iter(self) -> Iter<'a, T> {
1287 #[stable(since = "1.4.0", feature = "result_iter")]
1288 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
1289 type Item = &'a mut T;
1290 type IntoIter = IterMut<'a, T>;
1292 fn into_iter(self) -> IterMut<'a, T> {
1297 /////////////////////////////////////////////////////////////////////////////
1298 // The Result Iterators
1299 /////////////////////////////////////////////////////////////////////////////
1301 /// An iterator over a reference to the [`Ok`] variant of a [`Result`].
1303 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1305 /// Created by [`Result::iter`].
1307 /// [`Ok`]: enum.Result.html#variant.Ok
1308 /// [`Result`]: enum.Result.html
1309 /// [`Result::iter`]: enum.Result.html#method.iter
1311 #[stable(feature = "rust1", since = "1.0.0")]
1312 pub struct Iter<'a, T: 'a> {
1313 inner: Option<&'a T>,
1316 #[stable(feature = "rust1", since = "1.0.0")]
1317 impl<'a, T> Iterator for Iter<'a, T> {
1321 fn next(&mut self) -> Option<&'a T> {
1325 fn size_hint(&self) -> (usize, Option<usize>) {
1326 let n = if self.inner.is_some() { 1 } else { 0 };
1331 #[stable(feature = "rust1", since = "1.0.0")]
1332 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1334 fn next_back(&mut self) -> Option<&'a T> {
1339 #[stable(feature = "rust1", since = "1.0.0")]
1340 impl<T> ExactSizeIterator for Iter<'_, T> {}
1342 #[stable(feature = "fused", since = "1.26.0")]
1343 impl<T> FusedIterator for Iter<'_, T> {}
1345 #[unstable(feature = "trusted_len", issue = "37572")]
1346 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1348 #[stable(feature = "rust1", since = "1.0.0")]
1349 impl<T> Clone for Iter<'_, T> {
1351 fn clone(&self) -> Self {
1352 Iter { inner: self.inner }
1356 /// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
1358 /// Created by [`Result::iter_mut`].
1360 /// [`Ok`]: enum.Result.html#variant.Ok
1361 /// [`Result`]: enum.Result.html
1362 /// [`Result::iter_mut`]: enum.Result.html#method.iter_mut
1364 #[stable(feature = "rust1", since = "1.0.0")]
1365 pub struct IterMut<'a, T: 'a> {
1366 inner: Option<&'a mut T>,
1369 #[stable(feature = "rust1", since = "1.0.0")]
1370 impl<'a, T> Iterator for IterMut<'a, T> {
1371 type Item = &'a mut T;
1374 fn next(&mut self) -> Option<&'a mut T> {
1378 fn size_hint(&self) -> (usize, Option<usize>) {
1379 let n = if self.inner.is_some() { 1 } else { 0 };
1384 #[stable(feature = "rust1", since = "1.0.0")]
1385 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1387 fn next_back(&mut self) -> Option<&'a mut T> {
1392 #[stable(feature = "rust1", since = "1.0.0")]
1393 impl<T> ExactSizeIterator for IterMut<'_, T> {}
1395 #[stable(feature = "fused", since = "1.26.0")]
1396 impl<T> FusedIterator for IterMut<'_, T> {}
1398 #[unstable(feature = "trusted_len", issue = "37572")]
1399 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1401 /// An iterator over the value in a [`Ok`] variant of a [`Result`].
1403 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1405 /// This struct is created by the [`into_iter`] method on
1406 /// [`Result`] (provided by the [`IntoIterator`] trait).
1408 /// [`Ok`]: enum.Result.html#variant.Ok
1409 /// [`Result`]: enum.Result.html
1410 /// [`into_iter`]: ../iter/trait.IntoIterator.html#tymethod.into_iter
1411 /// [`IntoIterator`]: ../iter/trait.IntoIterator.html
1412 #[derive(Clone, Debug)]
1413 #[stable(feature = "rust1", since = "1.0.0")]
1414 pub struct IntoIter<T> {
1418 #[stable(feature = "rust1", since = "1.0.0")]
1419 impl<T> Iterator for IntoIter<T> {
1423 fn next(&mut self) -> Option<T> {
1427 fn size_hint(&self) -> (usize, Option<usize>) {
1428 let n = if self.inner.is_some() { 1 } else { 0 };
1433 #[stable(feature = "rust1", since = "1.0.0")]
1434 impl<T> DoubleEndedIterator for IntoIter<T> {
1436 fn next_back(&mut self) -> Option<T> {
1441 #[stable(feature = "rust1", since = "1.0.0")]
1442 impl<T> ExactSizeIterator for IntoIter<T> {}
1444 #[stable(feature = "fused", since = "1.26.0")]
1445 impl<T> FusedIterator for IntoIter<T> {}
1447 #[unstable(feature = "trusted_len", issue = "37572")]
1448 unsafe impl<A> TrustedLen for IntoIter<A> {}
1450 /////////////////////////////////////////////////////////////////////////////
1452 /////////////////////////////////////////////////////////////////////////////
1454 #[stable(feature = "rust1", since = "1.0.0")]
1455 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
1456 /// Takes each element in the `Iterator`: if it is an `Err`, no further
1457 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
1458 /// container with the values of each `Result` is returned.
1460 /// Here is an example which increments every integer in a vector,
1461 /// checking for overflow:
1464 /// let v = vec![1, 2];
1465 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1466 /// x.checked_add(1).ok_or("Overflow!")
1468 /// assert_eq!(res, Ok(vec![2, 3]));
1471 /// Here is another example that tries to subtract one from another list
1472 /// of integers, this time checking for underflow:
1475 /// let v = vec![1, 2, 0];
1476 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1477 /// x.checked_sub(1).ok_or("Underflow!")
1479 /// assert_eq!(res, Err("Underflow!"));
1482 /// Here is a variation on the previous example, showing that no
1483 /// further elements are taken from `iter` after the first `Err`.
1486 /// let v = vec![3, 2, 1, 10];
1487 /// let mut shared = 0;
1488 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {
1490 /// x.checked_sub(2).ok_or("Underflow!")
1492 /// assert_eq!(res, Err("Underflow!"));
1493 /// assert_eq!(shared, 6);
1496 /// Since the third element caused an underflow, no further elements were taken,
1497 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1499 fn from_iter<I: IntoIterator<Item = Result<A, E>>>(iter: I) -> Result<V, E> {
1500 // FIXME(#11084): This could be replaced with Iterator::scan when this
1501 // performance bug is closed.
1503 iter::process_results(iter.into_iter(), |i| i.collect())
1507 #[unstable(feature = "try_trait", issue = "42327")]
1508 impl<T, E> ops::Try for Result<T, E> {
1513 fn into_result(self) -> Self {
1518 fn from_ok(v: T) -> Self {
1523 fn from_error(v: E) -> Self {