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>` 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`](../../std/io/trait.Write.html) 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 `try!`:
145 //! # use std::fs::File;
146 //! # use std::io::prelude::*;
148 //! # #[allow(dead_code)]
149 //! fn write_message() -> io::Result<()> {
150 //! let mut file = try!(File::create("valuable_data.txt"));
151 //! try!(file.write_all(b"important message"));
156 //! # The `try!` macro
158 //! When writing code that calls many functions that return the
159 //! `Result` type, the error handling can be tedious. The `try!`
160 //! macro 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 = try!(File::create("my_best_friends.txt"));
212 //! // Early return on error
213 //! try!(file.write_all(format!("name: {}\n", info.name).as_bytes()));
214 //! try!(file.write_all(format!("age: {}\n", info.age).as_bytes()));
215 //! try!(file.write_all(format!("rating: {}\n", info.rating).as_bytes()));
220 //! *It's much nicer!*
222 //! Wrapping an expression in `try!` 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. Its simple definition
228 //! macro_rules! try {
229 //! ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
233 //! `try!` is imported by the prelude and is available everywhere, but it can only
234 //! be used in functions that return `Result` because of the early return of
235 //! `Err` that it provides.
237 #![stable(feature = "rust1", since = "1.0.0")]
239 use self::Result::{Ok, Err};
243 use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSizeIterator, IntoIterator};
245 use option::Option::{self, None, Some};
247 /// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
249 /// See the [`std::result`](index.html) module documentation for details.
250 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
252 #[stable(feature = "rust1", since = "1.0.0")]
253 pub enum Result<T, E> {
254 /// Contains the success value
255 #[stable(feature = "rust1", since = "1.0.0")]
256 Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
258 /// Contains the error value
259 #[stable(feature = "rust1", since = "1.0.0")]
260 Err(#[stable(feature = "rust1", since = "1.0.0")] E),
263 /////////////////////////////////////////////////////////////////////////////
264 // Type implementation
265 /////////////////////////////////////////////////////////////////////////////
267 impl<T, E> Result<T, E> {
268 /////////////////////////////////////////////////////////////////////////
269 // Querying the contained values
270 /////////////////////////////////////////////////////////////////////////
272 /// Returns true if the result is `Ok`
279 /// let x: Result<i32, &str> = Ok(-3);
280 /// assert_eq!(x.is_ok(), true);
282 /// let x: Result<i32, &str> = Err("Some error message");
283 /// assert_eq!(x.is_ok(), false);
286 #[stable(feature = "rust1", since = "1.0.0")]
287 pub fn is_ok(&self) -> bool {
294 /// Returns true if the result is `Err`
301 /// let x: Result<i32, &str> = Ok(-3);
302 /// assert_eq!(x.is_err(), false);
304 /// let x: Result<i32, &str> = Err("Some error message");
305 /// assert_eq!(x.is_err(), true);
308 #[stable(feature = "rust1", since = "1.0.0")]
309 pub fn is_err(&self) -> bool {
313 /////////////////////////////////////////////////////////////////////////
314 // Adapter for each variant
315 /////////////////////////////////////////////////////////////////////////
317 /// Converts from `Result<T, E>` to `Option<T>`
319 /// Converts `self` into an `Option<T>`, consuming `self`,
320 /// and discarding the error, if any.
327 /// let x: Result<u32, &str> = Ok(2);
328 /// assert_eq!(x.ok(), Some(2));
330 /// let x: Result<u32, &str> = Err("Nothing here");
331 /// assert_eq!(x.ok(), None);
334 #[stable(feature = "rust1", since = "1.0.0")]
335 pub fn ok(self) -> Option<T> {
342 /// Converts from `Result<T, E>` to `Option<E>`
344 /// Converts `self` into an `Option<E>`, consuming `self`,
345 /// and discarding the success value, if any.
352 /// let x: Result<u32, &str> = Ok(2);
353 /// assert_eq!(x.err(), None);
355 /// let x: Result<u32, &str> = Err("Nothing here");
356 /// assert_eq!(x.err(), Some("Nothing here"));
359 #[stable(feature = "rust1", since = "1.0.0")]
360 pub fn err(self) -> Option<E> {
367 /////////////////////////////////////////////////////////////////////////
368 // Adapter for working with references
369 /////////////////////////////////////////////////////////////////////////
371 /// Converts from `Result<T, E>` to `Result<&T, &E>`
373 /// Produces a new `Result`, containing a reference
374 /// into the original, leaving the original in place.
381 /// let x: Result<u32, &str> = Ok(2);
382 /// assert_eq!(x.as_ref(), Ok(&2));
384 /// let x: Result<u32, &str> = Err("Error");
385 /// assert_eq!(x.as_ref(), Err(&"Error"));
388 #[stable(feature = "rust1", since = "1.0.0")]
389 pub fn as_ref(&self) -> Result<&T, &E> {
392 Err(ref x) => Err(x),
396 /// Converts from `Result<T, E>` to `Result<&mut T, &mut E>`
403 /// fn mutate(r: &mut Result<i32, i32>) {
404 /// match r.as_mut() {
405 /// Ok(v) => *v = 42,
406 /// Err(e) => *e = 0,
410 /// let mut x: Result<i32, i32> = Ok(2);
412 /// assert_eq!(x.unwrap(), 42);
414 /// let mut x: Result<i32, i32> = Err(13);
416 /// assert_eq!(x.unwrap_err(), 0);
419 #[stable(feature = "rust1", since = "1.0.0")]
420 pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
422 Ok(ref mut x) => Ok(x),
423 Err(ref mut x) => Err(x),
427 /////////////////////////////////////////////////////////////////////////
428 // Transforming contained values
429 /////////////////////////////////////////////////////////////////////////
431 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
432 /// contained `Ok` value, leaving an `Err` value untouched.
434 /// This function can be used to compose the results of two functions.
438 /// Print the numbers on each line of a string multiplied by two.
441 /// let line = "1\n2\n3\n4\n";
443 /// for num in line.lines() {
444 /// match num.parse::<i32>().map(|i| i * 2) {
445 /// Ok(n) => println!("{}", n),
451 #[stable(feature = "rust1", since = "1.0.0")]
452 pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
459 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
460 /// contained `Err` value, leaving an `Ok` value untouched.
462 /// This function can be used to pass through a successful result while handling
470 /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
472 /// let x: Result<u32, u32> = Ok(2);
473 /// assert_eq!(x.map_err(stringify), Ok(2));
475 /// let x: Result<u32, u32> = Err(13);
476 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
479 #[stable(feature = "rust1", since = "1.0.0")]
480 pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> {
487 /////////////////////////////////////////////////////////////////////////
488 // Iterator constructors
489 /////////////////////////////////////////////////////////////////////////
491 /// Returns an iterator over the possibly contained value.
498 /// let x: Result<u32, &str> = Ok(7);
499 /// assert_eq!(x.iter().next(), Some(&7));
501 /// let x: Result<u32, &str> = Err("nothing!");
502 /// assert_eq!(x.iter().next(), None);
505 #[stable(feature = "rust1", since = "1.0.0")]
506 pub fn iter(&self) -> Iter<T> {
507 Iter { inner: self.as_ref().ok() }
510 /// Returns a mutable iterator over the possibly contained value.
517 /// let mut x: Result<u32, &str> = Ok(7);
518 /// match x.iter_mut().next() {
519 /// Some(v) => *v = 40,
522 /// assert_eq!(x, Ok(40));
524 /// let mut x: Result<u32, &str> = Err("nothing!");
525 /// assert_eq!(x.iter_mut().next(), None);
528 #[stable(feature = "rust1", since = "1.0.0")]
529 pub fn iter_mut(&mut self) -> IterMut<T> {
530 IterMut { inner: self.as_mut().ok() }
533 ////////////////////////////////////////////////////////////////////////
534 // Boolean operations on the values, eager and lazy
535 /////////////////////////////////////////////////////////////////////////
537 /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
544 /// let x: Result<u32, &str> = Ok(2);
545 /// let y: Result<&str, &str> = Err("late error");
546 /// assert_eq!(x.and(y), Err("late error"));
548 /// let x: Result<u32, &str> = Err("early error");
549 /// let y: Result<&str, &str> = Ok("foo");
550 /// assert_eq!(x.and(y), Err("early error"));
552 /// let x: Result<u32, &str> = Err("not a 2");
553 /// let y: Result<&str, &str> = Err("late error");
554 /// assert_eq!(x.and(y), Err("not a 2"));
556 /// let x: Result<u32, &str> = Ok(2);
557 /// let y: Result<&str, &str> = Ok("different result type");
558 /// assert_eq!(x.and(y), Ok("different result type"));
561 #[stable(feature = "rust1", since = "1.0.0")]
562 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
569 /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
571 /// This function can be used for control flow based on result values.
578 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
579 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
581 /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
582 /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
583 /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
584 /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
587 #[stable(feature = "rust1", since = "1.0.0")]
588 pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
595 /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
602 /// let x: Result<u32, &str> = Ok(2);
603 /// let y: Result<u32, &str> = Err("late error");
604 /// assert_eq!(x.or(y), Ok(2));
606 /// let x: Result<u32, &str> = Err("early error");
607 /// let y: Result<u32, &str> = Ok(2);
608 /// assert_eq!(x.or(y), Ok(2));
610 /// let x: Result<u32, &str> = Err("not a 2");
611 /// let y: Result<u32, &str> = Err("late error");
612 /// assert_eq!(x.or(y), Err("late error"));
614 /// let x: Result<u32, &str> = Ok(2);
615 /// let y: Result<u32, &str> = Ok(100);
616 /// assert_eq!(x.or(y), Ok(2));
619 #[stable(feature = "rust1", since = "1.0.0")]
620 pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
627 /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
629 /// This function can be used for control flow based on result values.
636 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
637 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
639 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
640 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
641 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
642 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
645 #[stable(feature = "rust1", since = "1.0.0")]
646 pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
653 /// Unwraps a result, yielding the content of an `Ok`.
654 /// Else it returns `optb`.
662 /// let x: Result<u32, &str> = Ok(9);
663 /// assert_eq!(x.unwrap_or(optb), 9);
665 /// let x: Result<u32, &str> = Err("error");
666 /// assert_eq!(x.unwrap_or(optb), optb);
669 #[stable(feature = "rust1", since = "1.0.0")]
670 pub fn unwrap_or(self, optb: T) -> T {
677 /// Unwraps a result, yielding the content of an `Ok`.
678 /// If the value is an `Err` then it calls `op` with its value.
685 /// fn count(x: &str) -> usize { x.len() }
687 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
688 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
691 #[stable(feature = "rust1", since = "1.0.0")]
692 pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
700 impl<T, E: fmt::Debug> Result<T, E> {
701 /// Unwraps a result, yielding the content of an `Ok`.
705 /// Panics if the value is an `Err`, with a panic message provided by the
713 /// let x: Result<u32, &str> = Ok(2);
714 /// assert_eq!(x.unwrap(), 2);
717 /// ```{.should_panic}
718 /// let x: Result<u32, &str> = Err("emergency failure");
719 /// x.unwrap(); // panics with `emergency failure`
722 #[stable(feature = "rust1", since = "1.0.0")]
723 pub fn unwrap(self) -> T {
726 Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", e),
730 /// Unwraps a result, yielding the content of an `Ok`.
734 /// Panics if the value is an `Err`, with a panic message including the
735 /// passed message, and the content of the `Err`.
741 /// ```{.should_panic}
742 /// let x: Result<u32, &str> = Err("emergency failure");
743 /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
746 #[stable(feature = "result_expect", since = "1.4.0")]
747 pub fn expect(self, msg: &str) -> T {
750 Err(e) => unwrap_failed(msg, e),
755 impl<T: fmt::Debug, E> Result<T, E> {
756 /// Unwraps a result, yielding the content of an `Err`.
760 /// Panics if the value is an `Ok`, with a custom panic message provided
761 /// by the `Ok`'s value.
765 /// ```{.should_panic}
766 /// let x: Result<u32, &str> = Ok(2);
767 /// x.unwrap_err(); // panics with `2`
771 /// let x: Result<u32, &str> = Err("emergency failure");
772 /// assert_eq!(x.unwrap_err(), "emergency failure");
775 #[stable(feature = "rust1", since = "1.0.0")]
776 pub fn unwrap_err(self) -> E {
778 Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", t),
784 // This is a separate function to reduce the code size of the methods
787 fn unwrap_failed<E: fmt::Debug>(msg: &str, error: E) -> ! {
788 panic!("{}: {:?}", msg, error)
791 /////////////////////////////////////////////////////////////////////////////
792 // Trait implementations
793 /////////////////////////////////////////////////////////////////////////////
795 #[stable(feature = "rust1", since = "1.0.0")]
796 impl<T, E> IntoIterator for Result<T, E> {
798 type IntoIter = IntoIter<T>;
800 /// Returns a consuming iterator over the possibly contained value.
807 /// let x: Result<u32, &str> = Ok(5);
808 /// let v: Vec<u32> = x.into_iter().collect();
809 /// assert_eq!(v, [5]);
811 /// let x: Result<u32, &str> = Err("nothing!");
812 /// let v: Vec<u32> = x.into_iter().collect();
813 /// assert_eq!(v, []);
816 fn into_iter(self) -> IntoIter<T> {
817 IntoIter { inner: self.ok() }
821 #[stable(since = "1.4.0", feature = "result_iter")]
822 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
824 type IntoIter = Iter<'a, T>;
826 fn into_iter(self) -> Iter<'a, T> {
831 #[stable(since = "1.4.0", feature = "result_iter")]
832 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
833 type Item = &'a mut T;
834 type IntoIter = IterMut<'a, T>;
836 fn into_iter(mut self) -> IterMut<'a, T> {
841 /////////////////////////////////////////////////////////////////////////////
842 // The Result Iterators
843 /////////////////////////////////////////////////////////////////////////////
845 /// An iterator over a reference to the `Ok` variant of a `Result`.
847 #[stable(feature = "rust1", since = "1.0.0")]
848 pub struct Iter<'a, T: 'a> { inner: Option<&'a T> }
850 #[stable(feature = "rust1", since = "1.0.0")]
851 impl<'a, T> Iterator for Iter<'a, T> {
855 fn next(&mut self) -> Option<&'a T> { self.inner.take() }
857 fn size_hint(&self) -> (usize, Option<usize>) {
858 let n = if self.inner.is_some() {1} else {0};
863 #[stable(feature = "rust1", since = "1.0.0")]
864 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
866 fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
869 #[stable(feature = "rust1", since = "1.0.0")]
870 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
872 #[stable(feature = "rust1", since = "1.0.0")]
873 impl<'a, T> Clone for Iter<'a, T> {
874 fn clone(&self) -> Iter<'a, T> { Iter { inner: self.inner } }
877 /// An iterator over a mutable reference to the `Ok` variant of a `Result`.
879 #[stable(feature = "rust1", since = "1.0.0")]
880 pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
882 #[stable(feature = "rust1", since = "1.0.0")]
883 impl<'a, T> Iterator for IterMut<'a, T> {
884 type Item = &'a mut T;
887 fn next(&mut self) -> Option<&'a mut T> { self.inner.take() }
889 fn size_hint(&self) -> (usize, Option<usize>) {
890 let n = if self.inner.is_some() {1} else {0};
895 #[stable(feature = "rust1", since = "1.0.0")]
896 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
898 fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
901 #[stable(feature = "rust1", since = "1.0.0")]
902 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
904 /// An iterator over the value in a `Ok` variant of a `Result`.
906 #[stable(feature = "rust1", since = "1.0.0")]
907 pub struct IntoIter<T> { inner: Option<T> }
909 #[stable(feature = "rust1", since = "1.0.0")]
910 impl<T> Iterator for IntoIter<T> {
914 fn next(&mut self) -> Option<T> { self.inner.take() }
916 fn size_hint(&self) -> (usize, Option<usize>) {
917 let n = if self.inner.is_some() {1} else {0};
922 #[stable(feature = "rust1", since = "1.0.0")]
923 impl<T> DoubleEndedIterator for IntoIter<T> {
925 fn next_back(&mut self) -> Option<T> { self.inner.take() }
928 #[stable(feature = "rust1", since = "1.0.0")]
929 impl<T> ExactSizeIterator for IntoIter<T> {}
931 /////////////////////////////////////////////////////////////////////////////
933 /////////////////////////////////////////////////////////////////////////////
935 #[stable(feature = "rust1", since = "1.0.0")]
936 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
937 /// Takes each element in the `Iterator`: if it is an `Err`, no further
938 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
939 /// container with the values of each `Result` is returned.
941 /// Here is an example which increments every integer in a vector,
942 /// checking for overflow:
947 /// let v = vec!(1, 2);
948 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|&x: &u32|
949 /// if x == u32::MAX { Err("Overflow!") }
950 /// else { Ok(x + 1) }
952 /// assert!(res == Ok(vec!(2, 3)));
955 fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
956 // FIXME(#11084): This could be replaced with Iterator::scan when this
957 // performance bug is closed.
959 struct Adapter<Iter, E> {
964 impl<T, E, Iter: Iterator<Item=Result<T, E>>> Iterator for Adapter<Iter, E> {
968 fn next(&mut self) -> Option<T> {
969 match self.iter.next() {
970 Some(Ok(value)) => Some(value),
972 self.err = Some(err);
980 let mut adapter = Adapter { iter: iter.into_iter(), err: None };
981 let v: V = FromIterator::from_iter(adapter.by_ref());
984 Some(err) => Err(err),