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"]
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub fn is_ok(&self) -> bool {
290 /// Returns `true` if the result is [`Err`].
292 /// [`Err`]: enum.Result.html#variant.Err
299 /// let x: Result<i32, &str> = Ok(-3);
300 /// assert_eq!(x.is_err(), false);
302 /// let x: Result<i32, &str> = Err("Some error message");
303 /// assert_eq!(x.is_err(), true);
305 #[must_use = "if you intended to assert that this is err, consider `.unwrap_err()` instead"]
307 #[stable(feature = "rust1", since = "1.0.0")]
308 pub 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 where U: PartialEq<T> {
338 /// Returns `true` if the result is an [`Err`] value containing the given value.
343 /// #![feature(result_contains_err)]
345 /// let x: Result<u32, &str> = Ok(2);
346 /// assert_eq!(x.contains_err(&"Some error message"), false);
348 /// let x: Result<u32, &str> = Err("Some error message");
349 /// assert_eq!(x.contains_err(&"Some error message"), true);
351 /// let x: Result<u32, &str> = Err("Some other error message");
352 /// assert_eq!(x.contains_err(&"Some error message"), false);
356 #[unstable(feature = "result_contains_err", issue = "62358")]
357 pub fn contains_err<F>(&self, f: &F) -> bool where F: PartialEq<E> {
364 /////////////////////////////////////////////////////////////////////////
365 // Adapter for each variant
366 /////////////////////////////////////////////////////////////////////////
368 /// Converts from `Result<T, E>` to [`Option<T>`].
370 /// Converts `self` into an [`Option<T>`], consuming `self`,
371 /// and discarding the error, if any.
373 /// [`Option<T>`]: ../../std/option/enum.Option.html
380 /// let x: Result<u32, &str> = Ok(2);
381 /// assert_eq!(x.ok(), Some(2));
383 /// let x: Result<u32, &str> = Err("Nothing here");
384 /// assert_eq!(x.ok(), None);
387 #[stable(feature = "rust1", since = "1.0.0")]
388 pub fn ok(self) -> Option<T> {
395 /// Converts from `Result<T, E>` to [`Option<E>`].
397 /// Converts `self` into an [`Option<E>`], consuming `self`,
398 /// and discarding the success value, if any.
400 /// [`Option<E>`]: ../../std/option/enum.Option.html
407 /// let x: Result<u32, &str> = Ok(2);
408 /// assert_eq!(x.err(), None);
410 /// let x: Result<u32, &str> = Err("Nothing here");
411 /// assert_eq!(x.err(), Some("Nothing here"));
414 #[stable(feature = "rust1", since = "1.0.0")]
415 pub fn err(self) -> Option<E> {
422 /////////////////////////////////////////////////////////////////////////
423 // Adapter for working with references
424 /////////////////////////////////////////////////////////////////////////
426 /// Converts from `&Result<T, E>` to `Result<&T, &E>`.
428 /// Produces a new `Result`, containing a reference
429 /// into the original, leaving the original in place.
436 /// let x: Result<u32, &str> = Ok(2);
437 /// assert_eq!(x.as_ref(), Ok(&2));
439 /// let x: Result<u32, &str> = Err("Error");
440 /// assert_eq!(x.as_ref(), Err(&"Error"));
443 #[stable(feature = "rust1", since = "1.0.0")]
444 pub fn as_ref(&self) -> Result<&T, &E> {
447 Err(ref x) => Err(x),
451 /// Converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`.
458 /// fn mutate(r: &mut Result<i32, i32>) {
459 /// match r.as_mut() {
460 /// Ok(v) => *v = 42,
461 /// Err(e) => *e = 0,
465 /// let mut x: Result<i32, i32> = Ok(2);
467 /// assert_eq!(x.unwrap(), 42);
469 /// let mut x: Result<i32, i32> = Err(13);
471 /// assert_eq!(x.unwrap_err(), 0);
474 #[stable(feature = "rust1", since = "1.0.0")]
475 pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
477 Ok(ref mut x) => Ok(x),
478 Err(ref mut x) => Err(x),
482 /////////////////////////////////////////////////////////////////////////
483 // Transforming contained values
484 /////////////////////////////////////////////////////////////////////////
486 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
487 /// contained [`Ok`] value, leaving an [`Err`] value untouched.
489 /// This function can be used to compose the results of two functions.
491 /// [`Ok`]: enum.Result.html#variant.Ok
492 /// [`Err`]: enum.Result.html#variant.Err
496 /// Print the numbers on each line of a string multiplied by two.
499 /// let line = "1\n2\n3\n4\n";
501 /// for num in line.lines() {
502 /// match num.parse::<i32>().map(|i| i * 2) {
503 /// Ok(n) => println!("{}", n),
509 #[stable(feature = "rust1", since = "1.0.0")]
510 pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
517 /// Applies a function to the contained value (if any),
518 /// or returns the provided default (if not).
523 /// #![feature(result_map_or)]
524 /// let x: Result<_, &str> = Ok("foo");
525 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
527 /// let x: Result<&str, _> = Err("bar");
528 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
531 #[unstable(feature = "result_map_or", issue = "66293")]
532 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
539 /// Maps a `Result<T, E>` to `U` by applying a function to a
540 /// contained [`Ok`] value, or a fallback function to a
541 /// contained [`Err`] value.
543 /// This function can be used to unpack a successful result
544 /// while handling an error.
546 /// [`Ok`]: enum.Result.html#variant.Ok
547 /// [`Err`]: enum.Result.html#variant.Err
556 /// let x : Result<_, &str> = Ok("foo");
557 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);
559 /// let x : Result<&str, _> = Err("bar");
560 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
563 #[stable(feature = "result_map_or_else", since = "1.41.0")]
564 pub fn map_or_else<U, D: FnOnce(E) -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
567 Err(e) => default(e),
571 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
572 /// contained [`Err`] value, leaving an [`Ok`] value untouched.
574 /// This function can be used to pass through a successful result while handling
577 /// [`Ok`]: enum.Result.html#variant.Ok
578 /// [`Err`]: enum.Result.html#variant.Err
585 /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
587 /// let x: Result<u32, u32> = Ok(2);
588 /// assert_eq!(x.map_err(stringify), Ok(2));
590 /// let x: Result<u32, u32> = Err(13);
591 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
594 #[stable(feature = "rust1", since = "1.0.0")]
595 pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> {
602 /////////////////////////////////////////////////////////////////////////
603 // Iterator constructors
604 /////////////////////////////////////////////////////////////////////////
606 /// Returns an iterator over the possibly contained value.
608 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
615 /// let x: Result<u32, &str> = Ok(7);
616 /// assert_eq!(x.iter().next(), Some(&7));
618 /// let x: Result<u32, &str> = Err("nothing!");
619 /// assert_eq!(x.iter().next(), None);
622 #[stable(feature = "rust1", since = "1.0.0")]
623 pub fn iter(&self) -> Iter<'_, T> {
624 Iter { inner: self.as_ref().ok() }
627 /// Returns a mutable iterator over the possibly contained value.
629 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
636 /// let mut x: Result<u32, &str> = Ok(7);
637 /// match x.iter_mut().next() {
638 /// Some(v) => *v = 40,
641 /// assert_eq!(x, Ok(40));
643 /// let mut x: Result<u32, &str> = Err("nothing!");
644 /// assert_eq!(x.iter_mut().next(), None);
647 #[stable(feature = "rust1", since = "1.0.0")]
648 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
649 IterMut { inner: self.as_mut().ok() }
652 ////////////////////////////////////////////////////////////////////////
653 // Boolean operations on the values, eager and lazy
654 /////////////////////////////////////////////////////////////////////////
656 /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
658 /// [`Ok`]: enum.Result.html#variant.Ok
659 /// [`Err`]: enum.Result.html#variant.Err
666 /// let x: Result<u32, &str> = Ok(2);
667 /// let y: Result<&str, &str> = Err("late error");
668 /// assert_eq!(x.and(y), Err("late error"));
670 /// let x: Result<u32, &str> = Err("early error");
671 /// let y: Result<&str, &str> = Ok("foo");
672 /// assert_eq!(x.and(y), Err("early error"));
674 /// let x: Result<u32, &str> = Err("not a 2");
675 /// let y: Result<&str, &str> = Err("late error");
676 /// assert_eq!(x.and(y), Err("not a 2"));
678 /// let x: Result<u32, &str> = Ok(2);
679 /// let y: Result<&str, &str> = Ok("different result type");
680 /// assert_eq!(x.and(y), Ok("different result type"));
683 #[stable(feature = "rust1", since = "1.0.0")]
684 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
691 /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
693 /// [`Ok`]: enum.Result.html#variant.Ok
694 /// [`Err`]: enum.Result.html#variant.Err
696 /// This function can be used for control flow based on `Result` values.
703 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
704 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
706 /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
707 /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
708 /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
709 /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
712 #[stable(feature = "rust1", since = "1.0.0")]
713 pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
720 /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
722 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
723 /// result of a function call, it is recommended to use [`or_else`], which is
724 /// lazily evaluated.
726 /// [`Ok`]: enum.Result.html#variant.Ok
727 /// [`Err`]: enum.Result.html#variant.Err
728 /// [`or_else`]: #method.or_else
735 /// let x: Result<u32, &str> = Ok(2);
736 /// let y: Result<u32, &str> = Err("late error");
737 /// assert_eq!(x.or(y), Ok(2));
739 /// let x: Result<u32, &str> = Err("early error");
740 /// let y: Result<u32, &str> = Ok(2);
741 /// assert_eq!(x.or(y), Ok(2));
743 /// let x: Result<u32, &str> = Err("not a 2");
744 /// let y: Result<u32, &str> = Err("late error");
745 /// assert_eq!(x.or(y), Err("late error"));
747 /// let x: Result<u32, &str> = Ok(2);
748 /// let y: Result<u32, &str> = Ok(100);
749 /// assert_eq!(x.or(y), Ok(2));
752 #[stable(feature = "rust1", since = "1.0.0")]
753 pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
760 /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
762 /// This function can be used for control flow based on result values.
764 /// [`Ok`]: enum.Result.html#variant.Ok
765 /// [`Err`]: enum.Result.html#variant.Err
772 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
773 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
775 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
776 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
777 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
778 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
781 #[stable(feature = "rust1", since = "1.0.0")]
782 pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
789 /// Unwraps a result, yielding the content of an [`Ok`].
790 /// Else, it returns `optb`.
792 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
793 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
794 /// which is lazily evaluated.
796 /// [`Ok`]: enum.Result.html#variant.Ok
797 /// [`Err`]: enum.Result.html#variant.Err
798 /// [`unwrap_or_else`]: #method.unwrap_or_else
806 /// let x: Result<u32, &str> = Ok(9);
807 /// assert_eq!(x.unwrap_or(optb), 9);
809 /// let x: Result<u32, &str> = Err("error");
810 /// assert_eq!(x.unwrap_or(optb), optb);
813 #[stable(feature = "rust1", since = "1.0.0")]
814 pub fn unwrap_or(self, optb: T) -> T {
821 /// Unwraps a result, yielding the content of an [`Ok`].
822 /// If the value is an [`Err`] then it calls `op` with its value.
824 /// [`Ok`]: enum.Result.html#variant.Ok
825 /// [`Err`]: enum.Result.html#variant.Err
832 /// fn count(x: &str) -> usize { x.len() }
834 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
835 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
838 #[stable(feature = "rust1", since = "1.0.0")]
839 pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
847 impl<T: Copy, E> Result<&T, E> {
848 /// Maps a `Result<&T, E>` to a `Result<T, E>` by copying the contents of the
854 /// #![feature(result_copied)]
856 /// let x: Result<&i32, i32> = Ok(&val);
857 /// assert_eq!(x, Ok(&12));
858 /// let copied = x.copied();
859 /// assert_eq!(copied, Ok(12));
861 #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
862 pub fn copied(self) -> Result<T, E> {
867 impl<T: Copy, E> Result<&mut T, E> {
868 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by copying the contents of the
874 /// #![feature(result_copied)]
875 /// let mut val = 12;
876 /// let x: Result<&mut i32, i32> = Ok(&mut val);
877 /// assert_eq!(x, Ok(&mut 12));
878 /// let copied = x.copied();
879 /// assert_eq!(copied, Ok(12));
881 #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
882 pub fn copied(self) -> Result<T, E> {
887 impl<T: Clone, E> Result<&T, E> {
888 /// Maps a `Result<&T, E>` to a `Result<T, E>` by cloning the contents of the
894 /// #![feature(result_cloned)]
896 /// let x: Result<&i32, i32> = Ok(&val);
897 /// assert_eq!(x, Ok(&12));
898 /// let cloned = x.cloned();
899 /// assert_eq!(cloned, Ok(12));
901 #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
902 pub fn cloned(self) -> Result<T, E> {
903 self.map(|t| t.clone())
907 impl<T: Clone, E> Result<&mut T, E> {
908 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by cloning the contents of the
914 /// #![feature(result_cloned)]
915 /// let mut val = 12;
916 /// let x: Result<&mut i32, i32> = Ok(&mut val);
917 /// assert_eq!(x, Ok(&mut 12));
918 /// let cloned = x.cloned();
919 /// assert_eq!(cloned, Ok(12));
921 #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
922 pub fn cloned(self) -> Result<T, E> {
923 self.map(|t| t.clone())
928 impl<T, E: fmt::Debug> Result<T, E> {
929 /// Unwraps a result, yielding the content of an [`Ok`].
933 /// Panics if the value is an [`Err`], with a panic message provided by the
936 /// [`Ok`]: enum.Result.html#variant.Ok
937 /// [`Err`]: enum.Result.html#variant.Err
944 /// let x: Result<u32, &str> = Ok(2);
945 /// assert_eq!(x.unwrap(), 2);
948 /// ```{.should_panic}
949 /// let x: Result<u32, &str> = Err("emergency failure");
950 /// x.unwrap(); // panics with `emergency failure`
953 #[stable(feature = "rust1", since = "1.0.0")]
954 pub fn unwrap(self) -> T {
957 Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e),
961 /// Unwraps a result, yielding the content of an [`Ok`].
965 /// Panics if the value is an [`Err`], with a panic message including the
966 /// passed message, and the content of the [`Err`].
968 /// [`Ok`]: enum.Result.html#variant.Ok
969 /// [`Err`]: enum.Result.html#variant.Err
975 /// ```{.should_panic}
976 /// let x: Result<u32, &str> = Err("emergency failure");
977 /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
980 #[stable(feature = "result_expect", since = "1.4.0")]
981 pub fn expect(self, msg: &str) -> T {
984 Err(e) => unwrap_failed(msg, &e),
989 impl<T: fmt::Debug, E> Result<T, E> {
990 /// Unwraps a result, yielding the content of an [`Err`].
994 /// Panics if the value is an [`Ok`], with a custom panic message provided
995 /// by the [`Ok`]'s value.
997 /// [`Ok`]: enum.Result.html#variant.Ok
998 /// [`Err`]: enum.Result.html#variant.Err
1003 /// ```{.should_panic}
1004 /// let x: Result<u32, &str> = Ok(2);
1005 /// x.unwrap_err(); // panics with `2`
1009 /// let x: Result<u32, &str> = Err("emergency failure");
1010 /// assert_eq!(x.unwrap_err(), "emergency failure");
1013 #[stable(feature = "rust1", since = "1.0.0")]
1014 pub fn unwrap_err(self) -> E {
1016 Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t),
1021 /// Unwraps a result, yielding the content of an [`Err`].
1025 /// Panics if the value is an [`Ok`], with a panic message including the
1026 /// passed message, and the content of the [`Ok`].
1028 /// [`Ok`]: enum.Result.html#variant.Ok
1029 /// [`Err`]: enum.Result.html#variant.Err
1035 /// ```{.should_panic}
1036 /// let x: Result<u32, &str> = Ok(10);
1037 /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
1040 #[stable(feature = "result_expect_err", since = "1.17.0")]
1041 pub fn expect_err(self, msg: &str) -> E {
1043 Ok(t) => unwrap_failed(msg, &t),
1049 impl<T: Default, E> Result<T, E> {
1050 /// Returns the contained value or a default
1052 /// Consumes the `self` argument then, if [`Ok`], returns the contained
1053 /// value, otherwise if [`Err`], returns the default value for that
1058 /// Converts a string to an integer, turning poorly-formed strings
1059 /// into 0 (the default value for integers). [`parse`] converts
1060 /// a string to any other type that implements [`FromStr`], returning an
1061 /// [`Err`] on error.
1064 /// let good_year_from_input = "1909";
1065 /// let bad_year_from_input = "190blarg";
1066 /// let good_year = good_year_from_input.parse().unwrap_or_default();
1067 /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
1069 /// assert_eq!(1909, good_year);
1070 /// assert_eq!(0, bad_year);
1073 /// [`parse`]: ../../std/primitive.str.html#method.parse
1074 /// [`FromStr`]: ../../std/str/trait.FromStr.html
1075 /// [`Ok`]: enum.Result.html#variant.Ok
1076 /// [`Err`]: enum.Result.html#variant.Err
1078 #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
1079 pub fn unwrap_or_default(self) -> T {
1082 Err(_) => Default::default(),
1087 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1088 impl<T: Deref, E> Result<T, E> {
1089 /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&T::Target, &E>`.
1091 /// Leaves the original `Result` in-place, creating a new one containing a reference to the
1092 /// `Ok` type's `Deref::Target` type.
1093 pub fn as_deref_ok(&self) -> Result<&T::Target, &E> {
1094 self.as_ref().map(|t| t.deref())
1098 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1099 impl<T, E: Deref> Result<T, E> {
1100 /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&T, &E::Target>`.
1102 /// Leaves the original `Result` in-place, creating a new one containing a reference to the
1103 /// `Err` type's `Deref::Target` type.
1104 pub fn as_deref_err(&self) -> Result<&T, &E::Target>
1106 self.as_ref().map_err(|e| e.deref())
1110 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1111 impl<T: Deref, E: Deref> Result<T, E> {
1112 /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&T::Target, &E::Target>`.
1114 /// Leaves the original `Result` in-place, creating a new one containing a reference to both
1115 /// the `Ok` and `Err` types' `Deref::Target` types.
1116 pub fn as_deref(&self) -> Result<&T::Target, &E::Target>
1118 self.as_ref().map(|t| t.deref()).map_err(|e| e.deref())
1122 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1123 impl<T: DerefMut, E> Result<T, E> {
1124 /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut T::Target, &mut E>`.
1126 /// Leaves the original `Result` in-place, creating a new one containing a mutable reference to
1127 /// the `Ok` type's `Deref::Target` type.
1128 pub fn as_deref_mut_ok(&mut self) -> Result<&mut T::Target, &mut E> {
1129 self.as_mut().map(|t| t.deref_mut())
1133 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1134 impl<T, E: DerefMut> Result<T, E> {
1135 /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut T, &mut E::Target>`.
1137 /// Leaves the original `Result` in-place, creating a new one containing a mutable reference to
1138 /// the `Err` type's `Deref::Target` type.
1139 pub fn as_deref_mut_err(&mut self) -> Result<&mut T, &mut E::Target>
1141 self.as_mut().map_err(|e| e.deref_mut())
1145 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1146 impl<T: DerefMut, E: DerefMut> Result<T, E> {
1147 /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to
1148 /// `Result<&mut T::Target, &mut E::Target>`.
1150 /// Leaves the original `Result` in-place, creating a new one containing a mutable reference to
1151 /// both the `Ok` and `Err` types' `Deref::Target` types.
1152 pub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E::Target>
1154 self.as_mut().map(|t| t.deref_mut()).map_err(|e| e.deref_mut())
1158 impl<T, E> Result<Option<T>, E> {
1159 /// Transposes a `Result` of an `Option` into an `Option` of a `Result`.
1161 /// `Ok(None)` will be mapped to `None`.
1162 /// `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`.
1167 /// #[derive(Debug, Eq, PartialEq)]
1170 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1171 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1172 /// assert_eq!(x.transpose(), y);
1175 #[stable(feature = "transpose_result", since = "1.33.0")]
1176 pub fn transpose(self) -> Option<Result<T, E>> {
1178 Ok(Some(x)) => Some(Ok(x)),
1180 Err(e) => Some(Err(e)),
1185 // This is a separate function to reduce the code size of the methods
1188 fn unwrap_failed(msg: &str, error: &dyn fmt::Debug) -> ! {
1189 panic!("{}: {:?}", msg, error)
1192 /////////////////////////////////////////////////////////////////////////////
1193 // Trait implementations
1194 /////////////////////////////////////////////////////////////////////////////
1196 #[stable(feature = "rust1", since = "1.0.0")]
1197 impl<T: Clone, E: Clone> Clone for Result<T, E> {
1199 fn clone(&self) -> Self {
1201 Ok(x) => Ok(x.clone()),
1202 Err(x) => Err(x.clone()),
1207 fn clone_from(&mut self, source: &Self) {
1208 match (self, source) {
1209 (Ok(to), Ok(from)) => to.clone_from(from),
1210 (Err(to), Err(from)) => to.clone_from(from),
1211 (to, from) => *to = from.clone(),
1217 #[stable(feature = "rust1", since = "1.0.0")]
1218 impl<T, E> IntoIterator for Result<T, E> {
1220 type IntoIter = IntoIter<T>;
1222 /// Returns a consuming iterator over the possibly contained value.
1224 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
1231 /// let x: Result<u32, &str> = Ok(5);
1232 /// let v: Vec<u32> = x.into_iter().collect();
1233 /// assert_eq!(v, [5]);
1235 /// let x: Result<u32, &str> = Err("nothing!");
1236 /// let v: Vec<u32> = x.into_iter().collect();
1237 /// assert_eq!(v, []);
1240 fn into_iter(self) -> IntoIter<T> {
1241 IntoIter { inner: self.ok() }
1245 #[stable(since = "1.4.0", feature = "result_iter")]
1246 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
1248 type IntoIter = Iter<'a, T>;
1250 fn into_iter(self) -> Iter<'a, T> {
1255 #[stable(since = "1.4.0", feature = "result_iter")]
1256 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
1257 type Item = &'a mut T;
1258 type IntoIter = IterMut<'a, T>;
1260 fn into_iter(self) -> IterMut<'a, T> {
1265 /////////////////////////////////////////////////////////////////////////////
1266 // The Result Iterators
1267 /////////////////////////////////////////////////////////////////////////////
1269 /// An iterator over a reference to the [`Ok`] variant of a [`Result`].
1271 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1273 /// Created by [`Result::iter`].
1275 /// [`Ok`]: enum.Result.html#variant.Ok
1276 /// [`Result`]: enum.Result.html
1277 /// [`Result::iter`]: enum.Result.html#method.iter
1279 #[stable(feature = "rust1", since = "1.0.0")]
1280 pub struct Iter<'a, T: 'a> { inner: Option<&'a T> }
1282 #[stable(feature = "rust1", since = "1.0.0")]
1283 impl<'a, T> Iterator for Iter<'a, T> {
1287 fn next(&mut self) -> Option<&'a T> { self.inner.take() }
1289 fn size_hint(&self) -> (usize, Option<usize>) {
1290 let n = if self.inner.is_some() {1} else {0};
1295 #[stable(feature = "rust1", since = "1.0.0")]
1296 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1298 fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
1301 #[stable(feature = "rust1", since = "1.0.0")]
1302 impl<T> ExactSizeIterator for Iter<'_, T> {}
1304 #[stable(feature = "fused", since = "1.26.0")]
1305 impl<T> FusedIterator for Iter<'_, T> {}
1307 #[unstable(feature = "trusted_len", issue = "37572")]
1308 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1310 #[stable(feature = "rust1", since = "1.0.0")]
1311 impl<T> Clone for Iter<'_, T> {
1313 fn clone(&self) -> Self { Iter { inner: self.inner } }
1316 /// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
1318 /// Created by [`Result::iter_mut`].
1320 /// [`Ok`]: enum.Result.html#variant.Ok
1321 /// [`Result`]: enum.Result.html
1322 /// [`Result::iter_mut`]: enum.Result.html#method.iter_mut
1324 #[stable(feature = "rust1", since = "1.0.0")]
1325 pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
1327 #[stable(feature = "rust1", since = "1.0.0")]
1328 impl<'a, T> Iterator for IterMut<'a, T> {
1329 type Item = &'a mut T;
1332 fn next(&mut self) -> Option<&'a mut T> { self.inner.take() }
1334 fn size_hint(&self) -> (usize, Option<usize>) {
1335 let n = if self.inner.is_some() {1} else {0};
1340 #[stable(feature = "rust1", since = "1.0.0")]
1341 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1343 fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
1346 #[stable(feature = "rust1", since = "1.0.0")]
1347 impl<T> ExactSizeIterator for IterMut<'_, T> {}
1349 #[stable(feature = "fused", since = "1.26.0")]
1350 impl<T> FusedIterator for IterMut<'_, T> {}
1352 #[unstable(feature = "trusted_len", issue = "37572")]
1353 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1355 /// An iterator over the value in a [`Ok`] variant of a [`Result`].
1357 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1359 /// This struct is created by the [`into_iter`] method on
1360 /// [`Result`][`Result`] (provided by the [`IntoIterator`] trait).
1362 /// [`Ok`]: enum.Result.html#variant.Ok
1363 /// [`Result`]: enum.Result.html
1364 /// [`into_iter`]: ../iter/trait.IntoIterator.html#tymethod.into_iter
1365 /// [`IntoIterator`]: ../iter/trait.IntoIterator.html
1366 #[derive(Clone, Debug)]
1367 #[stable(feature = "rust1", since = "1.0.0")]
1368 pub struct IntoIter<T> { inner: Option<T> }
1370 #[stable(feature = "rust1", since = "1.0.0")]
1371 impl<T> Iterator for IntoIter<T> {
1375 fn next(&mut self) -> Option<T> { self.inner.take() }
1377 fn size_hint(&self) -> (usize, Option<usize>) {
1378 let n = if self.inner.is_some() {1} else {0};
1383 #[stable(feature = "rust1", since = "1.0.0")]
1384 impl<T> DoubleEndedIterator for IntoIter<T> {
1386 fn next_back(&mut self) -> Option<T> { self.inner.take() }
1389 #[stable(feature = "rust1", since = "1.0.0")]
1390 impl<T> ExactSizeIterator for IntoIter<T> {}
1392 #[stable(feature = "fused", since = "1.26.0")]
1393 impl<T> FusedIterator for IntoIter<T> {}
1395 #[unstable(feature = "trusted_len", issue = "37572")]
1396 unsafe impl<A> TrustedLen for IntoIter<A> {}
1398 /////////////////////////////////////////////////////////////////////////////
1400 /////////////////////////////////////////////////////////////////////////////
1402 #[stable(feature = "rust1", since = "1.0.0")]
1403 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
1404 /// Takes each element in the `Iterator`: if it is an `Err`, no further
1405 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
1406 /// container with the values of each `Result` is returned.
1408 /// Here is an example which increments every integer in a vector,
1409 /// checking for overflow:
1412 /// let v = vec![1, 2];
1413 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1414 /// x.checked_add(1).ok_or("Overflow!")
1416 /// assert_eq!(res, Ok(vec![2, 3]));
1419 /// Here is another example that tries to subtract one from another list
1420 /// of integers, this time checking for underflow:
1423 /// let v = vec![1, 2, 0];
1424 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1425 /// x.checked_sub(1).ok_or("Underflow!")
1427 /// assert_eq!(res, Err("Underflow!"));
1430 /// Here is a variation on the previous example, showing that no
1431 /// further elements are taken from `iter` after the first `Err`.
1434 /// let v = vec![3, 2, 1, 10];
1435 /// let mut shared = 0;
1436 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {
1438 /// x.checked_sub(2).ok_or("Underflow!")
1440 /// assert_eq!(res, Err("Underflow!"));
1441 /// assert_eq!(shared, 6);
1444 /// Since the third element caused an underflow, no further elements were taken,
1445 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1447 fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
1448 // FIXME(#11084): This could be replaced with Iterator::scan when this
1449 // performance bug is closed.
1451 iter::process_results(iter.into_iter(), |i| i.collect())
1455 #[unstable(feature = "try_trait", issue = "42327")]
1456 impl<T,E> ops::Try for Result<T, E> {
1461 fn into_result(self) -> Self {
1466 fn from_ok(v: T) -> Self {
1471 fn from_error(v: E) -> Self {