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::{FromIterator, FusedIterator, TrustedLen};
235 use crate::ops::{self, Deref};
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(Clone, 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);
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);
307 #[stable(feature = "rust1", since = "1.0.0")]
308 pub fn is_err(&self) -> bool {
312 /////////////////////////////////////////////////////////////////////////
313 // Adapter for each variant
314 /////////////////////////////////////////////////////////////////////////
316 /// Converts from `Result<T, E>` to [`Option<T>`].
318 /// Converts `self` into an [`Option<T>`], consuming `self`,
319 /// and discarding the error, if any.
321 /// [`Option<T>`]: ../../std/option/enum.Option.html
328 /// let x: Result<u32, &str> = Ok(2);
329 /// assert_eq!(x.ok(), Some(2));
331 /// let x: Result<u32, &str> = Err("Nothing here");
332 /// assert_eq!(x.ok(), None);
335 #[stable(feature = "rust1", since = "1.0.0")]
336 pub fn ok(self) -> Option<T> {
343 /// Converts from `Result<T, E>` to [`Option<E>`].
345 /// Converts `self` into an [`Option<E>`], consuming `self`,
346 /// and discarding the success value, if any.
348 /// [`Option<E>`]: ../../std/option/enum.Option.html
355 /// let x: Result<u32, &str> = Ok(2);
356 /// assert_eq!(x.err(), None);
358 /// let x: Result<u32, &str> = Err("Nothing here");
359 /// assert_eq!(x.err(), Some("Nothing here"));
362 #[stable(feature = "rust1", since = "1.0.0")]
363 pub fn err(self) -> Option<E> {
370 /////////////////////////////////////////////////////////////////////////
371 // Adapter for working with references
372 /////////////////////////////////////////////////////////////////////////
374 /// Converts from `&Result<T, E>` to `Result<&T, &E>`.
376 /// Produces a new `Result`, containing a reference
377 /// into the original, leaving the original in place.
384 /// let x: Result<u32, &str> = Ok(2);
385 /// assert_eq!(x.as_ref(), Ok(&2));
387 /// let x: Result<u32, &str> = Err("Error");
388 /// assert_eq!(x.as_ref(), Err(&"Error"));
391 #[stable(feature = "rust1", since = "1.0.0")]
392 pub fn as_ref(&self) -> Result<&T, &E> {
395 Err(ref x) => Err(x),
399 /// Converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`.
406 /// fn mutate(r: &mut Result<i32, i32>) {
407 /// match r.as_mut() {
408 /// Ok(v) => *v = 42,
409 /// Err(e) => *e = 0,
413 /// let mut x: Result<i32, i32> = Ok(2);
415 /// assert_eq!(x.unwrap(), 42);
417 /// let mut x: Result<i32, i32> = Err(13);
419 /// assert_eq!(x.unwrap_err(), 0);
422 #[stable(feature = "rust1", since = "1.0.0")]
423 pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
425 Ok(ref mut x) => Ok(x),
426 Err(ref mut x) => Err(x),
430 /////////////////////////////////////////////////////////////////////////
431 // Transforming contained values
432 /////////////////////////////////////////////////////////////////////////
434 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
435 /// contained [`Ok`] value, leaving an [`Err`] value untouched.
437 /// This function can be used to compose the results of two functions.
439 /// [`Ok`]: enum.Result.html#variant.Ok
440 /// [`Err`]: enum.Result.html#variant.Err
444 /// Print the numbers on each line of a string multiplied by two.
447 /// let line = "1\n2\n3\n4\n";
449 /// for num in line.lines() {
450 /// match num.parse::<i32>().map(|i| i * 2) {
451 /// Ok(n) => println!("{}", n),
457 #[stable(feature = "rust1", since = "1.0.0")]
458 pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
465 /// Maps a `Result<T, E>` to `U` by applying a function to a
466 /// contained [`Ok`] value, or a fallback function to a
467 /// contained [`Err`] value.
469 /// This function can be used to unpack a successful result
470 /// while handling an error.
472 /// [`Ok`]: enum.Result.html#variant.Ok
473 /// [`Err`]: enum.Result.html#variant.Err
480 /// #![feature(result_map_or_else)]
483 /// let x : Result<_, &str> = Ok("foo");
484 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);
486 /// let x : Result<&str, _> = Err("bar");
487 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
490 #[unstable(feature = "result_map_or_else", issue = "53268")]
491 pub fn map_or_else<U, M: FnOnce(T) -> U, F: FnOnce(E) -> U>(self, fallback: F, map: M) -> U {
492 self.map(map).unwrap_or_else(fallback)
495 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
496 /// contained [`Err`] value, leaving an [`Ok`] value untouched.
498 /// This function can be used to pass through a successful result while handling
501 /// [`Ok`]: enum.Result.html#variant.Ok
502 /// [`Err`]: enum.Result.html#variant.Err
509 /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
511 /// let x: Result<u32, u32> = Ok(2);
512 /// assert_eq!(x.map_err(stringify), Ok(2));
514 /// let x: Result<u32, u32> = Err(13);
515 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
518 #[stable(feature = "rust1", since = "1.0.0")]
519 pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> {
526 /////////////////////////////////////////////////////////////////////////
527 // Iterator constructors
528 /////////////////////////////////////////////////////////////////////////
530 /// Returns an iterator over the possibly contained value.
532 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
539 /// let x: Result<u32, &str> = Ok(7);
540 /// assert_eq!(x.iter().next(), Some(&7));
542 /// let x: Result<u32, &str> = Err("nothing!");
543 /// assert_eq!(x.iter().next(), None);
546 #[stable(feature = "rust1", since = "1.0.0")]
547 pub fn iter(&self) -> Iter<'_, T> {
548 Iter { inner: self.as_ref().ok() }
551 /// Returns a mutable iterator over the possibly contained value.
553 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
560 /// let mut x: Result<u32, &str> = Ok(7);
561 /// match x.iter_mut().next() {
562 /// Some(v) => *v = 40,
565 /// assert_eq!(x, Ok(40));
567 /// let mut x: Result<u32, &str> = Err("nothing!");
568 /// assert_eq!(x.iter_mut().next(), None);
571 #[stable(feature = "rust1", since = "1.0.0")]
572 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
573 IterMut { inner: self.as_mut().ok() }
576 ////////////////////////////////////////////////////////////////////////
577 // Boolean operations on the values, eager and lazy
578 /////////////////////////////////////////////////////////////////////////
580 /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
582 /// [`Ok`]: enum.Result.html#variant.Ok
583 /// [`Err`]: enum.Result.html#variant.Err
590 /// let x: Result<u32, &str> = Ok(2);
591 /// let y: Result<&str, &str> = Err("late error");
592 /// assert_eq!(x.and(y), Err("late error"));
594 /// let x: Result<u32, &str> = Err("early error");
595 /// let y: Result<&str, &str> = Ok("foo");
596 /// assert_eq!(x.and(y), Err("early error"));
598 /// let x: Result<u32, &str> = Err("not a 2");
599 /// let y: Result<&str, &str> = Err("late error");
600 /// assert_eq!(x.and(y), Err("not a 2"));
602 /// let x: Result<u32, &str> = Ok(2);
603 /// let y: Result<&str, &str> = Ok("different result type");
604 /// assert_eq!(x.and(y), Ok("different result type"));
607 #[stable(feature = "rust1", since = "1.0.0")]
608 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
615 /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
617 /// [`Ok`]: enum.Result.html#variant.Ok
618 /// [`Err`]: enum.Result.html#variant.Err
620 /// This function can be used for control flow based on `Result` values.
627 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
628 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
630 /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
631 /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
632 /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
633 /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
636 #[stable(feature = "rust1", since = "1.0.0")]
637 pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
644 /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
646 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
647 /// result of a function call, it is recommended to use [`or_else`], which is
648 /// lazily evaluated.
650 /// [`Ok`]: enum.Result.html#variant.Ok
651 /// [`Err`]: enum.Result.html#variant.Err
652 /// [`or_else`]: #method.or_else
659 /// let x: Result<u32, &str> = Ok(2);
660 /// let y: Result<u32, &str> = Err("late error");
661 /// assert_eq!(x.or(y), Ok(2));
663 /// let x: Result<u32, &str> = Err("early error");
664 /// let y: Result<u32, &str> = Ok(2);
665 /// assert_eq!(x.or(y), Ok(2));
667 /// let x: Result<u32, &str> = Err("not a 2");
668 /// let y: Result<u32, &str> = Err("late error");
669 /// assert_eq!(x.or(y), Err("late error"));
671 /// let x: Result<u32, &str> = Ok(2);
672 /// let y: Result<u32, &str> = Ok(100);
673 /// assert_eq!(x.or(y), Ok(2));
676 #[stable(feature = "rust1", since = "1.0.0")]
677 pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
684 /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
686 /// This function can be used for control flow based on result values.
688 /// [`Ok`]: enum.Result.html#variant.Ok
689 /// [`Err`]: enum.Result.html#variant.Err
696 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
697 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
699 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
700 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
701 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
702 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
705 #[stable(feature = "rust1", since = "1.0.0")]
706 pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
713 /// Unwraps a result, yielding the content of an [`Ok`].
714 /// Else, it returns `optb`.
716 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
717 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
718 /// which is lazily evaluated.
720 /// [`Ok`]: enum.Result.html#variant.Ok
721 /// [`Err`]: enum.Result.html#variant.Err
722 /// [`unwrap_or_else`]: #method.unwrap_or_else
730 /// let x: Result<u32, &str> = Ok(9);
731 /// assert_eq!(x.unwrap_or(optb), 9);
733 /// let x: Result<u32, &str> = Err("error");
734 /// assert_eq!(x.unwrap_or(optb), optb);
737 #[stable(feature = "rust1", since = "1.0.0")]
738 pub fn unwrap_or(self, optb: T) -> T {
745 /// Unwraps a result, yielding the content of an [`Ok`].
746 /// If the value is an [`Err`] then it calls `op` with its value.
748 /// [`Ok`]: enum.Result.html#variant.Ok
749 /// [`Err`]: enum.Result.html#variant.Err
756 /// fn count(x: &str) -> usize { x.len() }
758 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
759 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
762 #[stable(feature = "rust1", since = "1.0.0")]
763 pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
771 impl<T, E: fmt::Debug> Result<T, E> {
772 /// Unwraps a result, yielding the content of an [`Ok`].
776 /// Panics if the value is an [`Err`], with a panic message provided by the
779 /// [`Ok`]: enum.Result.html#variant.Ok
780 /// [`Err`]: enum.Result.html#variant.Err
787 /// let x: Result<u32, &str> = Ok(2);
788 /// assert_eq!(x.unwrap(), 2);
791 /// ```{.should_panic}
792 /// let x: Result<u32, &str> = Err("emergency failure");
793 /// x.unwrap(); // panics with `emergency failure`
796 #[stable(feature = "rust1", since = "1.0.0")]
797 pub fn unwrap(self) -> T {
800 Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", e),
804 /// Unwraps a result, yielding the content of an [`Ok`].
808 /// Panics if the value is an [`Err`], with a panic message including the
809 /// passed message, and the content of the [`Err`].
811 /// [`Ok`]: enum.Result.html#variant.Ok
812 /// [`Err`]: enum.Result.html#variant.Err
818 /// ```{.should_panic}
819 /// let x: Result<u32, &str> = Err("emergency failure");
820 /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
823 #[stable(feature = "result_expect", since = "1.4.0")]
824 pub fn expect(self, msg: &str) -> T {
827 Err(e) => unwrap_failed(msg, e),
832 impl<T: fmt::Debug, E> Result<T, E> {
833 /// Unwraps a result, yielding the content of an [`Err`].
837 /// Panics if the value is an [`Ok`], with a custom panic message provided
838 /// by the [`Ok`]'s value.
840 /// [`Ok`]: enum.Result.html#variant.Ok
841 /// [`Err`]: enum.Result.html#variant.Err
846 /// ```{.should_panic}
847 /// let x: Result<u32, &str> = Ok(2);
848 /// x.unwrap_err(); // panics with `2`
852 /// let x: Result<u32, &str> = Err("emergency failure");
853 /// assert_eq!(x.unwrap_err(), "emergency failure");
856 #[stable(feature = "rust1", since = "1.0.0")]
857 pub fn unwrap_err(self) -> E {
859 Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", t),
864 /// Unwraps a result, yielding the content of an [`Err`].
868 /// Panics if the value is an [`Ok`], with a panic message including the
869 /// passed message, and the content of the [`Ok`].
871 /// [`Ok`]: enum.Result.html#variant.Ok
872 /// [`Err`]: enum.Result.html#variant.Err
878 /// ```{.should_panic}
879 /// let x: Result<u32, &str> = Ok(10);
880 /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
883 #[stable(feature = "result_expect_err", since = "1.17.0")]
884 pub fn expect_err(self, msg: &str) -> E {
886 Ok(t) => unwrap_failed(msg, t),
892 impl<T: Default, E> Result<T, E> {
893 /// Returns the contained value or a default
895 /// Consumes the `self` argument then, if [`Ok`], returns the contained
896 /// value, otherwise if [`Err`], returns the default value for that
901 /// Converts a string to an integer, turning poorly-formed strings
902 /// into 0 (the default value for integers). [`parse`] converts
903 /// a string to any other type that implements [`FromStr`], returning an
904 /// [`Err`] on error.
907 /// let good_year_from_input = "1909";
908 /// let bad_year_from_input = "190blarg";
909 /// let good_year = good_year_from_input.parse().unwrap_or_default();
910 /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
912 /// assert_eq!(1909, good_year);
913 /// assert_eq!(0, bad_year);
916 /// [`parse`]: ../../std/primitive.str.html#method.parse
917 /// [`FromStr`]: ../../std/str/trait.FromStr.html
918 /// [`Ok`]: enum.Result.html#variant.Ok
919 /// [`Err`]: enum.Result.html#variant.Err
921 #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
922 pub fn unwrap_or_default(self) -> T {
925 Err(_) => Default::default(),
930 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
931 impl<T: Deref, E> Result<T, E> {
932 /// Converts from `&Result<T, E>` to `Result<&T::Target, &E>`.
934 /// Leaves the original Result in-place, creating a new one with a reference
935 /// to the original one, additionally coercing the `Ok` arm of the Result via
937 pub fn deref_ok(&self) -> Result<&T::Target, &E> {
938 self.as_ref().map(|t| t.deref())
942 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
943 impl<T, E: Deref> Result<T, E> {
944 /// Converts from `&Result<T, E>` to `Result<&T, &E::Target>`.
946 /// Leaves the original Result in-place, creating a new one with a reference
947 /// to the original one, additionally coercing the `Err` arm of the Result via
949 pub fn deref_err(&self) -> Result<&T, &E::Target>
951 self.as_ref().map_err(|e| e.deref())
955 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
956 impl<T: Deref, E: Deref> Result<T, E> {
957 /// Converts from `&Result<T, E>` to `Result<&T::Target, &E::Target>`.
959 /// Leaves the original Result in-place, creating a new one with a reference
960 /// to the original one, additionally coercing both the `Ok` and `Err` arms
961 /// of the Result via `Deref`.
962 pub fn deref(&self) -> Result<&T::Target, &E::Target>
964 self.as_ref().map(|t| t.deref()).map_err(|e| e.deref())
968 impl<T, E> Result<Option<T>, E> {
969 /// Transposes a `Result` of an `Option` into an `Option` of a `Result`.
971 /// `Ok(None)` will be mapped to `None`.
972 /// `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`.
977 /// #[derive(Debug, Eq, PartialEq)]
980 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
981 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
982 /// assert_eq!(x.transpose(), y);
985 #[stable(feature = "transpose_result", since = "1.33.0")]
986 pub fn transpose(self) -> Option<Result<T, E>> {
988 Ok(Some(x)) => Some(Ok(x)),
990 Err(e) => Some(Err(e)),
995 // This is a separate function to reduce the code size of the methods
998 fn unwrap_failed<E: fmt::Debug>(msg: &str, error: E) -> ! {
999 panic!("{}: {:?}", msg, error)
1002 /////////////////////////////////////////////////////////////////////////////
1003 // Trait implementations
1004 /////////////////////////////////////////////////////////////////////////////
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 impl<T, E> IntoIterator for Result<T, E> {
1009 type IntoIter = IntoIter<T>;
1011 /// Returns a consuming iterator over the possibly contained value.
1013 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
1020 /// let x: Result<u32, &str> = Ok(5);
1021 /// let v: Vec<u32> = x.into_iter().collect();
1022 /// assert_eq!(v, [5]);
1024 /// let x: Result<u32, &str> = Err("nothing!");
1025 /// let v: Vec<u32> = x.into_iter().collect();
1026 /// assert_eq!(v, []);
1029 fn into_iter(self) -> IntoIter<T> {
1030 IntoIter { inner: self.ok() }
1034 #[stable(since = "1.4.0", feature = "result_iter")]
1035 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
1037 type IntoIter = Iter<'a, T>;
1039 fn into_iter(self) -> Iter<'a, T> {
1044 #[stable(since = "1.4.0", feature = "result_iter")]
1045 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
1046 type Item = &'a mut T;
1047 type IntoIter = IterMut<'a, T>;
1049 fn into_iter(self) -> IterMut<'a, T> {
1054 /////////////////////////////////////////////////////////////////////////////
1055 // The Result Iterators
1056 /////////////////////////////////////////////////////////////////////////////
1058 /// An iterator over a reference to the [`Ok`] variant of a [`Result`].
1060 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1062 /// Created by [`Result::iter`].
1064 /// [`Ok`]: enum.Result.html#variant.Ok
1065 /// [`Result`]: enum.Result.html
1066 /// [`Result::iter`]: enum.Result.html#method.iter
1068 #[stable(feature = "rust1", since = "1.0.0")]
1069 pub struct Iter<'a, T: 'a> { inner: Option<&'a T> }
1071 #[stable(feature = "rust1", since = "1.0.0")]
1072 impl<'a, T> Iterator for Iter<'a, T> {
1076 fn next(&mut self) -> Option<&'a T> { self.inner.take() }
1078 fn size_hint(&self) -> (usize, Option<usize>) {
1079 let n = if self.inner.is_some() {1} else {0};
1084 #[stable(feature = "rust1", since = "1.0.0")]
1085 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1087 fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
1090 #[stable(feature = "rust1", since = "1.0.0")]
1091 impl<T> ExactSizeIterator for Iter<'_, T> {}
1093 #[stable(feature = "fused", since = "1.26.0")]
1094 impl<T> FusedIterator for Iter<'_, T> {}
1096 #[unstable(feature = "trusted_len", issue = "37572")]
1097 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1099 #[stable(feature = "rust1", since = "1.0.0")]
1100 impl<T> Clone for Iter<'_, T> {
1102 fn clone(&self) -> Self { Iter { inner: self.inner } }
1105 /// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
1107 /// Created by [`Result::iter_mut`].
1109 /// [`Ok`]: enum.Result.html#variant.Ok
1110 /// [`Result`]: enum.Result.html
1111 /// [`Result::iter_mut`]: enum.Result.html#method.iter_mut
1113 #[stable(feature = "rust1", since = "1.0.0")]
1114 pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
1116 #[stable(feature = "rust1", since = "1.0.0")]
1117 impl<'a, T> Iterator for IterMut<'a, T> {
1118 type Item = &'a mut T;
1121 fn next(&mut self) -> Option<&'a mut T> { self.inner.take() }
1123 fn size_hint(&self) -> (usize, Option<usize>) {
1124 let n = if self.inner.is_some() {1} else {0};
1129 #[stable(feature = "rust1", since = "1.0.0")]
1130 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1132 fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
1135 #[stable(feature = "rust1", since = "1.0.0")]
1136 impl<T> ExactSizeIterator for IterMut<'_, T> {}
1138 #[stable(feature = "fused", since = "1.26.0")]
1139 impl<T> FusedIterator for IterMut<'_, T> {}
1141 #[unstable(feature = "trusted_len", issue = "37572")]
1142 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1144 /// An iterator over the value in a [`Ok`] variant of a [`Result`].
1146 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1148 /// This struct is created by the [`into_iter`] method on
1149 /// [`Result`][`Result`] (provided by the [`IntoIterator`] trait).
1151 /// [`Ok`]: enum.Result.html#variant.Ok
1152 /// [`Result`]: enum.Result.html
1153 /// [`into_iter`]: ../iter/trait.IntoIterator.html#tymethod.into_iter
1154 /// [`IntoIterator`]: ../iter/trait.IntoIterator.html
1155 #[derive(Clone, Debug)]
1156 #[stable(feature = "rust1", since = "1.0.0")]
1157 pub struct IntoIter<T> { inner: Option<T> }
1159 #[stable(feature = "rust1", since = "1.0.0")]
1160 impl<T> Iterator for IntoIter<T> {
1164 fn next(&mut self) -> Option<T> { self.inner.take() }
1166 fn size_hint(&self) -> (usize, Option<usize>) {
1167 let n = if self.inner.is_some() {1} else {0};
1172 #[stable(feature = "rust1", since = "1.0.0")]
1173 impl<T> DoubleEndedIterator for IntoIter<T> {
1175 fn next_back(&mut self) -> Option<T> { self.inner.take() }
1178 #[stable(feature = "rust1", since = "1.0.0")]
1179 impl<T> ExactSizeIterator for IntoIter<T> {}
1181 #[stable(feature = "fused", since = "1.26.0")]
1182 impl<T> FusedIterator for IntoIter<T> {}
1184 #[unstable(feature = "trusted_len", issue = "37572")]
1185 unsafe impl<A> TrustedLen for IntoIter<A> {}
1187 /////////////////////////////////////////////////////////////////////////////
1189 /////////////////////////////////////////////////////////////////////////////
1191 #[stable(feature = "rust1", since = "1.0.0")]
1192 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
1193 /// Takes each element in the `Iterator`: if it is an `Err`, no further
1194 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
1195 /// container with the values of each `Result` is returned.
1197 /// Here is an example which increments every integer in a vector,
1198 /// checking for overflow:
1201 /// let v = vec![1, 2];
1202 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1203 /// x.checked_add(1).ok_or("Overflow!")
1205 /// assert_eq!(res, Ok(vec![2, 3]));
1208 /// Here is another example that tries to subtract one from another list
1209 /// of integers, this time checking for underflow:
1212 /// let v = vec![1, 2, 0];
1213 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1214 /// x.checked_sub(1).ok_or("Underflow!")
1216 /// assert_eq!(res, Err("Underflow!"));
1219 /// Here is a variation on the previous example, showing that no
1220 /// further elements are taken from `iter` after the first `Err`.
1223 /// let v = vec![3, 2, 1, 10];
1224 /// let mut shared = 0;
1225 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {
1227 /// x.checked_sub(2).ok_or("Underflow!")
1229 /// assert_eq!(res, Err("Underflow!"));
1230 /// assert_eq!(shared, 6);
1233 /// Since the third element caused an underflow, no further elements were taken,
1234 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1236 fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
1237 // FIXME(#11084): This could be replaced with Iterator::scan when this
1238 // performance bug is closed.
1240 struct Adapter<Iter, E> {
1245 impl<T, E, Iter: Iterator<Item=Result<T, E>>> Iterator for Adapter<Iter, E> {
1249 fn next(&mut self) -> Option<T> {
1250 match self.iter.next() {
1251 Some(Ok(value)) => Some(value),
1253 self.err = Some(err);
1260 fn size_hint(&self) -> (usize, Option<usize>) {
1261 let (_min, max) = self.iter.size_hint();
1266 let mut adapter = Adapter { iter: iter.into_iter(), err: None };
1267 let v: V = FromIterator::from_iter(adapter.by_ref());
1270 Some(err) => Err(err),
1276 #[unstable(feature = "try_trait", issue = "42327")]
1277 impl<T,E> ops::Try for Result<T, E> {
1282 fn into_result(self) -> Self {
1287 fn from_ok(v: T) -> Self {
1292 fn from_error(v: E) -> Self {