1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Error handling with the `Result` type.
13 //! [`Result<T, E>`][`Result`] is the type used for returning and propagating
14 //! errors. It is an enum with the variants, [`Ok(T)`], representing
15 //! success and containing a value, and [`Err(E)`], representing error
16 //! and containing an error value.
19 //! # #[allow(dead_code)]
20 //! enum Result<T, E> {
26 //! Functions return [`Result`] whenever errors are expected and
27 //! recoverable. In the `std` crate, [`Result`] is most prominently used
28 //! for [I/O](../../std/io/index.html).
30 //! A simple function returning [`Result`] might be
31 //! defined and used like so:
35 //! enum Version { Version1, Version2 }
37 //! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
38 //! match header.get(0) {
39 //! None => Err("invalid header length"),
40 //! Some(&1) => Ok(Version::Version1),
41 //! Some(&2) => Ok(Version::Version2),
42 //! Some(_) => Err("invalid version"),
46 //! let version = parse_version(&[1, 2, 3, 4]);
48 //! Ok(v) => println!("working with version: {:?}", v),
49 //! Err(e) => println!("error parsing header: {:?}", e),
53 //! Pattern matching on [`Result`]s is clear and straightforward for
54 //! simple cases, but [`Result`] comes with some convenience methods
55 //! that make working with it more succinct.
58 //! let good_result: Result<i32, i32> = Ok(10);
59 //! let bad_result: Result<i32, i32> = Err(10);
61 //! // The `is_ok` and `is_err` methods do what they say.
62 //! assert!(good_result.is_ok() && !good_result.is_err());
63 //! assert!(bad_result.is_err() && !bad_result.is_ok());
65 //! // `map` consumes the `Result` and produces another.
66 //! let good_result: Result<i32, i32> = good_result.map(|i| i + 1);
67 //! let bad_result: Result<i32, i32> = bad_result.map(|i| i - 1);
69 //! // Use `and_then` to continue the computation.
70 //! let good_result: Result<bool, i32> = good_result.and_then(|i| Ok(i == 11));
72 //! // Use `or_else` to handle the error.
73 //! let bad_result: Result<i32, i32> = bad_result.or_else(|i| Ok(i + 20));
75 //! // Consume the result and return the contents with `unwrap`.
76 //! let final_awesome_result = good_result.unwrap();
79 //! # Results must be used
81 //! A common problem with using return values to indicate errors is
82 //! that it is easy to ignore the return value, thus failing to handle
83 //! the error. [`Result`] is annotated with the `#[must_use]` attribute,
84 //! which will cause the compiler to issue a warning when a Result
85 //! value is ignored. This makes [`Result`] especially useful with
86 //! functions that may encounter errors but don't otherwise return a
89 //! Consider the [`write_all`] method defined for I/O types
90 //! by the [`Write`] trait:
96 //! fn write_all(&mut self, bytes: &[u8]) -> Result<(), io::Error>;
100 //! *Note: The actual definition of [`Write`] uses [`io::Result`], which
101 //! is just a synonym for [`Result`]`<T, `[`io::Error`]`>`.*
103 //! This method doesn't produce a value, but the write may
104 //! fail. It's crucial to handle the error case, and *not* write
105 //! something like this:
108 //! # #![allow(unused_must_use)] // \o/
109 //! use std::fs::File;
110 //! use std::io::prelude::*;
112 //! let mut file = File::create("valuable_data.txt").unwrap();
113 //! // If `write_all` errors, then we'll never know, because the return
114 //! // value is ignored.
115 //! file.write_all(b"important message");
118 //! If you *do* write that in Rust, the compiler will give you a
119 //! warning (by default, controlled by the `unused_must_use` lint).
121 //! You might instead, if you don't want to handle the error, simply
122 //! assert success with [`expect`]. This will panic if the
123 //! write fails, providing a marginally useful message indicating why:
126 //! use std::fs::File;
127 //! use std::io::prelude::*;
129 //! let mut file = File::create("valuable_data.txt").unwrap();
130 //! file.write_all(b"important message").expect("failed to write message");
133 //! You might also simply assert success:
136 //! # use std::fs::File;
137 //! # use std::io::prelude::*;
138 //! # let mut file = File::create("valuable_data.txt").unwrap();
139 //! assert!(file.write_all(b"important message").is_ok());
142 //! Or propagate the error up the call stack with [`?`]:
145 //! # use std::fs::File;
146 //! # use std::io::prelude::*;
148 //! # #[allow(dead_code)]
149 //! fn write_message() -> io::Result<()> {
150 //! let mut file = File::create("valuable_data.txt")?;
151 //! file.write_all(b"important message")?;
158 //! When writing code that calls many functions that return the
159 //! [`Result`] type, the error handling can be tedious. The [`?`]
160 //! syntax hides some of the boilerplate of propagating errors up the
163 //! It replaces this:
166 //! # #![allow(dead_code)]
167 //! use std::fs::File;
168 //! use std::io::prelude::*;
177 //! fn write_info(info: &Info) -> io::Result<()> {
178 //! // Early return on error
179 //! let mut file = match File::create("my_best_friends.txt") {
180 //! Err(e) => return Err(e),
183 //! if let Err(e) = file.write_all(format!("name: {}\n", info.name).as_bytes()) {
186 //! if let Err(e) = file.write_all(format!("age: {}\n", info.age).as_bytes()) {
189 //! if let Err(e) = file.write_all(format!("rating: {}\n", info.rating).as_bytes()) {
199 //! # #![allow(dead_code)]
200 //! use std::fs::File;
201 //! use std::io::prelude::*;
210 //! fn write_info(info: &Info) -> io::Result<()> {
211 //! let mut file = File::create("my_best_friends.txt")?;
212 //! // Early return on error
213 //! file.write_all(format!("name: {}\n", info.name).as_bytes())?;
214 //! file.write_all(format!("age: {}\n", info.age).as_bytes())?;
215 //! file.write_all(format!("rating: {}\n", info.rating).as_bytes())?;
220 //! *It's much nicer!*
222 //! Ending the expression with [`?`] will result in the unwrapped
223 //! success ([`Ok`]) value, unless the result is [`Err`], in which case
224 //! [`Err`] is returned early from the enclosing function.
226 //! [`?`] can only be used in functions that return [`Result`] because of the
227 //! early return of [`Err`] that it provides.
229 //! [`expect`]: enum.Result.html#method.expect
230 //! [`Write`]: ../../std/io/trait.Write.html
231 //! [`write_all`]: ../../std/io/trait.Write.html#method.write_all
232 //! [`io::Result`]: ../../std/io/type.Result.html
233 //! [`?`]: ../../std/macro.try.html
234 //! [`Result`]: enum.Result.html
235 //! [`Ok(T)`]: enum.Result.html#variant.Ok
236 //! [`Err(E)`]: enum.Result.html#variant.Err
237 //! [`io::Error`]: ../../std/io/struct.Error.html
238 //! [`Ok`]: enum.Result.html#variant.Ok
239 //! [`Err`]: enum.Result.html#variant.Err
241 #![stable(feature = "rust1", since = "1.0.0")]
244 use iter::{FromIterator, FusedIterator, TrustedLen};
247 /// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]).
249 /// See the [`std::result`](index.html) module documentation for details.
251 /// [`Ok`]: enum.Result.html#variant.Ok
252 /// [`Err`]: enum.Result.html#variant.Err
253 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
255 #[stable(feature = "rust1", since = "1.0.0")]
256 pub enum Result<T, E> {
257 /// Contains the success value
258 #[stable(feature = "rust1", since = "1.0.0")]
259 Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
261 /// Contains the error value
262 #[stable(feature = "rust1", since = "1.0.0")]
263 Err(#[stable(feature = "rust1", since = "1.0.0")] E),
266 /////////////////////////////////////////////////////////////////////////////
267 // Type implementation
268 /////////////////////////////////////////////////////////////////////////////
270 impl<T, E> Result<T, E> {
271 /////////////////////////////////////////////////////////////////////////
272 // Querying the contained values
273 /////////////////////////////////////////////////////////////////////////
275 /// Returns `true` if the result is [`Ok`].
277 /// [`Ok`]: enum.Result.html#variant.Ok
284 /// let x: Result<i32, &str> = Ok(-3);
285 /// assert_eq!(x.is_ok(), true);
287 /// let x: Result<i32, &str> = Err("Some error message");
288 /// assert_eq!(x.is_ok(), false);
291 #[stable(feature = "rust1", since = "1.0.0")]
292 pub fn is_ok(&self) -> bool {
299 /// Returns `true` if the result is [`Err`].
301 /// [`Err`]: enum.Result.html#variant.Err
308 /// let x: Result<i32, &str> = Ok(-3);
309 /// assert_eq!(x.is_err(), false);
311 /// let x: Result<i32, &str> = Err("Some error message");
312 /// assert_eq!(x.is_err(), true);
315 #[stable(feature = "rust1", since = "1.0.0")]
316 pub fn is_err(&self) -> bool {
320 /////////////////////////////////////////////////////////////////////////
321 // Adapter for each variant
322 /////////////////////////////////////////////////////////////////////////
324 /// Converts from `Result<T, E>` to [`Option<T>`].
326 /// Converts `self` into an [`Option<T>`], consuming `self`,
327 /// and discarding the error, if any.
329 /// [`Option<T>`]: ../../std/option/enum.Option.html
336 /// let x: Result<u32, &str> = Ok(2);
337 /// assert_eq!(x.ok(), Some(2));
339 /// let x: Result<u32, &str> = Err("Nothing here");
340 /// assert_eq!(x.ok(), None);
343 #[stable(feature = "rust1", since = "1.0.0")]
344 pub fn ok(self) -> Option<T> {
351 /// Converts from `Result<T, E>` to [`Option<E>`].
353 /// Converts `self` into an [`Option<E>`], consuming `self`,
354 /// and discarding the success value, if any.
356 /// [`Option<E>`]: ../../std/option/enum.Option.html
363 /// let x: Result<u32, &str> = Ok(2);
364 /// assert_eq!(x.err(), None);
366 /// let x: Result<u32, &str> = Err("Nothing here");
367 /// assert_eq!(x.err(), Some("Nothing here"));
370 #[stable(feature = "rust1", since = "1.0.0")]
371 pub fn err(self) -> Option<E> {
378 /////////////////////////////////////////////////////////////////////////
379 // Adapter for working with references
380 /////////////////////////////////////////////////////////////////////////
382 /// Converts from `Result<T, E>` to `Result<&T, &E>`.
384 /// Produces a new `Result`, containing a reference
385 /// into the original, leaving the original in place.
392 /// let x: Result<u32, &str> = Ok(2);
393 /// assert_eq!(x.as_ref(), Ok(&2));
395 /// let x: Result<u32, &str> = Err("Error");
396 /// assert_eq!(x.as_ref(), Err(&"Error"));
399 #[stable(feature = "rust1", since = "1.0.0")]
400 pub fn as_ref(&self) -> Result<&T, &E> {
403 Err(ref x) => Err(x),
407 /// Converts from `Result<T, E>` to `Result<&mut T, &mut E>`.
414 /// fn mutate(r: &mut Result<i32, i32>) {
415 /// match r.as_mut() {
416 /// Ok(v) => *v = 42,
417 /// Err(e) => *e = 0,
421 /// let mut x: Result<i32, i32> = Ok(2);
423 /// assert_eq!(x.unwrap(), 42);
425 /// let mut x: Result<i32, i32> = Err(13);
427 /// assert_eq!(x.unwrap_err(), 0);
430 #[stable(feature = "rust1", since = "1.0.0")]
431 pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
433 Ok(ref mut x) => Ok(x),
434 Err(ref mut x) => Err(x),
438 /////////////////////////////////////////////////////////////////////////
439 // Transforming contained values
440 /////////////////////////////////////////////////////////////////////////
442 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
443 /// contained [`Ok`] value, leaving an [`Err`] value untouched.
445 /// This function can be used to compose the results of two functions.
447 /// [`Ok`]: enum.Result.html#variant.Ok
448 /// [`Err`]: enum.Result.html#variant.Err
452 /// Print the numbers on each line of a string multiplied by two.
455 /// let line = "1\n2\n3\n4\n";
457 /// for num in line.lines() {
458 /// match num.parse::<i32>().map(|i| i * 2) {
459 /// Ok(n) => println!("{}", n),
465 #[stable(feature = "rust1", since = "1.0.0")]
466 pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
473 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
474 /// contained [`Err`] value, leaving an [`Ok`] value untouched.
476 /// This function can be used to pass through a successful result while handling
479 /// [`Ok`]: enum.Result.html#variant.Ok
480 /// [`Err`]: enum.Result.html#variant.Err
487 /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
489 /// let x: Result<u32, u32> = Ok(2);
490 /// assert_eq!(x.map_err(stringify), Ok(2));
492 /// let x: Result<u32, u32> = Err(13);
493 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
496 #[stable(feature = "rust1", since = "1.0.0")]
497 pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> {
504 /////////////////////////////////////////////////////////////////////////
505 // Iterator constructors
506 /////////////////////////////////////////////////////////////////////////
508 /// Returns an iterator over the possibly contained value.
510 /// The iterator yields one value if the result is [`Ok`], otherwise none.
517 /// let x: Result<u32, &str> = Ok(7);
518 /// assert_eq!(x.iter().next(), Some(&7));
520 /// let x: Result<u32, &str> = Err("nothing!");
521 /// assert_eq!(x.iter().next(), None);
524 /// [`Ok`]: enum.Result.html#variant.Ok
526 #[stable(feature = "rust1", since = "1.0.0")]
527 pub fn iter(&self) -> Iter<T> {
528 Iter { inner: self.as_ref().ok() }
531 /// Returns a mutable iterator over the possibly contained value.
533 /// The iterator yields one value if the result is [`Ok`], otherwise none.
540 /// let mut x: Result<u32, &str> = Ok(7);
541 /// match x.iter_mut().next() {
542 /// Some(v) => *v = 40,
545 /// assert_eq!(x, Ok(40));
547 /// let mut x: Result<u32, &str> = Err("nothing!");
548 /// assert_eq!(x.iter_mut().next(), None);
551 /// [`Ok`]: enum.Result.html#variant.Ok
553 #[stable(feature = "rust1", since = "1.0.0")]
554 pub fn iter_mut(&mut self) -> IterMut<T> {
555 IterMut { inner: self.as_mut().ok() }
558 ////////////////////////////////////////////////////////////////////////
559 // Boolean operations on the values, eager and lazy
560 /////////////////////////////////////////////////////////////////////////
562 /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
564 /// [`Ok`]: enum.Result.html#variant.Ok
565 /// [`Err`]: enum.Result.html#variant.Err
572 /// let x: Result<u32, &str> = Ok(2);
573 /// let y: Result<&str, &str> = Err("late error");
574 /// assert_eq!(x.and(y), Err("late error"));
576 /// let x: Result<u32, &str> = Err("early error");
577 /// let y: Result<&str, &str> = Ok("foo");
578 /// assert_eq!(x.and(y), Err("early error"));
580 /// let x: Result<u32, &str> = Err("not a 2");
581 /// let y: Result<&str, &str> = Err("late error");
582 /// assert_eq!(x.and(y), Err("not a 2"));
584 /// let x: Result<u32, &str> = Ok(2);
585 /// let y: Result<&str, &str> = Ok("different result type");
586 /// assert_eq!(x.and(y), Ok("different result type"));
589 #[stable(feature = "rust1", since = "1.0.0")]
590 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
597 /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
599 /// [`Ok`]: enum.Result.html#variant.Ok
600 /// [`Err`]: enum.Result.html#variant.Err
602 /// This function can be used for control flow based on `Result` values.
609 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
610 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
612 /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
613 /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
614 /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
615 /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
618 #[stable(feature = "rust1", since = "1.0.0")]
619 pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
626 /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
628 /// [`Ok`]: enum.Result.html#variant.Ok
629 /// [`Err`]: enum.Result.html#variant.Err
636 /// let x: Result<u32, &str> = Ok(2);
637 /// let y: Result<u32, &str> = Err("late error");
638 /// assert_eq!(x.or(y), Ok(2));
640 /// let x: Result<u32, &str> = Err("early error");
641 /// let y: Result<u32, &str> = Ok(2);
642 /// assert_eq!(x.or(y), Ok(2));
644 /// let x: Result<u32, &str> = Err("not a 2");
645 /// let y: Result<u32, &str> = Err("late error");
646 /// assert_eq!(x.or(y), Err("late error"));
648 /// let x: Result<u32, &str> = Ok(2);
649 /// let y: Result<u32, &str> = Ok(100);
650 /// assert_eq!(x.or(y), Ok(2));
653 #[stable(feature = "rust1", since = "1.0.0")]
654 pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
661 /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
663 /// This function can be used for control flow based on result values.
665 /// [`Ok`]: enum.Result.html#variant.Ok
666 /// [`Err`]: enum.Result.html#variant.Err
673 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
674 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
676 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
677 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
678 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
679 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
682 #[stable(feature = "rust1", since = "1.0.0")]
683 pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
690 /// Unwraps a result, yielding the content of an [`Ok`].
691 /// Else, it returns `optb`.
693 /// [`Ok`]: enum.Result.html#variant.Ok
694 /// [`Err`]: enum.Result.html#variant.Err
702 /// let x: Result<u32, &str> = Ok(9);
703 /// assert_eq!(x.unwrap_or(optb), 9);
705 /// let x: Result<u32, &str> = Err("error");
706 /// assert_eq!(x.unwrap_or(optb), optb);
709 #[stable(feature = "rust1", since = "1.0.0")]
710 pub fn unwrap_or(self, optb: T) -> T {
717 /// Unwraps a result, yielding the content of an [`Ok`].
718 /// If the value is an [`Err`] then it calls `op` with its value.
720 /// [`Ok`]: enum.Result.html#variant.Ok
721 /// [`Err`]: enum.Result.html#variant.Err
728 /// fn count(x: &str) -> usize { x.len() }
730 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
731 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
734 #[stable(feature = "rust1", since = "1.0.0")]
735 pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
743 impl<T, E: fmt::Debug> Result<T, E> {
744 /// Unwraps a result, yielding the content of an [`Ok`].
748 /// Panics if the value is an [`Err`], with a panic message provided by the
751 /// [`Ok`]: enum.Result.html#variant.Ok
752 /// [`Err`]: enum.Result.html#variant.Err
759 /// let x: Result<u32, &str> = Ok(2);
760 /// assert_eq!(x.unwrap(), 2);
763 /// ```{.should_panic}
764 /// let x: Result<u32, &str> = Err("emergency failure");
765 /// x.unwrap(); // panics with `emergency failure`
768 #[stable(feature = "rust1", since = "1.0.0")]
769 pub fn unwrap(self) -> T {
772 Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", e),
776 /// Unwraps a result, yielding the content of an [`Ok`].
780 /// Panics if the value is an [`Err`], with a panic message including the
781 /// passed message, and the content of the [`Err`].
783 /// [`Ok`]: enum.Result.html#variant.Ok
784 /// [`Err`]: enum.Result.html#variant.Err
790 /// ```{.should_panic}
791 /// let x: Result<u32, &str> = Err("emergency failure");
792 /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
795 #[stable(feature = "result_expect", since = "1.4.0")]
796 pub fn expect(self, msg: &str) -> T {
799 Err(e) => unwrap_failed(msg, e),
804 impl<T: fmt::Debug, E> Result<T, E> {
805 /// Unwraps a result, yielding the content of an [`Err`].
809 /// Panics if the value is an [`Ok`], with a custom panic message provided
810 /// by the [`Ok`]'s value.
812 /// [`Ok`]: enum.Result.html#variant.Ok
813 /// [`Err`]: enum.Result.html#variant.Err
818 /// ```{.should_panic}
819 /// let x: Result<u32, &str> = Ok(2);
820 /// x.unwrap_err(); // panics with `2`
824 /// let x: Result<u32, &str> = Err("emergency failure");
825 /// assert_eq!(x.unwrap_err(), "emergency failure");
828 #[stable(feature = "rust1", since = "1.0.0")]
829 pub fn unwrap_err(self) -> E {
831 Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", t),
836 /// Unwraps a result, yielding the content of an [`Err`].
840 /// Panics if the value is an [`Ok`], with a panic message including the
841 /// passed message, and the content of the [`Ok`].
843 /// [`Ok`]: enum.Result.html#variant.Ok
844 /// [`Err`]: enum.Result.html#variant.Err
850 /// ```{.should_panic}
851 /// let x: Result<u32, &str> = Ok(10);
852 /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
855 #[stable(feature = "result_expect_err", since = "1.17.0")]
856 pub fn expect_err(self, msg: &str) -> E {
858 Ok(t) => unwrap_failed(msg, t),
864 impl<T: Default, E> Result<T, E> {
865 /// Returns the contained value or a default
867 /// Consumes the `self` argument then, if [`Ok`], returns the contained
868 /// value, otherwise if [`Err`], returns the default value for that
873 /// Convert a string to an integer, turning poorly-formed strings
874 /// into 0 (the default value for integers). [`parse`] converts
875 /// a string to any other type that implements [`FromStr`], returning an
876 /// [`Err`] on error.
879 /// let good_year_from_input = "1909";
880 /// let bad_year_from_input = "190blarg";
881 /// let good_year = good_year_from_input.parse().unwrap_or_default();
882 /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
884 /// assert_eq!(1909, good_year);
885 /// assert_eq!(0, bad_year);
888 /// [`parse`]: ../../std/primitive.str.html#method.parse
889 /// [`FromStr`]: ../../std/str/trait.FromStr.html
890 /// [`Ok`]: enum.Result.html#variant.Ok
891 /// [`Err`]: enum.Result.html#variant.Err
893 #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
894 pub fn unwrap_or_default(self) -> T {
897 Err(_) => Default::default(),
902 // This is a separate function to reduce the code size of the methods
905 fn unwrap_failed<E: fmt::Debug>(msg: &str, error: E) -> ! {
906 panic!("{}: {:?}", msg, error)
909 /////////////////////////////////////////////////////////////////////////////
910 // Trait implementations
911 /////////////////////////////////////////////////////////////////////////////
913 #[stable(feature = "rust1", since = "1.0.0")]
914 impl<T, E> IntoIterator for Result<T, E> {
916 type IntoIter = IntoIter<T>;
918 /// Returns a consuming iterator over the possibly contained value.
920 /// The iterator yields one value if the result is [`Ok`], otherwise none.
927 /// let x: Result<u32, &str> = Ok(5);
928 /// let v: Vec<u32> = x.into_iter().collect();
929 /// assert_eq!(v, [5]);
931 /// let x: Result<u32, &str> = Err("nothing!");
932 /// let v: Vec<u32> = x.into_iter().collect();
933 /// assert_eq!(v, []);
936 /// [`Ok`]: enum.Result.html#variant.Ok
938 fn into_iter(self) -> IntoIter<T> {
939 IntoIter { inner: self.ok() }
943 #[stable(since = "1.4.0", feature = "result_iter")]
944 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
946 type IntoIter = Iter<'a, T>;
948 fn into_iter(self) -> Iter<'a, T> {
953 #[stable(since = "1.4.0", feature = "result_iter")]
954 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
955 type Item = &'a mut T;
956 type IntoIter = IterMut<'a, T>;
958 fn into_iter(self) -> IterMut<'a, T> {
963 /////////////////////////////////////////////////////////////////////////////
964 // The Result Iterators
965 /////////////////////////////////////////////////////////////////////////////
967 /// An iterator over a reference to the [`Ok`] variant of a [`Result`].
969 /// The iterator yields one value if the result is [`Ok`], otherwise none.
971 /// Created by [`Result::iter`].
973 /// [`Ok`]: enum.Result.html#variant.Ok
974 /// [`Result`]: enum.Result.html
975 /// [`Result::iter`]: enum.Result.html#method.iter
977 #[stable(feature = "rust1", since = "1.0.0")]
978 pub struct Iter<'a, T: 'a> { inner: Option<&'a T> }
980 #[stable(feature = "rust1", since = "1.0.0")]
981 impl<'a, T> Iterator for Iter<'a, T> {
985 fn next(&mut self) -> Option<&'a T> { self.inner.take() }
987 fn size_hint(&self) -> (usize, Option<usize>) {
988 let n = if self.inner.is_some() {1} else {0};
993 #[stable(feature = "rust1", since = "1.0.0")]
994 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
996 fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
999 #[stable(feature = "rust1", since = "1.0.0")]
1000 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
1002 #[unstable(feature = "fused", issue = "35602")]
1003 impl<'a, T> FusedIterator for Iter<'a, T> {}
1005 #[unstable(feature = "trusted_len", issue = "37572")]
1006 unsafe impl<'a, A> TrustedLen for Iter<'a, A> {}
1008 #[stable(feature = "rust1", since = "1.0.0")]
1009 impl<'a, T> Clone for Iter<'a, T> {
1010 fn clone(&self) -> Iter<'a, T> { Iter { inner: self.inner } }
1013 /// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
1015 /// Created by [`Result::iter_mut`].
1017 /// [`Ok`]: enum.Result.html#variant.Ok
1018 /// [`Result`]: enum.Result.html
1019 /// [`Result::iter_mut`]: enum.Result.html#method.iter_mut
1021 #[stable(feature = "rust1", since = "1.0.0")]
1022 pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
1024 #[stable(feature = "rust1", since = "1.0.0")]
1025 impl<'a, T> Iterator for IterMut<'a, T> {
1026 type Item = &'a mut T;
1029 fn next(&mut self) -> Option<&'a mut T> { self.inner.take() }
1031 fn size_hint(&self) -> (usize, Option<usize>) {
1032 let n = if self.inner.is_some() {1} else {0};
1037 #[stable(feature = "rust1", since = "1.0.0")]
1038 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1040 fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
1043 #[stable(feature = "rust1", since = "1.0.0")]
1044 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
1046 #[unstable(feature = "fused", issue = "35602")]
1047 impl<'a, T> FusedIterator for IterMut<'a, T> {}
1049 #[unstable(feature = "trusted_len", issue = "37572")]
1050 unsafe impl<'a, A> TrustedLen for IterMut<'a, A> {}
1052 /// An iterator over the value in a [`Ok`] variant of a [`Result`].
1054 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1056 /// This struct is created by the [`into_iter`] method on
1057 /// [`Result`][`Result`] (provided by the [`IntoIterator`] trait).
1059 /// [`Ok`]: enum.Result.html#variant.Ok
1060 /// [`Result`]: enum.Result.html
1061 /// [`into_iter`]: ../iter/trait.IntoIterator.html#tymethod.into_iter
1062 /// [`IntoIterator`]: ../iter/trait.IntoIterator.html
1063 #[derive(Clone, Debug)]
1064 #[stable(feature = "rust1", since = "1.0.0")]
1065 pub struct IntoIter<T> { inner: Option<T> }
1067 #[stable(feature = "rust1", since = "1.0.0")]
1068 impl<T> Iterator for IntoIter<T> {
1072 fn next(&mut self) -> Option<T> { self.inner.take() }
1074 fn size_hint(&self) -> (usize, Option<usize>) {
1075 let n = if self.inner.is_some() {1} else {0};
1080 #[stable(feature = "rust1", since = "1.0.0")]
1081 impl<T> DoubleEndedIterator for IntoIter<T> {
1083 fn next_back(&mut self) -> Option<T> { self.inner.take() }
1086 #[stable(feature = "rust1", since = "1.0.0")]
1087 impl<T> ExactSizeIterator for IntoIter<T> {}
1089 #[unstable(feature = "fused", issue = "35602")]
1090 impl<T> FusedIterator for IntoIter<T> {}
1092 #[unstable(feature = "trusted_len", issue = "37572")]
1093 unsafe impl<A> TrustedLen for IntoIter<A> {}
1095 /////////////////////////////////////////////////////////////////////////////
1097 /////////////////////////////////////////////////////////////////////////////
1099 #[stable(feature = "rust1", since = "1.0.0")]
1100 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
1101 /// Takes each element in the `Iterator`: if it is an `Err`, no further
1102 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
1103 /// container with the values of each `Result` is returned.
1105 /// Here is an example which increments every integer in a vector,
1106 /// checking for overflow:
1109 /// let v = vec![1, 2];
1110 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1111 /// x.checked_add(1).ok_or("Overflow!")
1113 /// assert!(res == Ok(vec![2, 3]));
1116 fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
1117 // FIXME(#11084): This could be replaced with Iterator::scan when this
1118 // performance bug is closed.
1120 struct Adapter<Iter, E> {
1125 impl<T, E, Iter: Iterator<Item=Result<T, E>>> Iterator for Adapter<Iter, E> {
1129 fn next(&mut self) -> Option<T> {
1130 match self.iter.next() {
1131 Some(Ok(value)) => Some(value),
1133 self.err = Some(err);
1140 fn size_hint(&self) -> (usize, Option<usize>) {
1141 let (_min, max) = self.iter.size_hint();
1146 let mut adapter = Adapter { iter: iter.into_iter(), err: None };
1147 let v: V = FromIterator::from_iter(adapter.by_ref());
1150 Some(err) => Err(err),
1156 #[unstable(feature = "try_trait", issue = "42327")]
1157 impl<T,E> ops::Try for Result<T, E> {
1161 fn into_result(self) -> Self {
1165 fn from_ok(v: T) -> Self {
1169 fn from_error(v: E) -> Self {