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};
246 /// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
248 /// See the [`std::result`](index.html) module documentation for details.
249 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
251 #[stable(feature = "rust1", since = "1.0.0")]
252 pub enum Result<T, E> {
253 /// Contains the success value
254 #[stable(feature = "rust1", since = "1.0.0")]
255 Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
257 /// Contains the error value
258 #[stable(feature = "rust1", since = "1.0.0")]
259 Err(#[stable(feature = "rust1", since = "1.0.0")] E),
262 /////////////////////////////////////////////////////////////////////////////
263 // Type implementation
264 /////////////////////////////////////////////////////////////////////////////
266 impl<T, E> Result<T, E> {
267 /////////////////////////////////////////////////////////////////////////
268 // Querying the contained values
269 /////////////////////////////////////////////////////////////////////////
271 /// Returns true if the result is `Ok`.
278 /// let x: Result<i32, &str> = Ok(-3);
279 /// assert_eq!(x.is_ok(), true);
281 /// let x: Result<i32, &str> = Err("Some error message");
282 /// assert_eq!(x.is_ok(), false);
285 #[stable(feature = "rust1", since = "1.0.0")]
286 pub fn is_ok(&self) -> bool {
293 /// Returns true if the result is `Err`.
300 /// let x: Result<i32, &str> = Ok(-3);
301 /// assert_eq!(x.is_err(), false);
303 /// let x: Result<i32, &str> = Err("Some error message");
304 /// 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 `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.
441 /// Print the numbers on each line of a string multiplied by two.
444 /// let line = "1\n2\n3\n4\n";
446 /// for num in line.lines() {
447 /// match num.parse::<i32>().map(|i| i * 2) {
448 /// Ok(n) => println!("{}", n),
454 #[stable(feature = "rust1", since = "1.0.0")]
455 pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
462 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
463 /// contained `Err` value, leaving an `Ok` value untouched.
465 /// This function can be used to pass through a successful result while handling
473 /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
475 /// let x: Result<u32, u32> = Ok(2);
476 /// assert_eq!(x.map_err(stringify), Ok(2));
478 /// let x: Result<u32, u32> = Err(13);
479 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
482 #[stable(feature = "rust1", since = "1.0.0")]
483 pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> {
490 /////////////////////////////////////////////////////////////////////////
491 // Iterator constructors
492 /////////////////////////////////////////////////////////////////////////
494 /// Returns an iterator over the possibly contained value.
496 /// The iterator yields one value if the result is [`Ok`], otherwise none.
503 /// let x: Result<u32, &str> = Ok(7);
504 /// assert_eq!(x.iter().next(), Some(&7));
506 /// let x: Result<u32, &str> = Err("nothing!");
507 /// assert_eq!(x.iter().next(), None);
510 /// [`Ok`]: enum.Result.html#variant.Ok
512 #[stable(feature = "rust1", since = "1.0.0")]
513 pub fn iter(&self) -> Iter<T> {
514 Iter { inner: self.as_ref().ok() }
517 /// Returns a mutable iterator over the possibly contained value.
519 /// The iterator yields one value if the result is [`Ok`], otherwise none.
526 /// let mut x: Result<u32, &str> = Ok(7);
527 /// match x.iter_mut().next() {
528 /// Some(v) => *v = 40,
531 /// assert_eq!(x, Ok(40));
533 /// let mut x: Result<u32, &str> = Err("nothing!");
534 /// assert_eq!(x.iter_mut().next(), None);
537 /// [`Ok`]: enum.Result.html#variant.Ok
539 #[stable(feature = "rust1", since = "1.0.0")]
540 pub fn iter_mut(&mut self) -> IterMut<T> {
541 IterMut { inner: self.as_mut().ok() }
544 ////////////////////////////////////////////////////////////////////////
545 // Boolean operations on the values, eager and lazy
546 /////////////////////////////////////////////////////////////////////////
548 /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
555 /// let x: Result<u32, &str> = Ok(2);
556 /// let y: Result<&str, &str> = Err("late error");
557 /// assert_eq!(x.and(y), Err("late error"));
559 /// let x: Result<u32, &str> = Err("early error");
560 /// let y: Result<&str, &str> = Ok("foo");
561 /// assert_eq!(x.and(y), Err("early error"));
563 /// let x: Result<u32, &str> = Err("not a 2");
564 /// let y: Result<&str, &str> = Err("late error");
565 /// assert_eq!(x.and(y), Err("not a 2"));
567 /// let x: Result<u32, &str> = Ok(2);
568 /// let y: Result<&str, &str> = Ok("different result type");
569 /// assert_eq!(x.and(y), Ok("different result type"));
572 #[stable(feature = "rust1", since = "1.0.0")]
573 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
580 /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
582 /// This function can be used for control flow based on `Result` values.
589 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
590 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
592 /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
593 /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
594 /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
595 /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
598 #[stable(feature = "rust1", since = "1.0.0")]
599 pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
606 /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
613 /// let x: Result<u32, &str> = Ok(2);
614 /// let y: Result<u32, &str> = Err("late error");
615 /// assert_eq!(x.or(y), Ok(2));
617 /// let x: Result<u32, &str> = Err("early error");
618 /// let y: Result<u32, &str> = Ok(2);
619 /// assert_eq!(x.or(y), Ok(2));
621 /// let x: Result<u32, &str> = Err("not a 2");
622 /// let y: Result<u32, &str> = Err("late error");
623 /// assert_eq!(x.or(y), Err("late error"));
625 /// let x: Result<u32, &str> = Ok(2);
626 /// let y: Result<u32, &str> = Ok(100);
627 /// assert_eq!(x.or(y), Ok(2));
630 #[stable(feature = "rust1", since = "1.0.0")]
631 pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
638 /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
640 /// This function can be used for control flow based on result values.
647 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
648 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
650 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
651 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
652 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
653 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
656 #[stable(feature = "rust1", since = "1.0.0")]
657 pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
664 /// Unwraps a result, yielding the content of an `Ok`.
665 /// Else, it returns `optb`.
673 /// let x: Result<u32, &str> = Ok(9);
674 /// assert_eq!(x.unwrap_or(optb), 9);
676 /// let x: Result<u32, &str> = Err("error");
677 /// assert_eq!(x.unwrap_or(optb), optb);
680 #[stable(feature = "rust1", since = "1.0.0")]
681 pub fn unwrap_or(self, optb: T) -> T {
688 /// Unwraps a result, yielding the content of an `Ok`.
689 /// If the value is an `Err` then it calls `op` with its value.
696 /// fn count(x: &str) -> usize { x.len() }
698 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
699 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
702 #[stable(feature = "rust1", since = "1.0.0")]
703 pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
711 impl<T, E: fmt::Debug> Result<T, E> {
712 /// Unwraps a result, yielding the content of an `Ok`.
716 /// Panics if the value is an `Err`, with a panic message provided by the
724 /// let x: Result<u32, &str> = Ok(2);
725 /// assert_eq!(x.unwrap(), 2);
728 /// ```{.should_panic}
729 /// let x: Result<u32, &str> = Err("emergency failure");
730 /// x.unwrap(); // panics with `emergency failure`
733 #[stable(feature = "rust1", since = "1.0.0")]
734 pub fn unwrap(self) -> T {
737 Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", e),
741 /// Unwraps a result, yielding the content of an `Ok`.
745 /// Panics if the value is an `Err`, with a panic message including the
746 /// passed message, and the content of the `Err`.
752 /// ```{.should_panic}
753 /// let x: Result<u32, &str> = Err("emergency failure");
754 /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
757 #[stable(feature = "result_expect", since = "1.4.0")]
758 pub fn expect(self, msg: &str) -> T {
761 Err(e) => unwrap_failed(msg, e),
766 impl<T: fmt::Debug, E> Result<T, E> {
767 /// Unwraps a result, yielding the content of an `Err`.
771 /// Panics if the value is an `Ok`, with a custom panic message provided
772 /// by the `Ok`'s value.
776 /// ```{.should_panic}
777 /// let x: Result<u32, &str> = Ok(2);
778 /// x.unwrap_err(); // panics with `2`
782 /// let x: Result<u32, &str> = Err("emergency failure");
783 /// assert_eq!(x.unwrap_err(), "emergency failure");
786 #[stable(feature = "rust1", since = "1.0.0")]
787 pub fn unwrap_err(self) -> E {
789 Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", t),
794 /// Unwraps a result, yielding the content of an `Err`.
798 /// Panics if the value is an `Ok`, with a panic message including the
799 /// passed message, and the content of the `Ok`.
805 /// ```{.should_panic}
806 /// let x: Result<u32, &str> = Ok(10);
807 /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
810 #[stable(feature = "result_expect_err", since = "1.17.0")]
811 pub fn expect_err(self, msg: &str) -> E {
813 Ok(t) => unwrap_failed(msg, t),
819 impl<T: Default, E> Result<T, E> {
820 /// Returns the contained value or a default
822 /// Consumes the `self` argument then, if `Ok`, returns the contained
823 /// value, otherwise if `Err`, returns the default value for that
828 /// Convert a string to an integer, turning poorly-formed strings
829 /// into 0 (the default value for integers). [`parse`] converts
830 /// a string to any other type that implements [`FromStr`], returning an
834 /// let good_year_from_input = "1909";
835 /// let bad_year_from_input = "190blarg";
836 /// let good_year = good_year_from_input.parse().unwrap_or_default();
837 /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
839 /// assert_eq!(1909, good_year);
840 /// assert_eq!(0, bad_year);
842 /// [`parse`]: ../../std/primitive.str.html#method.parse
843 /// [`FromStr`]: ../../std/str/trait.FromStr.html
846 #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
847 pub fn unwrap_or_default(self) -> T {
850 Err(_) => Default::default(),
855 // This is a separate function to reduce the code size of the methods
858 fn unwrap_failed<E: fmt::Debug>(msg: &str, error: E) -> ! {
859 panic!("{}: {:?}", msg, error)
862 /////////////////////////////////////////////////////////////////////////////
863 // Trait implementations
864 /////////////////////////////////////////////////////////////////////////////
866 #[stable(feature = "rust1", since = "1.0.0")]
867 impl<T, E> IntoIterator for Result<T, E> {
869 type IntoIter = IntoIter<T>;
871 /// Returns a consuming iterator over the possibly contained value.
873 /// The iterator yields one value if the result is [`Ok`], otherwise none.
880 /// let x: Result<u32, &str> = Ok(5);
881 /// let v: Vec<u32> = x.into_iter().collect();
882 /// assert_eq!(v, [5]);
884 /// let x: Result<u32, &str> = Err("nothing!");
885 /// let v: Vec<u32> = x.into_iter().collect();
886 /// assert_eq!(v, []);
889 /// [`Ok`]: enum.Result.html#variant.Ok
891 fn into_iter(self) -> IntoIter<T> {
892 IntoIter { inner: self.ok() }
896 #[stable(since = "1.4.0", feature = "result_iter")]
897 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
899 type IntoIter = Iter<'a, T>;
901 fn into_iter(self) -> Iter<'a, T> {
906 #[stable(since = "1.4.0", feature = "result_iter")]
907 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
908 type Item = &'a mut T;
909 type IntoIter = IterMut<'a, T>;
911 fn into_iter(mut self) -> IterMut<'a, T> {
916 /////////////////////////////////////////////////////////////////////////////
917 // The Result Iterators
918 /////////////////////////////////////////////////////////////////////////////
920 /// An iterator over a reference to the [`Ok`] variant of a [`Result`].
922 /// The iterator yields one value if the result is [`Ok`], otherwise none.
924 /// Created by [`Result::iter`].
926 /// [`Ok`]: enum.Result.html#variant.Ok
927 /// [`Result`]: enum.Result.html
928 /// [`Result::iter`]: enum.Result.html#method.iter
930 #[stable(feature = "rust1", since = "1.0.0")]
931 pub struct Iter<'a, T: 'a> { inner: Option<&'a T> }
933 #[stable(feature = "rust1", since = "1.0.0")]
934 impl<'a, T> Iterator for Iter<'a, T> {
938 fn next(&mut self) -> Option<&'a T> { self.inner.take() }
940 fn size_hint(&self) -> (usize, Option<usize>) {
941 let n = if self.inner.is_some() {1} else {0};
946 #[stable(feature = "rust1", since = "1.0.0")]
947 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
949 fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
952 #[stable(feature = "rust1", since = "1.0.0")]
953 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
955 #[unstable(feature = "fused", issue = "35602")]
956 impl<'a, T> FusedIterator for Iter<'a, T> {}
958 #[unstable(feature = "trusted_len", issue = "37572")]
959 unsafe impl<'a, A> TrustedLen for Iter<'a, A> {}
961 #[stable(feature = "rust1", since = "1.0.0")]
962 impl<'a, T> Clone for Iter<'a, T> {
963 fn clone(&self) -> Iter<'a, T> { Iter { inner: self.inner } }
966 /// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
968 /// Created by [`Result::iter_mut`].
970 /// [`Ok`]: enum.Result.html#variant.Ok
971 /// [`Result`]: enum.Result.html
972 /// [`Result::iter_mut`]: enum.Result.html#method.iter_mut
974 #[stable(feature = "rust1", since = "1.0.0")]
975 pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
977 #[stable(feature = "rust1", since = "1.0.0")]
978 impl<'a, T> Iterator for IterMut<'a, T> {
979 type Item = &'a mut T;
982 fn next(&mut self) -> Option<&'a mut T> { self.inner.take() }
984 fn size_hint(&self) -> (usize, Option<usize>) {
985 let n = if self.inner.is_some() {1} else {0};
990 #[stable(feature = "rust1", since = "1.0.0")]
991 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
993 fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
996 #[stable(feature = "rust1", since = "1.0.0")]
997 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
999 #[unstable(feature = "fused", issue = "35602")]
1000 impl<'a, T> FusedIterator for IterMut<'a, T> {}
1002 #[unstable(feature = "trusted_len", issue = "37572")]
1003 unsafe impl<'a, A> TrustedLen for IterMut<'a, A> {}
1005 /// An iterator over the value in a [`Ok`] variant of a [`Result`].
1007 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1009 /// This struct is created by the [`into_iter`] method on
1010 /// [`Result`][`Result`] (provided by the [`IntoIterator`] trait).
1012 /// [`Ok`]: enum.Result.html#variant.Ok
1013 /// [`Result`]: enum.Result.html
1014 /// [`into_iter`]: ../iter/trait.IntoIterator.html#tymethod.into_iter
1015 /// [`IntoIterator`]: ../iter/trait.IntoIterator.html
1017 #[stable(feature = "rust1", since = "1.0.0")]
1018 pub struct IntoIter<T> { inner: Option<T> }
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 impl<T> Iterator for IntoIter<T> {
1025 fn next(&mut self) -> Option<T> { self.inner.take() }
1027 fn size_hint(&self) -> (usize, Option<usize>) {
1028 let n = if self.inner.is_some() {1} else {0};
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 impl<T> DoubleEndedIterator for IntoIter<T> {
1036 fn next_back(&mut self) -> Option<T> { self.inner.take() }
1039 #[stable(feature = "rust1", since = "1.0.0")]
1040 impl<T> ExactSizeIterator for IntoIter<T> {}
1042 #[unstable(feature = "fused", issue = "35602")]
1043 impl<T> FusedIterator for IntoIter<T> {}
1045 #[unstable(feature = "trusted_len", issue = "37572")]
1046 unsafe impl<A> TrustedLen for IntoIter<A> {}
1048 /////////////////////////////////////////////////////////////////////////////
1050 /////////////////////////////////////////////////////////////////////////////
1052 #[stable(feature = "rust1", since = "1.0.0")]
1053 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
1054 /// Takes each element in the `Iterator`: if it is an `Err`, no further
1055 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
1056 /// container with the values of each `Result` is returned.
1058 /// Here is an example which increments every integer in a vector,
1059 /// checking for overflow:
1064 /// let v = vec![1, 2];
1065 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|&x: &u32|
1066 /// if x == u32::MAX { Err("Overflow!") }
1067 /// else { Ok(x + 1) }
1069 /// assert!(res == Ok(vec![2, 3]));
1072 fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
1073 // FIXME(#11084): This could be replaced with Iterator::scan when this
1074 // performance bug is closed.
1076 struct Adapter<Iter, E> {
1081 impl<T, E, Iter: Iterator<Item=Result<T, E>>> Iterator for Adapter<Iter, E> {
1085 fn next(&mut self) -> Option<T> {
1086 match self.iter.next() {
1087 Some(Ok(value)) => Some(value),
1089 self.err = Some(err);
1096 fn size_hint(&self) -> (usize, Option<usize>) {
1097 let (_min, max) = self.iter.size_hint();
1102 let mut adapter = Adapter { iter: iter.into_iter(), err: None };
1103 let v: V = FromIterator::from_iter(adapter.by_ref());
1106 Some(err) => Err(err),