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.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::*;
114 //! use std::old_path::Path;
116 //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
117 //! // If `write_line` errors, then we'll never know, because the return
118 //! // value is ignored.
119 //! file.write_line("important message");
123 //! If you *do* write that in Rust, the compiler will give you a
124 //! warning (by default, controlled by the `unused_must_use` lint).
126 //! You might instead, if you don't want to handle the error, simply
127 //! panic, by converting to an `Option` with `ok`, then asserting
128 //! success with `expect`. This will panic if the write fails, proving
129 //! a marginally useful message indicating why:
132 //! use std::old_io::*;
133 //! use std::old_path::Path;
135 //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
136 //! file.write_line("important message").ok().expect("failed to write message");
140 //! You might also simply assert success:
143 //! # use std::old_io::*;
144 //! # use std::old_path::Path;
146 //! # let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
147 //! assert!(file.write_line("important message").is_ok());
151 //! Or propagate the error up the call stack with `try!`:
154 //! # use std::old_io::*;
155 //! # use std::old_path::Path;
156 //! fn write_message() -> Result<(), IoError> {
157 //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
158 //! try!(file.write_line("important message"));
164 //! # The `try!` macro
166 //! When writing code that calls many functions that return the
167 //! `Result` type, the error handling can be tedious. The `try!`
168 //! macro hides some of the boilerplate of propagating errors up the
171 //! It replaces this:
174 //! use std::old_io::*;
175 //! use std::old_path::Path;
183 //! fn write_info(info: &Info) -> Result<(), IoError> {
184 //! let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
185 //! // Early return on error
186 //! if let Err(e) = file.write_line(&format!("name: {}", info.name)) {
189 //! if let Err(e) = file.write_line(&format!("age: {}", info.age)) {
192 //! return file.write_line(&format!("rating: {}", info.rating));
199 //! use std::old_io::*;
200 //! use std::old_path::Path;
208 //! fn write_info(info: &Info) -> Result<(), IoError> {
209 //! let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
210 //! // Early return on error
211 //! try!(file.write_line(&format!("name: {}", info.name)));
212 //! try!(file.write_line(&format!("age: {}", info.age)));
213 //! try!(file.write_line(&format!("rating: {}", info.rating)));
218 //! *It's much nicer!*
220 //! Wrapping an expression in `try!` will result in the unwrapped
221 //! success (`Ok`) value, unless the result is `Err`, in which case
222 //! `Err` is returned early from the enclosing function. Its simple definition
226 //! macro_rules! try {
227 //! ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
231 //! `try!` is imported by the prelude, and is available everywhere.
233 #![stable(feature = "rust1", since = "1.0.0")]
235 use self::Result::{Ok, Err};
239 use iter::{Iterator, IteratorExt, DoubleEndedIterator,
240 FromIterator, ExactSizeIterator, IntoIterator};
241 use ops::{FnMut, FnOnce};
242 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")]
258 /// Contains the error value
259 #[stable(feature = "rust1", since = "1.0.0")]
263 /////////////////////////////////////////////////////////////////////////////
264 // Type implementation
265 /////////////////////////////////////////////////////////////////////////////
267 #[stable(feature = "rust1", since = "1.0.0")]
268 impl<T, E> Result<T, E> {
269 /////////////////////////////////////////////////////////////////////////
270 // Querying the contained values
271 /////////////////////////////////////////////////////////////////////////
273 /// Returns true if the result is `Ok`
278 /// let x: Result<int, &str> = Ok(-3);
279 /// assert_eq!(x.is_ok(), true);
281 /// let x: Result<int, &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`
298 /// let x: Result<int, &str> = Ok(-3);
299 /// assert_eq!(x.is_err(), false);
301 /// let x: Result<int, &str> = Err("Some error message");
302 /// assert_eq!(x.is_err(), true);
305 #[stable(feature = "rust1", since = "1.0.0")]
306 pub fn is_err(&self) -> bool {
310 /////////////////////////////////////////////////////////////////////////
311 // Adapter for each variant
312 /////////////////////////////////////////////////////////////////////////
314 /// Convert from `Result<T, E>` to `Option<T>`
316 /// Converts `self` into an `Option<T>`, consuming `self`,
317 /// and discarding the error, if any.
322 /// let x: Result<u32, &str> = Ok(2);
323 /// assert_eq!(x.ok(), Some(2));
325 /// let x: Result<u32, &str> = Err("Nothing here");
326 /// assert_eq!(x.ok(), None);
329 #[stable(feature = "rust1", since = "1.0.0")]
330 pub fn ok(self) -> Option<T> {
337 /// Convert from `Result<T, E>` to `Option<E>`
339 /// Converts `self` into an `Option<E>`, consuming `self`,
340 /// and discarding the success value, if any.
345 /// let x: Result<u32, &str> = Ok(2);
346 /// assert_eq!(x.err(), None);
348 /// let x: Result<u32, &str> = Err("Nothing here");
349 /// assert_eq!(x.err(), Some("Nothing here"));
352 #[stable(feature = "rust1", since = "1.0.0")]
353 pub fn err(self) -> Option<E> {
360 /////////////////////////////////////////////////////////////////////////
361 // Adapter for working with references
362 /////////////////////////////////////////////////////////////////////////
364 /// Convert from `Result<T, E>` to `Result<&T, &E>`
366 /// Produces a new `Result`, containing a reference
367 /// into the original, leaving the original in place.
370 /// let x: Result<u32, &str> = Ok(2);
371 /// assert_eq!(x.as_ref(), Ok(&2));
373 /// let x: Result<u32, &str> = Err("Error");
374 /// assert_eq!(x.as_ref(), Err(&"Error"));
377 #[stable(feature = "rust1", since = "1.0.0")]
378 pub fn as_ref(&self) -> Result<&T, &E> {
381 Err(ref x) => Err(x),
385 /// Convert from `Result<T, E>` to `Result<&mut T, &mut E>`
388 /// fn mutate(r: &mut Result<int, int>) {
389 /// match r.as_mut() {
390 /// Ok(&mut ref mut v) => *v = 42,
391 /// Err(&mut ref mut e) => *e = 0,
395 /// let mut x: Result<int, int> = Ok(2);
397 /// assert_eq!(x.unwrap(), 42);
399 /// let mut x: Result<int, int> = Err(13);
401 /// assert_eq!(x.unwrap_err(), 0);
404 #[stable(feature = "rust1", since = "1.0.0")]
405 pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
407 Ok(ref mut x) => Ok(x),
408 Err(ref mut x) => Err(x),
412 /// Convert from `Result<T, E>` to `&[T]` (without copying)
414 #[unstable(feature = "as_slice", since = "unsure of the utility here")]
415 pub fn as_slice(&self) -> &[T] {
417 Ok(ref x) => slice::ref_slice(x),
419 // work around lack of implicit coercion from fixed-size array to slice
426 /// Convert from `Result<T, E>` to `&mut [T]` (without copying)
429 /// let mut x: Result<&str, u32> = Ok("Gold");
431 /// let v = x.as_mut_slice();
432 /// assert!(v == ["Gold"]);
434 /// assert!(v == ["Silver"]);
436 /// assert_eq!(x, Ok("Silver"));
438 /// let mut x: Result<&str, u32> = Err(45);
439 /// assert!(x.as_mut_slice().is_empty());
442 #[unstable(feature = "core",
443 reason = "waiting for mut conventions")]
444 pub fn as_mut_slice(&mut self) -> &mut [T] {
446 Ok(ref mut x) => slice::mut_ref_slice(x),
448 // work around lack of implicit coercion from fixed-size array to slice
449 let emp: &mut [_] = &mut [];
455 /////////////////////////////////////////////////////////////////////////
456 // Transforming contained values
457 /////////////////////////////////////////////////////////////////////////
459 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to an
460 /// contained `Ok` value, leaving an `Err` value untouched.
462 /// This function can be used to compose the results of two functions.
466 /// Sum the lines of a buffer by mapping strings to numbers,
467 /// ignoring I/O and parse errors:
470 /// use std::old_io::*;
472 /// let mut buffer: &[u8] = b"1\n2\n3\n4\n";
473 /// let mut buffer = &mut buffer;
477 /// while !buffer.is_empty() {
478 /// let line: IoResult<String> = buffer.read_line();
479 /// // Convert the string line to a number using `map` and `from_str`
480 /// let val: IoResult<int> = line.map(|line| {
481 /// line.trim_right().parse::<int>().unwrap_or(0)
483 /// // Add the value if there were no errors, otherwise add 0
484 /// sum += val.unwrap_or(0);
487 /// assert!(sum == 10);
490 #[stable(feature = "rust1", since = "1.0.0")]
491 pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
498 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to an
499 /// contained `Err` value, leaving an `Ok` value untouched.
501 /// This function can be used to pass through a successful result while handling
507 /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
509 /// let x: Result<u32, u32> = Ok(2);
510 /// assert_eq!(x.map_err(stringify), Ok(2));
512 /// let x: Result<u32, u32> = Err(13);
513 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
516 #[stable(feature = "rust1", since = "1.0.0")]
517 pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> {
524 /////////////////////////////////////////////////////////////////////////
525 // Iterator constructors
526 /////////////////////////////////////////////////////////////////////////
528 /// Returns an iterator over the possibly contained value.
533 /// let x: Result<u32, &str> = Ok(7);
534 /// assert_eq!(x.iter().next(), Some(&7));
536 /// let x: Result<u32, &str> = Err("nothing!");
537 /// assert_eq!(x.iter().next(), None);
540 #[stable(feature = "rust1", since = "1.0.0")]
541 pub fn iter(&self) -> Iter<T> {
542 Iter { inner: self.as_ref().ok() }
545 /// Returns a mutable iterator over the possibly contained value.
550 /// let mut x: Result<u32, &str> = Ok(7);
551 /// match x.iter_mut().next() {
552 /// Some(&mut ref mut x) => *x = 40,
555 /// assert_eq!(x, Ok(40));
557 /// let mut x: Result<u32, &str> = Err("nothing!");
558 /// assert_eq!(x.iter_mut().next(), None);
561 #[stable(feature = "rust1", since = "1.0.0")]
562 pub fn iter_mut(&mut self) -> IterMut<T> {
563 IterMut { inner: self.as_mut().ok() }
566 /// Returns a consuming iterator over the possibly contained value.
571 /// let x: Result<u32, &str> = Ok(5);
572 /// let v: Vec<u32> = x.into_iter().collect();
573 /// assert_eq!(v, [5]);
575 /// let x: Result<u32, &str> = Err("nothing!");
576 /// let v: Vec<u32> = x.into_iter().collect();
577 /// assert_eq!(v, []);
580 #[stable(feature = "rust1", since = "1.0.0")]
581 pub fn into_iter(self) -> IntoIter<T> {
582 IntoIter { inner: self.ok() }
585 ////////////////////////////////////////////////////////////////////////
586 // Boolean operations on the values, eager and lazy
587 /////////////////////////////////////////////////////////////////////////
589 /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
594 /// let x: Result<u32, &str> = Ok(2);
595 /// let y: Result<&str, &str> = Err("late error");
596 /// assert_eq!(x.and(y), Err("late error"));
598 /// let x: Result<u32, &str> = Err("early error");
599 /// let y: Result<&str, &str> = Ok("foo");
600 /// assert_eq!(x.and(y), Err("early error"));
602 /// let x: Result<u32, &str> = Err("not a 2");
603 /// let y: Result<&str, &str> = Err("late error");
604 /// assert_eq!(x.and(y), Err("not a 2"));
606 /// let x: Result<u32, &str> = Ok(2);
607 /// let y: Result<&str, &str> = Ok("different result type");
608 /// assert_eq!(x.and(y), Ok("different result type"));
611 #[stable(feature = "rust1", since = "1.0.0")]
612 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
619 /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
621 /// This function can be used for control flow based on result values.
626 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
627 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
629 /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
630 /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
631 /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
632 /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
635 #[stable(feature = "rust1", since = "1.0.0")]
636 pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
643 /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
648 /// let x: Result<u32, &str> = Ok(2);
649 /// let y: Result<u32, &str> = Err("late error");
650 /// assert_eq!(x.or(y), Ok(2));
652 /// let x: Result<u32, &str> = Err("early error");
653 /// let y: Result<u32, &str> = Ok(2);
654 /// assert_eq!(x.or(y), Ok(2));
656 /// let x: Result<u32, &str> = Err("not a 2");
657 /// let y: Result<u32, &str> = Err("late error");
658 /// assert_eq!(x.or(y), Err("late error"));
660 /// let x: Result<u32, &str> = Ok(2);
661 /// let y: Result<u32, &str> = Ok(100);
662 /// assert_eq!(x.or(y), Ok(2));
665 #[stable(feature = "rust1", since = "1.0.0")]
666 pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
673 /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
675 /// This function can be used for control flow based on result values.
680 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
681 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
683 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
684 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
685 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
686 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
689 #[stable(feature = "rust1", since = "1.0.0")]
690 pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
697 /// Unwraps a result, yielding the content of an `Ok`.
698 /// Else it returns `optb`.
704 /// let x: Result<u32, &str> = Ok(9);
705 /// assert_eq!(x.unwrap_or(optb), 9);
707 /// let x: Result<u32, &str> = Err("error");
708 /// assert_eq!(x.unwrap_or(optb), optb);
711 #[stable(feature = "rust1", since = "1.0.0")]
712 pub fn unwrap_or(self, optb: T) -> T {
719 /// Unwraps a result, yielding the content of an `Ok`.
720 /// If the value is an `Err` then it calls `op` with its value.
725 /// fn count(x: &str) -> usize { x.len() }
727 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
728 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
731 #[stable(feature = "rust1", since = "1.0.0")]
732 pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
740 #[stable(feature = "rust1", since = "1.0.0")]
741 impl<T, E: fmt::Debug> Result<T, E> {
742 /// Unwraps a result, yielding the content of an `Ok`.
746 /// Panics if the value is an `Err`, with a custom panic message provided
747 /// by the `Err`'s value.
752 /// let x: Result<u32, &str> = Ok(2);
753 /// assert_eq!(x.unwrap(), 2);
756 /// ```{.should_fail}
757 /// let x: Result<u32, &str> = Err("emergency failure");
758 /// x.unwrap(); // panics with `emergency failure`
761 #[stable(feature = "rust1", since = "1.0.0")]
762 pub fn unwrap(self) -> T {
766 panic!("called `Result::unwrap()` on an `Err` value: {:?}", e)
771 #[stable(feature = "rust1", since = "1.0.0")]
772 impl<T: fmt::Debug, E> Result<T, E> {
773 /// Unwraps a result, yielding the content of an `Err`.
777 /// Panics if the value is an `Ok`, with a custom panic message provided
778 /// by the `Ok`'s value.
782 /// ```{.should_fail}
783 /// let x: Result<u32, &str> = Ok(2);
784 /// x.unwrap_err(); // panics with `2`
788 /// let x: Result<u32, &str> = Err("emergency failure");
789 /// assert_eq!(x.unwrap_err(), "emergency failure");
792 #[stable(feature = "rust1", since = "1.0.0")]
793 pub fn unwrap_err(self) -> E {
796 panic!("called `Result::unwrap_err()` on an `Ok` value: {:?}", t),
802 /////////////////////////////////////////////////////////////////////////////
803 // Trait implementations
804 /////////////////////////////////////////////////////////////////////////////
806 #[unstable(feature = "core",
807 reason = "waiting on the stability of the trait itself")]
808 #[deprecated(since = "1.0.0",
809 reason = "use inherent method instead")]
811 impl<T, E> AsSlice<T> for Result<T, E> {
812 /// Convert from `Result<T, E>` to `&[T]` (without copying)
814 fn as_slice<'a>(&'a self) -> &'a [T] {
816 Ok(ref x) => slice::ref_slice(x),
818 // work around lack of implicit coercion from fixed-size array to slice
826 /////////////////////////////////////////////////////////////////////////////
827 // The Result Iterators
828 /////////////////////////////////////////////////////////////////////////////
830 /// An iterator over a reference to the `Ok` variant of a `Result`.
831 #[stable(feature = "rust1", since = "1.0.0")]
832 pub struct Iter<'a, T: 'a> { inner: Option<&'a T> }
834 #[stable(feature = "rust1", since = "1.0.0")]
835 impl<'a, T> Iterator for Iter<'a, T> {
839 fn next(&mut self) -> Option<&'a T> { self.inner.take() }
841 fn size_hint(&self) -> (usize, Option<usize>) {
842 let n = if self.inner.is_some() {1} else {0};
847 #[stable(feature = "rust1", since = "1.0.0")]
848 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
850 fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
853 #[stable(feature = "rust1", since = "1.0.0")]
854 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
856 impl<'a, T> Clone for Iter<'a, T> {
857 fn clone(&self) -> Iter<'a, T> { Iter { inner: self.inner } }
860 /// An iterator over a mutable reference to the `Ok` variant of a `Result`.
861 #[stable(feature = "rust1", since = "1.0.0")]
862 pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
864 #[stable(feature = "rust1", since = "1.0.0")]
865 impl<'a, T> Iterator for IterMut<'a, T> {
866 type Item = &'a mut T;
869 fn next(&mut self) -> Option<&'a mut T> { self.inner.take() }
871 fn size_hint(&self) -> (usize, Option<usize>) {
872 let n = if self.inner.is_some() {1} else {0};
877 #[stable(feature = "rust1", since = "1.0.0")]
878 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
880 fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
883 #[stable(feature = "rust1", since = "1.0.0")]
884 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
886 /// An iterator over the value in a `Ok` variant of a `Result`.
887 #[stable(feature = "rust1", since = "1.0.0")]
888 pub struct IntoIter<T> { inner: Option<T> }
890 #[stable(feature = "rust1", since = "1.0.0")]
891 impl<T> Iterator for IntoIter<T> {
895 fn next(&mut self) -> Option<T> { self.inner.take() }
897 fn size_hint(&self) -> (usize, Option<usize>) {
898 let n = if self.inner.is_some() {1} else {0};
903 #[stable(feature = "rust1", since = "1.0.0")]
904 impl<T> DoubleEndedIterator for IntoIter<T> {
906 fn next_back(&mut self) -> Option<T> { self.inner.take() }
909 #[stable(feature = "rust1", since = "1.0.0")]
910 impl<T> ExactSizeIterator for IntoIter<T> {}
912 /////////////////////////////////////////////////////////////////////////////
914 /////////////////////////////////////////////////////////////////////////////
916 #[stable(feature = "rust1", since = "1.0.0")]
917 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
918 /// Takes each element in the `Iterator`: if it is an `Err`, no further
919 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
920 /// container with the values of each `Result` is returned.
922 /// Here is an example which increments every integer in a vector,
923 /// checking for overflow:
928 /// let v = vec!(1, 2);
929 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|&x: &u32|
930 /// if x == u32::MAX { Err("Overflow!") }
931 /// else { Ok(x + 1) }
933 /// assert!(res == Ok(vec!(2, 3)));
936 fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
937 // FIXME(#11084): This could be replaced with Iterator::scan when this
938 // performance bug is closed.
940 struct Adapter<Iter, E> {
945 impl<T, E, Iter: Iterator<Item=Result<T, E>>> Iterator for Adapter<Iter, E> {
949 fn next(&mut self) -> Option<T> {
950 match self.iter.next() {
951 Some(Ok(value)) => Some(value),
953 self.err = Some(err);
961 let mut adapter = Adapter { iter: iter.into_iter(), err: None };
962 let v: V = FromIterator::from_iter(adapter.by_ref());
965 Some(err) => Err(err),
971 /////////////////////////////////////////////////////////////////////////////
973 /////////////////////////////////////////////////////////////////////////////
975 /// Perform a fold operation over the result values from an iterator.
977 /// If an `Err` is encountered, it is immediately returned.
978 /// Otherwise, the folded value is returned.
980 #[unstable(feature = "core")]
985 Iter: Iterator<Item=Result<T, E>>>(
992 Ok(v) => init = f(init, v),
993 Err(u) => return Err(u)