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 iter::{FromIterator, FusedIterator, TrustedLen};
235 use 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);
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub fn is_ok(&self) -> bool {
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);
305 #[stable(feature = "rust1", since = "1.0.0")]
306 pub fn is_err(&self) -> bool {
310 /////////////////////////////////////////////////////////////////////////
311 // Adapter for each variant
312 /////////////////////////////////////////////////////////////////////////
314 /// Converts from `Result<T, E>` to [`Option<T>`].
316 /// Converts `self` into an [`Option<T>`], consuming `self`,
317 /// and discarding the error, if any.
319 /// [`Option<T>`]: ../../std/option/enum.Option.html
326 /// let x: Result<u32, &str> = Ok(2);
327 /// assert_eq!(x.ok(), Some(2));
329 /// let x: Result<u32, &str> = Err("Nothing here");
330 /// assert_eq!(x.ok(), None);
333 #[stable(feature = "rust1", since = "1.0.0")]
334 pub fn ok(self) -> Option<T> {
341 /// Converts from `Result<T, E>` to [`Option<E>`].
343 /// Converts `self` into an [`Option<E>`], consuming `self`,
344 /// and discarding the success value, if any.
346 /// [`Option<E>`]: ../../std/option/enum.Option.html
353 /// let x: Result<u32, &str> = Ok(2);
354 /// assert_eq!(x.err(), None);
356 /// let x: Result<u32, &str> = Err("Nothing here");
357 /// assert_eq!(x.err(), Some("Nothing here"));
360 #[stable(feature = "rust1", since = "1.0.0")]
361 pub fn err(self) -> Option<E> {
368 /////////////////////////////////////////////////////////////////////////
369 // Adapter for working with references
370 /////////////////////////////////////////////////////////////////////////
372 /// Converts from `Result<T, E>` to `Result<&T, &E>`.
374 /// Produces a new `Result`, containing a reference
375 /// into the original, leaving the original in place.
382 /// let x: Result<u32, &str> = Ok(2);
383 /// assert_eq!(x.as_ref(), Ok(&2));
385 /// let x: Result<u32, &str> = Err("Error");
386 /// assert_eq!(x.as_ref(), Err(&"Error"));
389 #[stable(feature = "rust1", since = "1.0.0")]
390 pub fn as_ref(&self) -> Result<&T, &E> {
393 Err(ref x) => Err(x),
397 /// Converts from `Result<T, E>` to `Result<&mut T, &mut E>`.
404 /// fn mutate(r: &mut Result<i32, i32>) {
405 /// match r.as_mut() {
406 /// Ok(v) => *v = 42,
407 /// Err(e) => *e = 0,
411 /// let mut x: Result<i32, i32> = Ok(2);
413 /// assert_eq!(x.unwrap(), 42);
415 /// let mut x: Result<i32, i32> = Err(13);
417 /// assert_eq!(x.unwrap_err(), 0);
420 #[stable(feature = "rust1", since = "1.0.0")]
421 pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
423 Ok(ref mut x) => Ok(x),
424 Err(ref mut x) => Err(x),
428 /////////////////////////////////////////////////////////////////////////
429 // Transforming contained values
430 /////////////////////////////////////////////////////////////////////////
432 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
433 /// contained [`Ok`] value, leaving an [`Err`] value untouched.
435 /// This function can be used to compose the results of two functions.
437 /// [`Ok`]: enum.Result.html#variant.Ok
438 /// [`Err`]: enum.Result.html#variant.Err
442 /// Print the numbers on each line of a string multiplied by two.
445 /// let line = "1\n2\n3\n4\n";
447 /// for num in line.lines() {
448 /// match num.parse::<i32>().map(|i| i * 2) {
449 /// Ok(n) => println!("{}", n),
455 #[stable(feature = "rust1", since = "1.0.0")]
456 pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
463 /// Maps a `Result<T, E>` to `U` by applying a function to a
464 /// contained [`Ok`] value, or a fallback function to a
465 /// contained [`Err`] value.
467 /// This function can be used to unpack a successful result
468 /// while handling an error.
470 /// [`Ok`]: enum.Result.html#variant.Ok
471 /// [`Err`]: enum.Result.html#variant.Err
478 /// #![feature(result_map_or_else)]
481 /// let x : Result<_, &str> = Ok("foo");
482 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);
484 /// let x : Result<&str, _> = Err("bar");
485 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
488 #[unstable(feature = "result_map_or_else", issue = "53268")]
489 pub fn map_or_else<U, M: FnOnce(T) -> U, F: FnOnce(E) -> U>(self, fallback: F, map: M) -> U {
490 self.map(map).unwrap_or_else(fallback)
493 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
494 /// contained [`Err`] value, leaving an [`Ok`] value untouched.
496 /// This function can be used to pass through a successful result while handling
499 /// [`Ok`]: enum.Result.html#variant.Ok
500 /// [`Err`]: enum.Result.html#variant.Err
507 /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
509 /// let x: Result<u32, u32> = Ok(2);
510 /// assert_eq!(x.map_err(stringify), Ok(2));
512 /// let x: Result<u32, u32> = Err(13);
513 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
516 #[stable(feature = "rust1", since = "1.0.0")]
517 pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> {
524 /////////////////////////////////////////////////////////////////////////
525 // Iterator constructors
526 /////////////////////////////////////////////////////////////////////////
528 /// Returns an iterator over the possibly contained value.
530 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
537 /// let x: Result<u32, &str> = Ok(7);
538 /// assert_eq!(x.iter().next(), Some(&7));
540 /// let x: Result<u32, &str> = Err("nothing!");
541 /// assert_eq!(x.iter().next(), None);
544 #[stable(feature = "rust1", since = "1.0.0")]
545 pub fn iter(&self) -> Iter<T> {
546 Iter { inner: self.as_ref().ok() }
549 /// Returns a mutable iterator over the possibly contained value.
551 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
558 /// let mut x: Result<u32, &str> = Ok(7);
559 /// match x.iter_mut().next() {
560 /// Some(v) => *v = 40,
563 /// assert_eq!(x, Ok(40));
565 /// let mut x: Result<u32, &str> = Err("nothing!");
566 /// assert_eq!(x.iter_mut().next(), None);
569 #[stable(feature = "rust1", since = "1.0.0")]
570 pub fn iter_mut(&mut self) -> IterMut<T> {
571 IterMut { inner: self.as_mut().ok() }
574 ////////////////////////////////////////////////////////////////////////
575 // Boolean operations on the values, eager and lazy
576 /////////////////////////////////////////////////////////////////////////
578 /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
580 /// [`Ok`]: enum.Result.html#variant.Ok
581 /// [`Err`]: enum.Result.html#variant.Err
588 /// let x: Result<u32, &str> = Ok(2);
589 /// let y: Result<&str, &str> = Err("late error");
590 /// assert_eq!(x.and(y), Err("late error"));
592 /// let x: Result<u32, &str> = Err("early error");
593 /// let y: Result<&str, &str> = Ok("foo");
594 /// assert_eq!(x.and(y), Err("early error"));
596 /// let x: Result<u32, &str> = Err("not a 2");
597 /// let y: Result<&str, &str> = Err("late error");
598 /// assert_eq!(x.and(y), Err("not a 2"));
600 /// let x: Result<u32, &str> = Ok(2);
601 /// let y: Result<&str, &str> = Ok("different result type");
602 /// assert_eq!(x.and(y), Ok("different result type"));
605 #[stable(feature = "rust1", since = "1.0.0")]
606 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
613 /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
615 /// [`Ok`]: enum.Result.html#variant.Ok
616 /// [`Err`]: enum.Result.html#variant.Err
618 /// This function can be used for control flow based on `Result` values.
625 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
626 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
628 /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
629 /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
630 /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
631 /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
634 #[stable(feature = "rust1", since = "1.0.0")]
635 pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
642 /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
644 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
645 /// result of a function call, it is recommended to use [`or_else`], which is
646 /// lazily evaluated.
648 /// [`Ok`]: enum.Result.html#variant.Ok
649 /// [`Err`]: enum.Result.html#variant.Err
650 /// [`or_else`]: #method.or_else
657 /// let x: Result<u32, &str> = Ok(2);
658 /// let y: Result<u32, &str> = Err("late error");
659 /// assert_eq!(x.or(y), Ok(2));
661 /// let x: Result<u32, &str> = Err("early error");
662 /// let y: Result<u32, &str> = Ok(2);
663 /// assert_eq!(x.or(y), Ok(2));
665 /// let x: Result<u32, &str> = Err("not a 2");
666 /// let y: Result<u32, &str> = Err("late error");
667 /// assert_eq!(x.or(y), Err("late error"));
669 /// let x: Result<u32, &str> = Ok(2);
670 /// let y: Result<u32, &str> = Ok(100);
671 /// assert_eq!(x.or(y), Ok(2));
674 #[stable(feature = "rust1", since = "1.0.0")]
675 pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
682 /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
684 /// This function can be used for control flow based on result values.
686 /// [`Ok`]: enum.Result.html#variant.Ok
687 /// [`Err`]: enum.Result.html#variant.Err
694 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
695 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
697 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
698 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
699 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
700 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
703 #[stable(feature = "rust1", since = "1.0.0")]
704 pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
711 /// Unwraps a result, yielding the content of an [`Ok`].
712 /// Else, it returns `optb`.
714 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
715 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
716 /// which is lazily evaluated.
718 /// [`Ok`]: enum.Result.html#variant.Ok
719 /// [`Err`]: enum.Result.html#variant.Err
720 /// [`unwrap_or_else`]: #method.unwrap_or_else
728 /// let x: Result<u32, &str> = Ok(9);
729 /// assert_eq!(x.unwrap_or(optb), 9);
731 /// let x: Result<u32, &str> = Err("error");
732 /// assert_eq!(x.unwrap_or(optb), optb);
735 #[stable(feature = "rust1", since = "1.0.0")]
736 pub fn unwrap_or(self, optb: T) -> T {
743 /// Unwraps a result, yielding the content of an [`Ok`].
744 /// If the value is an [`Err`] then it calls `op` with its value.
746 /// [`Ok`]: enum.Result.html#variant.Ok
747 /// [`Err`]: enum.Result.html#variant.Err
754 /// fn count(x: &str) -> usize { x.len() }
756 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
757 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
760 #[stable(feature = "rust1", since = "1.0.0")]
761 pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
769 impl<T, E: fmt::Debug> Result<T, E> {
770 /// Unwraps a result, yielding the content of an [`Ok`].
774 /// Panics if the value is an [`Err`], with a panic message provided by the
777 /// [`Ok`]: enum.Result.html#variant.Ok
778 /// [`Err`]: enum.Result.html#variant.Err
785 /// let x: Result<u32, &str> = Ok(2);
786 /// assert_eq!(x.unwrap(), 2);
789 /// ```{.should_panic}
790 /// let x: Result<u32, &str> = Err("emergency failure");
791 /// x.unwrap(); // panics with `emergency failure`
794 #[stable(feature = "rust1", since = "1.0.0")]
795 pub fn unwrap(self) -> T {
798 Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", e),
802 /// Unwraps a result, yielding the content of an [`Ok`].
806 /// Panics if the value is an [`Err`], with a panic message including the
807 /// passed message, and the content of the [`Err`].
809 /// [`Ok`]: enum.Result.html#variant.Ok
810 /// [`Err`]: enum.Result.html#variant.Err
816 /// ```{.should_panic}
817 /// let x: Result<u32, &str> = Err("emergency failure");
818 /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
821 #[stable(feature = "result_expect", since = "1.4.0")]
822 pub fn expect(self, msg: &str) -> T {
825 Err(e) => unwrap_failed(msg, e),
830 impl<T: fmt::Debug, E> Result<T, E> {
831 /// Unwraps a result, yielding the content of an [`Err`].
835 /// Panics if the value is an [`Ok`], with a custom panic message provided
836 /// by the [`Ok`]'s value.
838 /// [`Ok`]: enum.Result.html#variant.Ok
839 /// [`Err`]: enum.Result.html#variant.Err
844 /// ```{.should_panic}
845 /// let x: Result<u32, &str> = Ok(2);
846 /// x.unwrap_err(); // panics with `2`
850 /// let x: Result<u32, &str> = Err("emergency failure");
851 /// assert_eq!(x.unwrap_err(), "emergency failure");
854 #[stable(feature = "rust1", since = "1.0.0")]
855 pub fn unwrap_err(self) -> E {
857 Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", t),
862 /// Unwraps a result, yielding the content of an [`Err`].
866 /// Panics if the value is an [`Ok`], with a panic message including the
867 /// passed message, and the content of the [`Ok`].
869 /// [`Ok`]: enum.Result.html#variant.Ok
870 /// [`Err`]: enum.Result.html#variant.Err
876 /// ```{.should_panic}
877 /// let x: Result<u32, &str> = Ok(10);
878 /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
881 #[stable(feature = "result_expect_err", since = "1.17.0")]
882 pub fn expect_err(self, msg: &str) -> E {
884 Ok(t) => unwrap_failed(msg, t),
890 impl<T: Default, E> Result<T, E> {
891 /// Returns the contained value or a default
893 /// Consumes the `self` argument then, if [`Ok`], returns the contained
894 /// value, otherwise if [`Err`], returns the default value for that
899 /// Convert a string to an integer, turning poorly-formed strings
900 /// into 0 (the default value for integers). [`parse`] converts
901 /// a string to any other type that implements [`FromStr`], returning an
902 /// [`Err`] on error.
905 /// let good_year_from_input = "1909";
906 /// let bad_year_from_input = "190blarg";
907 /// let good_year = good_year_from_input.parse().unwrap_or_default();
908 /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
910 /// assert_eq!(1909, good_year);
911 /// assert_eq!(0, bad_year);
914 /// [`parse`]: ../../std/primitive.str.html#method.parse
915 /// [`FromStr`]: ../../std/str/trait.FromStr.html
916 /// [`Ok`]: enum.Result.html#variant.Ok
917 /// [`Err`]: enum.Result.html#variant.Err
919 #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
920 pub fn unwrap_or_default(self) -> T {
923 Err(_) => Default::default(),
928 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
929 impl<T: Deref, E> Result<T, E> {
930 /// Converts from `&Result<T, E>` to `Result<&T::Target, &E>`.
932 /// Leaves the original Result in-place, creating a new one with a reference
933 /// to the original one, additionally coercing the `Ok` arm of the Result via
935 pub fn deref_ok(&self) -> Result<&T::Target, &E> {
936 self.as_ref().map(|t| t.deref())
940 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
941 impl<T, E: Deref> Result<T, E> {
942 /// Converts from `&Result<T, E>` to `Result<&T, &E::Target>`.
944 /// Leaves the original Result in-place, creating a new one with a reference
945 /// to the original one, additionally coercing the `Err` arm of the Result via
947 pub fn deref_err(&self) -> Result<&T, &E::Target>
949 self.as_ref().map_err(|e| e.deref())
953 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
954 impl<T: Deref, E: Deref> Result<T, E> {
955 /// Converts from `&Result<T, E>` to `Result<&T::Target, &E::Target>`.
957 /// Leaves the original Result in-place, creating a new one with a reference
958 /// to the original one, additionally coercing both the `Ok` and `Err` arms
959 /// of the Result via `Deref`.
960 pub fn deref(&self) -> Result<&T::Target, &E::Target>
962 self.as_ref().map(|t| t.deref()).map_err(|e| e.deref())
966 impl<T, E> Result<Option<T>, E> {
967 /// Transposes a `Result` of an `Option` into an `Option` of a `Result`.
969 /// `Ok(None)` will be mapped to `None`.
970 /// `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`.
975 /// #[derive(Debug, Eq, PartialEq)]
978 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
979 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
980 /// assert_eq!(x.transpose(), y);
983 #[stable(feature = "transpose_result", since = "1.33.0")]
984 pub fn transpose(self) -> Option<Result<T, E>> {
986 Ok(Some(x)) => Some(Ok(x)),
988 Err(e) => Some(Err(e)),
993 // This is a separate function to reduce the code size of the methods
996 fn unwrap_failed<E: fmt::Debug>(msg: &str, error: E) -> ! {
997 panic!("{}: {:?}", msg, error)
1000 /////////////////////////////////////////////////////////////////////////////
1001 // Trait implementations
1002 /////////////////////////////////////////////////////////////////////////////
1004 #[stable(feature = "rust1", since = "1.0.0")]
1005 impl<T, E> IntoIterator for Result<T, E> {
1007 type IntoIter = IntoIter<T>;
1009 /// Returns a consuming iterator over the possibly contained value.
1011 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
1018 /// let x: Result<u32, &str> = Ok(5);
1019 /// let v: Vec<u32> = x.into_iter().collect();
1020 /// assert_eq!(v, [5]);
1022 /// let x: Result<u32, &str> = Err("nothing!");
1023 /// let v: Vec<u32> = x.into_iter().collect();
1024 /// assert_eq!(v, []);
1027 fn into_iter(self) -> IntoIter<T> {
1028 IntoIter { inner: self.ok() }
1032 #[stable(since = "1.4.0", feature = "result_iter")]
1033 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
1035 type IntoIter = Iter<'a, T>;
1037 fn into_iter(self) -> Iter<'a, T> {
1042 #[stable(since = "1.4.0", feature = "result_iter")]
1043 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
1044 type Item = &'a mut T;
1045 type IntoIter = IterMut<'a, T>;
1047 fn into_iter(self) -> IterMut<'a, T> {
1052 /////////////////////////////////////////////////////////////////////////////
1053 // The Result Iterators
1054 /////////////////////////////////////////////////////////////////////////////
1056 /// An iterator over a reference to the [`Ok`] variant of a [`Result`].
1058 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1060 /// Created by [`Result::iter`].
1062 /// [`Ok`]: enum.Result.html#variant.Ok
1063 /// [`Result`]: enum.Result.html
1064 /// [`Result::iter`]: enum.Result.html#method.iter
1066 #[stable(feature = "rust1", since = "1.0.0")]
1067 pub struct Iter<'a, T: 'a> { inner: Option<&'a T> }
1069 #[stable(feature = "rust1", since = "1.0.0")]
1070 impl<'a, T> Iterator for Iter<'a, T> {
1074 fn next(&mut self) -> Option<&'a T> { self.inner.take() }
1076 fn size_hint(&self) -> (usize, Option<usize>) {
1077 let n = if self.inner.is_some() {1} else {0};
1082 #[stable(feature = "rust1", since = "1.0.0")]
1083 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1085 fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
1088 #[stable(feature = "rust1", since = "1.0.0")]
1089 impl<T> ExactSizeIterator for Iter<'_, T> {}
1091 #[stable(feature = "fused", since = "1.26.0")]
1092 impl<T> FusedIterator for Iter<'_, T> {}
1094 #[unstable(feature = "trusted_len", issue = "37572")]
1095 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1097 #[stable(feature = "rust1", since = "1.0.0")]
1098 impl<T> Clone for Iter<'_, T> {
1100 fn clone(&self) -> Self { Iter { inner: self.inner } }
1103 /// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
1105 /// Created by [`Result::iter_mut`].
1107 /// [`Ok`]: enum.Result.html#variant.Ok
1108 /// [`Result`]: enum.Result.html
1109 /// [`Result::iter_mut`]: enum.Result.html#method.iter_mut
1111 #[stable(feature = "rust1", since = "1.0.0")]
1112 pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
1114 #[stable(feature = "rust1", since = "1.0.0")]
1115 impl<'a, T> Iterator for IterMut<'a, T> {
1116 type Item = &'a mut T;
1119 fn next(&mut self) -> Option<&'a mut T> { self.inner.take() }
1121 fn size_hint(&self) -> (usize, Option<usize>) {
1122 let n = if self.inner.is_some() {1} else {0};
1127 #[stable(feature = "rust1", since = "1.0.0")]
1128 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1130 fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
1133 #[stable(feature = "rust1", since = "1.0.0")]
1134 impl<T> ExactSizeIterator for IterMut<'_, T> {}
1136 #[stable(feature = "fused", since = "1.26.0")]
1137 impl<T> FusedIterator for IterMut<'_, T> {}
1139 #[unstable(feature = "trusted_len", issue = "37572")]
1140 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1142 /// An iterator over the value in a [`Ok`] variant of a [`Result`].
1144 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1146 /// This struct is created by the [`into_iter`] method on
1147 /// [`Result`][`Result`] (provided by the [`IntoIterator`] trait).
1149 /// [`Ok`]: enum.Result.html#variant.Ok
1150 /// [`Result`]: enum.Result.html
1151 /// [`into_iter`]: ../iter/trait.IntoIterator.html#tymethod.into_iter
1152 /// [`IntoIterator`]: ../iter/trait.IntoIterator.html
1153 #[derive(Clone, Debug)]
1154 #[stable(feature = "rust1", since = "1.0.0")]
1155 pub struct IntoIter<T> { inner: Option<T> }
1157 #[stable(feature = "rust1", since = "1.0.0")]
1158 impl<T> Iterator for IntoIter<T> {
1162 fn next(&mut self) -> Option<T> { self.inner.take() }
1164 fn size_hint(&self) -> (usize, Option<usize>) {
1165 let n = if self.inner.is_some() {1} else {0};
1170 #[stable(feature = "rust1", since = "1.0.0")]
1171 impl<T> DoubleEndedIterator for IntoIter<T> {
1173 fn next_back(&mut self) -> Option<T> { self.inner.take() }
1176 #[stable(feature = "rust1", since = "1.0.0")]
1177 impl<T> ExactSizeIterator for IntoIter<T> {}
1179 #[stable(feature = "fused", since = "1.26.0")]
1180 impl<T> FusedIterator for IntoIter<T> {}
1182 #[unstable(feature = "trusted_len", issue = "37572")]
1183 unsafe impl<A> TrustedLen for IntoIter<A> {}
1185 /////////////////////////////////////////////////////////////////////////////
1187 /////////////////////////////////////////////////////////////////////////////
1189 #[stable(feature = "rust1", since = "1.0.0")]
1190 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
1191 /// Takes each element in the `Iterator`: if it is an `Err`, no further
1192 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
1193 /// container with the values of each `Result` is returned.
1195 /// Here is an example which increments every integer in a vector,
1196 /// checking for overflow:
1199 /// let v = vec![1, 2];
1200 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1201 /// x.checked_add(1).ok_or("Overflow!")
1203 /// assert!(res == Ok(vec![2, 3]));
1206 fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
1207 // FIXME(#11084): This could be replaced with Iterator::scan when this
1208 // performance bug is closed.
1210 struct Adapter<Iter, E> {
1215 impl<T, E, Iter: Iterator<Item=Result<T, E>>> Iterator for Adapter<Iter, E> {
1219 fn next(&mut self) -> Option<T> {
1220 match self.iter.next() {
1221 Some(Ok(value)) => Some(value),
1223 self.err = Some(err);
1230 fn size_hint(&self) -> (usize, Option<usize>) {
1231 let (_min, max) = self.iter.size_hint();
1236 let mut adapter = Adapter { iter: iter.into_iter(), err: None };
1237 let v: V = FromIterator::from_iter(adapter.by_ref());
1240 Some(err) => Err(err),
1246 #[unstable(feature = "try_trait", issue = "42327")]
1247 impl<T,E> ops::Try for Result<T, E> {
1252 fn into_result(self) -> Self {
1257 fn from_ok(v: T) -> Self {
1262 fn from_error(v: E) -> Self {