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 //! enum Result<T, E> {
25 //! Functions return `Result` whenever errors are expected and
26 //! recoverable. In the `std` crate `Result` is most prominently used
27 //! for [I/O](../../std/io/index.html).
29 //! A simple function returning `Result` might be
30 //! defined and used like so:
34 //! enum Version { Version1, Version2 }
36 //! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
37 //! if header.len() < 1 {
38 //! return Err("invalid header length");
41 //! 1 => Ok(Version::Version1),
42 //! 2 => Ok(Version::Version2),
43 //! _ => Err("invalid version")
47 //! let version = parse_version(&[1, 2, 3, 4]);
50 //! println!("working with version: {:?}", v);
53 //! println!("error parsing header: {:?}", e);
58 //! Pattern matching on `Result`s is clear and straightforward for
59 //! simple cases, but `Result` comes with some convenience methods
60 //! that make working with it more succinct.
63 //! let good_result: Result<int, int> = Ok(10);
64 //! let bad_result: Result<int, int> = Err(10);
66 //! // The `is_ok` and `is_err` methods do what they say.
67 //! assert!(good_result.is_ok() && !good_result.is_err());
68 //! assert!(bad_result.is_err() && !bad_result.is_ok());
70 //! // `map` consumes the `Result` and produces another.
71 //! let good_result: Result<int, int> = good_result.map(|i| i + 1);
72 //! let bad_result: Result<int, int> = bad_result.map(|i| i - 1);
74 //! // Use `and_then` to continue the computation.
75 //! let good_result: Result<bool, int> = good_result.and_then(|i| Ok(i == 11));
77 //! // Use `or_else` to handle the error.
78 //! let bad_result: Result<int, int> = bad_result.or_else(|i| Ok(11));
80 //! // Consume the result and return the contents with `unwrap`.
81 //! let final_awesome_result = good_result.ok().unwrap();
84 //! # Results must be used
86 //! A common problem with using return values to indicate errors is
87 //! that it is easy to ignore the return value, thus failing to handle
88 //! the error. Result is annotated with the #[must_use] attribute,
89 //! which will cause the compiler to issue a warning when a Result
90 //! value is ignored. This makes `Result` especially useful with
91 //! functions that may encounter errors but don't otherwise return a
94 //! Consider the `write_line` method defined for I/O types
95 //! by the [`Writer`](../io/trait.Writer.html) trait:
98 //! use std::old_io::IoError;
101 //! fn write_line(&mut self, s: &str) -> Result<(), IoError>;
105 //! *Note: The actual definition of `Writer` uses `IoResult`, which
106 //! is just a synonym for `Result<T, IoError>`.*
108 //! This method doesn't produce a value, but the write may
109 //! fail. It's crucial to handle the error case, and *not* write
110 //! something like this:
113 //! use std::old_io::{File, Open, Write};
115 //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
116 //! // If `write_line` errors, then we'll never know, because the return
117 //! // value is ignored.
118 //! file.write_line("important message");
122 //! If you *do* write that in Rust, the compiler will give you a
123 //! warning (by default, controlled by the `unused_must_use` lint).
125 //! You might instead, if you don't want to handle the error, simply
126 //! panic, by converting to an `Option` with `ok`, then asserting
127 //! success with `expect`. This will panic if the write fails, proving
128 //! a marginally useful message indicating why:
131 //! use std::old_io::{File, Open, Write};
133 //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
134 //! file.write_line("important message").ok().expect("failed to write message");
138 //! You might also simply assert success:
141 //! # use std::old_io::{File, Open, Write};
143 //! # let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
144 //! assert!(file.write_line("important message").is_ok());
148 //! Or propagate the error up the call stack with `try!`:
151 //! # use std::old_io::{File, Open, Write, IoError};
152 //! fn write_message() -> Result<(), IoError> {
153 //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
154 //! try!(file.write_line("important message"));
160 //! # The `try!` macro
162 //! When writing code that calls many functions that return the
163 //! `Result` type, the error handling can be tedious. The `try!`
164 //! macro hides some of the boilerplate of propagating errors up the
167 //! It replaces this:
170 //! use std::old_io::{File, Open, Write, IoError};
178 //! fn write_info(info: &Info) -> Result<(), IoError> {
179 //! let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
180 //! // Early return on error
181 //! if let Err(e) = file.write_line(format!("name: {}", info.name).as_slice()) {
184 //! if let Err(e) = file.write_line(format!("age: {}", info.age).as_slice()) {
187 //! return file.write_line(format!("rating: {}", info.rating).as_slice());
194 //! use std::old_io::{File, Open, Write, IoError};
202 //! fn write_info(info: &Info) -> Result<(), IoError> {
203 //! let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
204 //! // Early return on error
205 //! try!(file.write_line(format!("name: {}", info.name).as_slice()));
206 //! try!(file.write_line(format!("age: {}", info.age).as_slice()));
207 //! try!(file.write_line(format!("rating: {}", info.rating).as_slice()));
212 //! *It's much nicer!*
214 //! Wrapping an expression in `try!` will result in the unwrapped
215 //! success (`Ok`) value, unless the result is `Err`, in which case
216 //! `Err` is returned early from the enclosing function. Its simple definition
220 //! macro_rules! try {
221 //! ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
225 //! `try!` is imported by the prelude, and is available everywhere.
227 #![stable(feature = "rust1", since = "1.0.0")]
229 use self::Result::{Ok, Err};
233 use iter::{Iterator, IteratorExt, DoubleEndedIterator, FromIterator, ExactSizeIterator};
234 use ops::{FnMut, FnOnce};
235 use option::Option::{self, None, Some};
239 /// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
241 /// See the [`std::result`](index.html) module documentation for details.
242 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
244 #[stable(feature = "rust1", since = "1.0.0")]
245 pub enum Result<T, E> {
246 /// Contains the success value
247 #[stable(feature = "rust1", since = "1.0.0")]
250 /// Contains the error value
251 #[stable(feature = "rust1", since = "1.0.0")]
255 /////////////////////////////////////////////////////////////////////////////
256 // Type implementation
257 /////////////////////////////////////////////////////////////////////////////
259 #[stable(feature = "rust1", since = "1.0.0")]
260 impl<T, E> Result<T, E> {
261 /////////////////////////////////////////////////////////////////////////
262 // Querying the contained values
263 /////////////////////////////////////////////////////////////////////////
265 /// Returns true if the result is `Ok`
270 /// let x: Result<int, &str> = Ok(-3);
271 /// assert_eq!(x.is_ok(), true);
273 /// let x: Result<int, &str> = Err("Some error message");
274 /// assert_eq!(x.is_ok(), false);
277 #[stable(feature = "rust1", since = "1.0.0")]
278 pub fn is_ok(&self) -> bool {
285 /// Returns true if the result is `Err`
290 /// let x: Result<int, &str> = Ok(-3);
291 /// assert_eq!(x.is_err(), false);
293 /// let x: Result<int, &str> = Err("Some error message");
294 /// assert_eq!(x.is_err(), true);
297 #[stable(feature = "rust1", since = "1.0.0")]
298 pub fn is_err(&self) -> bool {
302 /////////////////////////////////////////////////////////////////////////
303 // Adapter for each variant
304 /////////////////////////////////////////////////////////////////////////
306 /// Convert from `Result<T, E>` to `Option<T>`
308 /// Converts `self` into an `Option<T>`, consuming `self`,
309 /// and discarding the error, if any.
314 /// let x: Result<uint, &str> = Ok(2);
315 /// assert_eq!(x.ok(), Some(2));
317 /// let x: Result<uint, &str> = Err("Nothing here");
318 /// assert_eq!(x.ok(), None);
321 #[stable(feature = "rust1", since = "1.0.0")]
322 pub fn ok(self) -> Option<T> {
329 /// Convert from `Result<T, E>` to `Option<E>`
331 /// Converts `self` into an `Option<E>`, consuming `self`,
332 /// and discarding the value, if any.
337 /// let x: Result<uint, &str> = Ok(2);
338 /// assert_eq!(x.err(), None);
340 /// let x: Result<uint, &str> = Err("Nothing here");
341 /// assert_eq!(x.err(), Some("Nothing here"));
344 #[stable(feature = "rust1", since = "1.0.0")]
345 pub fn err(self) -> Option<E> {
352 /////////////////////////////////////////////////////////////////////////
353 // Adapter for working with references
354 /////////////////////////////////////////////////////////////////////////
356 /// Convert from `Result<T, E>` to `Result<&T, &E>`
358 /// Produces a new `Result`, containing a reference
359 /// into the original, leaving the original in place.
362 /// let x: Result<uint, &str> = Ok(2);
363 /// assert_eq!(x.as_ref(), Ok(&2));
365 /// let x: Result<uint, &str> = Err("Error");
366 /// assert_eq!(x.as_ref(), Err(&"Error"));
369 #[stable(feature = "rust1", since = "1.0.0")]
370 pub fn as_ref(&self) -> Result<&T, &E> {
373 Err(ref x) => Err(x),
377 /// Convert from `Result<T, E>` to `Result<&mut T, &mut E>`
380 /// fn mutate(r: &mut Result<int, int>) {
381 /// match r.as_mut() {
382 /// Ok(&mut ref mut v) => *v = 42,
383 /// Err(&mut ref mut e) => *e = 0,
387 /// let mut x: Result<int, int> = Ok(2);
389 /// assert_eq!(x.unwrap(), 42);
391 /// let mut x: Result<int, int> = Err(13);
393 /// assert_eq!(x.unwrap_err(), 0);
396 #[stable(feature = "rust1", since = "1.0.0")]
397 pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
399 Ok(ref mut x) => Ok(x),
400 Err(ref mut x) => Err(x),
404 /// Convert from `Result<T, E>` to `&mut [T]` (without copying)
407 /// let mut x: Result<&str, uint> = Ok("Gold");
409 /// let v = x.as_mut_slice();
410 /// assert!(v == ["Gold"]);
412 /// assert!(v == ["Silver"]);
414 /// assert_eq!(x, Ok("Silver"));
416 /// let mut x: Result<&str, uint> = Err(45);
417 /// assert!(x.as_mut_slice().is_empty());
420 #[unstable(feature = "core",
421 reason = "waiting for mut conventions")]
422 pub fn as_mut_slice(&mut self) -> &mut [T] {
424 Ok(ref mut x) => slice::mut_ref_slice(x),
426 // work around lack of implicit coercion from fixed-size array to slice
427 let emp: &mut [_] = &mut [];
433 /////////////////////////////////////////////////////////////////////////
434 // Transforming contained values
435 /////////////////////////////////////////////////////////////////////////
437 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to an
438 /// contained `Ok` value, leaving an `Err` value untouched.
440 /// This function can be used to compose the results of two functions.
444 /// Sum the lines of a buffer by mapping strings to numbers,
445 /// ignoring I/O and parse errors:
448 /// use std::old_io::IoResult;
450 /// let mut buffer = &mut b"1\n2\n3\n4\n";
454 /// while !buffer.is_empty() {
455 /// let line: IoResult<String> = buffer.read_line();
456 /// // Convert the string line to a number using `map` and `from_str`
457 /// let val: IoResult<int> = line.map(|line| {
458 /// line.trim_right().parse::<int>().unwrap_or(0)
460 /// // Add the value if there were no errors, otherwise add 0
461 /// sum += val.ok().unwrap_or(0);
464 /// assert!(sum == 10);
467 #[stable(feature = "rust1", since = "1.0.0")]
468 pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
475 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to an
476 /// contained `Err` value, leaving an `Ok` value untouched.
478 /// This function can be used to pass through a successful result while handling
484 /// fn stringify(x: uint) -> String { format!("error code: {}", x) }
486 /// let x: Result<uint, uint> = Ok(2);
487 /// assert_eq!(x.map_err(stringify), Ok(2));
489 /// let x: Result<uint, uint> = Err(13);
490 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
493 #[stable(feature = "rust1", since = "1.0.0")]
494 pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> {
501 /////////////////////////////////////////////////////////////////////////
502 // Iterator constructors
503 /////////////////////////////////////////////////////////////////////////
505 /// Returns an iterator over the possibly contained value.
510 /// let x: Result<uint, &str> = Ok(7);
511 /// assert_eq!(x.iter().next(), Some(&7));
513 /// let x: Result<uint, &str> = Err("nothing!");
514 /// assert_eq!(x.iter().next(), None);
517 #[stable(feature = "rust1", since = "1.0.0")]
518 pub fn iter(&self) -> Iter<T> {
519 Iter { inner: self.as_ref().ok() }
522 /// Returns a mutable iterator over the possibly contained value.
527 /// let mut x: Result<uint, &str> = Ok(7);
528 /// match x.iter_mut().next() {
529 /// Some(&mut ref mut x) => *x = 40,
532 /// assert_eq!(x, Ok(40));
534 /// let mut x: Result<uint, &str> = Err("nothing!");
535 /// assert_eq!(x.iter_mut().next(), None);
538 #[stable(feature = "rust1", since = "1.0.0")]
539 pub fn iter_mut(&mut self) -> IterMut<T> {
540 IterMut { inner: self.as_mut().ok() }
543 /// Returns a consuming iterator over the possibly contained value.
548 /// let x: Result<uint, &str> = Ok(5);
549 /// let v: Vec<uint> = x.into_iter().collect();
550 /// assert_eq!(v, vec![5]);
552 /// let x: Result<uint, &str> = Err("nothing!");
553 /// let v: Vec<uint> = x.into_iter().collect();
554 /// assert_eq!(v, vec![]);
557 #[stable(feature = "rust1", since = "1.0.0")]
558 pub fn into_iter(self) -> IntoIter<T> {
559 IntoIter { inner: self.ok() }
562 ////////////////////////////////////////////////////////////////////////
563 // Boolean operations on the values, eager and lazy
564 /////////////////////////////////////////////////////////////////////////
566 /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
571 /// let x: Result<uint, &str> = Ok(2);
572 /// let y: Result<&str, &str> = Err("late error");
573 /// assert_eq!(x.and(y), Err("late error"));
575 /// let x: Result<uint, &str> = Err("early error");
576 /// let y: Result<&str, &str> = Ok("foo");
577 /// assert_eq!(x.and(y), Err("early error"));
579 /// let x: Result<uint, &str> = Err("not a 2");
580 /// let y: Result<&str, &str> = Err("late error");
581 /// assert_eq!(x.and(y), Err("not a 2"));
583 /// let x: Result<uint, &str> = Ok(2);
584 /// let y: Result<&str, &str> = Ok("different result type");
585 /// assert_eq!(x.and(y), Ok("different result type"));
588 #[stable(feature = "rust1", since = "1.0.0")]
589 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
596 /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
598 /// This function can be used for control flow based on result values.
603 /// fn sq(x: uint) -> Result<uint, uint> { Ok(x * x) }
604 /// fn err(x: uint) -> Result<uint, uint> { Err(x) }
606 /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
607 /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
608 /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
609 /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
612 #[stable(feature = "rust1", since = "1.0.0")]
613 pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
620 /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
625 /// let x: Result<uint, &str> = Ok(2);
626 /// let y: Result<uint, &str> = Err("late error");
627 /// assert_eq!(x.or(y), Ok(2));
629 /// let x: Result<uint, &str> = Err("early error");
630 /// let y: Result<uint, &str> = Ok(2);
631 /// assert_eq!(x.or(y), Ok(2));
633 /// let x: Result<uint, &str> = Err("not a 2");
634 /// let y: Result<uint, &str> = Err("late error");
635 /// assert_eq!(x.or(y), Err("late error"));
637 /// let x: Result<uint, &str> = Ok(2);
638 /// let y: Result<uint, &str> = Ok(100);
639 /// assert_eq!(x.or(y), Ok(2));
642 #[stable(feature = "rust1", since = "1.0.0")]
643 pub fn or(self, res: Result<T, E>) -> Result<T, E> {
650 /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
652 /// This function can be used for control flow based on result values.
657 /// fn sq(x: uint) -> Result<uint, uint> { Ok(x * x) }
658 /// fn err(x: uint) -> Result<uint, uint> { Err(x) }
660 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
661 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
662 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
663 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
666 #[stable(feature = "rust1", since = "1.0.0")]
667 pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
674 /// Unwraps a result, yielding the content of an `Ok`.
675 /// Else it returns `optb`.
681 /// let x: Result<uint, &str> = Ok(9);
682 /// assert_eq!(x.unwrap_or(optb), 9);
684 /// let x: Result<uint, &str> = Err("error");
685 /// assert_eq!(x.unwrap_or(optb), optb);
688 #[stable(feature = "rust1", since = "1.0.0")]
689 pub fn unwrap_or(self, optb: T) -> T {
696 /// Unwraps a result, yielding the content of an `Ok`.
697 /// If the value is an `Err` then it calls `op` with its value.
702 /// fn count(x: &str) -> uint { x.len() }
704 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
705 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
708 #[stable(feature = "rust1", since = "1.0.0")]
709 pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
717 #[stable(feature = "rust1", since = "1.0.0")]
718 impl<T, E: fmt::Debug> Result<T, E> {
719 /// Unwraps a result, yielding the content of an `Ok`.
723 /// Panics if the value is an `Err`, with a custom panic message provided
724 /// by the `Err`'s value.
729 /// let x: Result<uint, &str> = Ok(2);
730 /// assert_eq!(x.unwrap(), 2);
733 /// ```{.should_fail}
734 /// let x: Result<uint, &str> = Err("emergency failure");
735 /// x.unwrap(); // panics with `emergency failure`
738 #[stable(feature = "rust1", since = "1.0.0")]
739 pub fn unwrap(self) -> T {
743 panic!("called `Result::unwrap()` on an `Err` value: {:?}", e)
748 #[stable(feature = "rust1", since = "1.0.0")]
749 impl<T: fmt::Debug, E> Result<T, E> {
750 /// Unwraps a result, yielding the content of an `Err`.
754 /// Panics if the value is an `Ok`, with a custom panic message provided
755 /// by the `Ok`'s value.
759 /// ```{.should_fail}
760 /// let x: Result<uint, &str> = Ok(2);
761 /// x.unwrap_err(); // panics with `2`
765 /// let x: Result<uint, &str> = Err("emergency failure");
766 /// assert_eq!(x.unwrap_err(), "emergency failure");
769 #[stable(feature = "rust1", since = "1.0.0")]
770 pub fn unwrap_err(self) -> E {
773 panic!("called `Result::unwrap_err()` on an `Ok` value: {:?}", t),
779 /////////////////////////////////////////////////////////////////////////////
780 // Trait implementations
781 /////////////////////////////////////////////////////////////////////////////
783 impl<T, E> AsSlice<T> for Result<T, E> {
784 /// Convert from `Result<T, E>` to `&[T]` (without copying)
786 #[stable(feature = "rust1", since = "1.0.0")]
787 fn as_slice<'a>(&'a self) -> &'a [T] {
789 Ok(ref x) => slice::ref_slice(x),
791 // work around lack of implicit coercion from fixed-size array to slice
799 /////////////////////////////////////////////////////////////////////////////
800 // The Result Iterators
801 /////////////////////////////////////////////////////////////////////////////
803 /// An iterator over a reference to the `Ok` variant of a `Result`.
804 #[stable(feature = "rust1", since = "1.0.0")]
805 pub struct Iter<'a, T: 'a> { inner: Option<&'a T> }
807 #[stable(feature = "rust1", since = "1.0.0")]
808 impl<'a, T> Iterator for Iter<'a, T> {
812 fn next(&mut self) -> Option<&'a T> { self.inner.take() }
814 fn size_hint(&self) -> (uint, Option<uint>) {
815 let n = if self.inner.is_some() {1} else {0};
820 #[stable(feature = "rust1", since = "1.0.0")]
821 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
823 fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
826 #[stable(feature = "rust1", since = "1.0.0")]
827 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
829 impl<'a, T> Clone for Iter<'a, T> {
830 fn clone(&self) -> Iter<'a, T> { Iter { inner: self.inner } }
833 /// An iterator over a mutable reference to the `Ok` variant of a `Result`.
834 #[stable(feature = "rust1", since = "1.0.0")]
835 pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
837 #[stable(feature = "rust1", since = "1.0.0")]
838 impl<'a, T> Iterator for IterMut<'a, T> {
839 type Item = &'a mut T;
842 fn next(&mut self) -> Option<&'a mut T> { self.inner.take() }
844 fn size_hint(&self) -> (uint, Option<uint>) {
845 let n = if self.inner.is_some() {1} else {0};
850 #[stable(feature = "rust1", since = "1.0.0")]
851 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
853 fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
856 #[stable(feature = "rust1", since = "1.0.0")]
857 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
859 /// An iterator over the value in a `Ok` variant of a `Result`.
860 #[stable(feature = "rust1", since = "1.0.0")]
861 pub struct IntoIter<T> { inner: Option<T> }
863 #[stable(feature = "rust1", since = "1.0.0")]
864 impl<T> Iterator for IntoIter<T> {
868 fn next(&mut self) -> Option<T> { self.inner.take() }
870 fn size_hint(&self) -> (uint, Option<uint>) {
871 let n = if self.inner.is_some() {1} else {0};
876 #[stable(feature = "rust1", since = "1.0.0")]
877 impl<T> DoubleEndedIterator for IntoIter<T> {
879 fn next_back(&mut self) -> Option<T> { self.inner.take() }
882 #[stable(feature = "rust1", since = "1.0.0")]
883 impl<T> ExactSizeIterator for IntoIter<T> {}
885 /////////////////////////////////////////////////////////////////////////////
887 /////////////////////////////////////////////////////////////////////////////
889 #[stable(feature = "rust1", since = "1.0.0")]
890 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
891 /// Takes each element in the `Iterator`: if it is an `Err`, no further
892 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
893 /// container with the values of each `Result` is returned.
895 /// Here is an example which increments every integer in a vector,
896 /// checking for overflow:
901 /// let v = vec!(1, 2);
902 /// let res: Result<Vec<uint>, &'static str> = v.iter().map(|&x: &uint|
903 /// if x == uint::MAX { Err("Overflow!") }
904 /// else { Ok(x + 1) }
906 /// assert!(res == Ok(vec!(2, 3)));
909 fn from_iter<I: Iterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
910 // FIXME(#11084): This could be replaced with Iterator::scan when this
911 // performance bug is closed.
913 struct Adapter<Iter, E> {
918 impl<T, E, Iter: Iterator<Item=Result<T, E>>> Iterator for Adapter<Iter, E> {
922 fn next(&mut self) -> Option<T> {
923 match self.iter.next() {
924 Some(Ok(value)) => Some(value),
926 self.err = Some(err);
934 let mut adapter = Adapter { iter: iter, err: None };
935 let v: V = FromIterator::from_iter(adapter.by_ref());
938 Some(err) => Err(err),
944 /////////////////////////////////////////////////////////////////////////////
946 /////////////////////////////////////////////////////////////////////////////
948 /// Perform a fold operation over the result values from an iterator.
950 /// If an `Err` is encountered, it is immediately returned.
951 /// Otherwise, the folded value is returned.
953 #[unstable(feature = "core")]
958 Iter: Iterator<Item=Result<T, E>>>(
965 Ok(v) => init = f(init, v),
966 Err(u) => return Err(u)