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 //! match header.get(0) {
38 //! None => Err("invalid header length"),
39 //! Some(&1) => Ok(Version::Version1),
40 //! Some(&2) => Ok(Version::Version2),
41 //! Some(_) => Err("invalid version")
45 //! let version = parse_version(&[1, 2, 3, 4]);
47 //! Ok(v) => println!("working with version: {:?}", v),
48 //! Err(e) => println!("error parsing header: {:?}", e),
52 //! Pattern matching on `Result`s is clear and straightforward for
53 //! simple cases, but `Result` comes with some convenience methods
54 //! that make working with it more succinct.
57 //! let good_result: Result<i32, i32> = Ok(10);
58 //! let bad_result: Result<i32, i32> = Err(10);
60 //! // The `is_ok` and `is_err` methods do what they say.
61 //! assert!(good_result.is_ok() && !good_result.is_err());
62 //! assert!(bad_result.is_err() && !bad_result.is_ok());
64 //! // `map` consumes the `Result` and produces another.
65 //! let good_result: Result<i32, i32> = good_result.map(|i| i + 1);
66 //! let bad_result: Result<i32, i32> = bad_result.map(|i| i - 1);
68 //! // Use `and_then` to continue the computation.
69 //! let good_result: Result<bool, i32> = good_result.and_then(|i| Ok(i == 11));
71 //! // Use `or_else` to handle the error.
72 //! let bad_result: Result<i32, i32> = bad_result.or_else(|i| Ok(i + 20));
74 //! // Consume the result and return the contents with `unwrap`.
75 //! let final_awesome_result = good_result.unwrap();
78 //! # Results must be used
80 //! A common problem with using return values to indicate errors is
81 //! that it is easy to ignore the return value, thus failing to handle
82 //! the error. Result is annotated with the #[must_use] attribute,
83 //! which will cause the compiler to issue a warning when a Result
84 //! value is ignored. This makes `Result` especially useful with
85 //! functions that may encounter errors but don't otherwise return a
88 //! Consider the `write_all` method defined for I/O types
89 //! by the [`Write`](../../std/io/trait.Write.html) trait:
95 //! fn write_all(&mut self, bytes: &[u8]) -> Result<(), io::Error>;
99 //! *Note: The actual definition of `Write` uses `io::Result`, which
100 //! is just a synonym for `Result<T, io::Error>`.*
102 //! This method doesn't produce a value, but the write may
103 //! fail. It's crucial to handle the error case, and *not* write
104 //! something like this:
107 //! use std::fs::File;
108 //! use std::io::prelude::*;
110 //! let mut file = File::create("valuable_data.txt").unwrap();
111 //! // If `write_all` errors, then we'll never know, because the return
112 //! // value is ignored.
113 //! file.write_all(b"important message");
116 //! If you *do* write that in Rust, the compiler will give you a
117 //! warning (by default, controlled by the `unused_must_use` lint).
119 //! You might instead, if you don't want to handle the error, simply
120 //! assert success with `expect`. This will panic if the
121 //! write fails, providing a marginally useful message indicating why:
124 //! use std::fs::File;
125 //! use std::io::prelude::*;
127 //! let mut file = File::create("valuable_data.txt").unwrap();
128 //! file.write_all(b"important message").expect("failed to write message");
131 //! You might also simply assert success:
134 //! # use std::fs::File;
135 //! # use std::io::prelude::*;
136 //! # let mut file = File::create("valuable_data.txt").unwrap();
137 //! assert!(file.write_all(b"important message").is_ok());
140 //! Or propagate the error up the call stack with `try!`:
143 //! # use std::fs::File;
144 //! # use std::io::prelude::*;
146 //! fn write_message() -> io::Result<()> {
147 //! let mut file = try!(File::create("valuable_data.txt"));
148 //! try!(file.write_all(b"important message"));
153 //! # The `try!` macro
155 //! When writing code that calls many functions that return the
156 //! `Result` type, the error handling can be tedious. The `try!`
157 //! macro hides some of the boilerplate of propagating errors up the
160 //! It replaces this:
163 //! use std::fs::File;
164 //! use std::io::prelude::*;
173 //! fn write_info(info: &Info) -> io::Result<()> {
174 //! let mut file = try!(File::create("my_best_friends.txt"));
175 //! // Early return on error
176 //! if let Err(e) = file.write_all(format!("name: {}\n", info.name).as_bytes()) {
179 //! if let Err(e) = file.write_all(format!("age: {}\n", info.age).as_bytes()) {
182 //! if let Err(e) = file.write_all(format!("rating: {}\n", info.rating).as_bytes()) {
192 //! use std::fs::File;
193 //! use std::io::prelude::*;
202 //! fn write_info(info: &Info) -> io::Result<()> {
203 //! let mut file = try!(File::create("my_best_friends.txt"));
204 //! // Early return on error
205 //! try!(file.write_all(format!("name: {}\n", info.name).as_bytes()));
206 //! try!(file.write_all(format!("age: {}\n", info.age).as_bytes()));
207 //! try!(file.write_all(format!("rating: {}\n", info.rating).as_bytes()));
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, but it can only
226 //! be used in functions that return `Result` because of the early return of
227 //! `Err` that it provides.
229 #![stable(feature = "rust1", since = "1.0.0")]
231 use self::Result::{Ok, Err};
235 use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSizeIterator, IntoIterator};
237 use option::Option::{self, None, Some};
240 /// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
242 /// See the [`std::result`](index.html) module documentation for details.
243 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
245 #[stable(feature = "rust1", since = "1.0.0")]
246 pub enum Result<T, E> {
247 /// Contains the success value
248 #[stable(feature = "rust1", since = "1.0.0")]
251 /// Contains the error value
252 #[stable(feature = "rust1", since = "1.0.0")]
256 /////////////////////////////////////////////////////////////////////////////
257 // Type implementation
258 /////////////////////////////////////////////////////////////////////////////
260 #[stable(feature = "rust1", since = "1.0.0")]
261 impl<T, E> Result<T, E> {
262 /////////////////////////////////////////////////////////////////////////
263 // Querying the contained values
264 /////////////////////////////////////////////////////////////////////////
266 /// Returns true if the result is `Ok`
271 /// let x: Result<i32, &str> = Ok(-3);
272 /// assert_eq!(x.is_ok(), true);
274 /// let x: Result<i32, &str> = Err("Some error message");
275 /// assert_eq!(x.is_ok(), false);
278 #[stable(feature = "rust1", since = "1.0.0")]
279 pub fn is_ok(&self) -> bool {
286 /// Returns true if the result is `Err`
291 /// let x: Result<i32, &str> = Ok(-3);
292 /// assert_eq!(x.is_err(), false);
294 /// let x: Result<i32, &str> = Err("Some error message");
295 /// assert_eq!(x.is_err(), true);
298 #[stable(feature = "rust1", since = "1.0.0")]
299 pub fn is_err(&self) -> bool {
303 /////////////////////////////////////////////////////////////////////////
304 // Adapter for each variant
305 /////////////////////////////////////////////////////////////////////////
307 /// Converts from `Result<T, E>` to `Option<T>`
309 /// Converts `self` into an `Option<T>`, consuming `self`,
310 /// and discarding the error, if any.
315 /// let x: Result<u32, &str> = Ok(2);
316 /// assert_eq!(x.ok(), Some(2));
318 /// let x: Result<u32, &str> = Err("Nothing here");
319 /// assert_eq!(x.ok(), None);
322 #[stable(feature = "rust1", since = "1.0.0")]
323 pub fn ok(self) -> Option<T> {
330 /// Converts from `Result<T, E>` to `Option<E>`
332 /// Converts `self` into an `Option<E>`, consuming `self`,
333 /// and discarding the success value, if any.
338 /// let x: Result<u32, &str> = Ok(2);
339 /// assert_eq!(x.err(), None);
341 /// let x: Result<u32, &str> = Err("Nothing here");
342 /// assert_eq!(x.err(), Some("Nothing here"));
345 #[stable(feature = "rust1", since = "1.0.0")]
346 pub fn err(self) -> Option<E> {
353 /////////////////////////////////////////////////////////////////////////
354 // Adapter for working with references
355 /////////////////////////////////////////////////////////////////////////
357 /// Converts from `Result<T, E>` to `Result<&T, &E>`
359 /// Produces a new `Result`, containing a reference
360 /// into the original, leaving the original in place.
363 /// let x: Result<u32, &str> = Ok(2);
364 /// assert_eq!(x.as_ref(), Ok(&2));
366 /// let x: Result<u32, &str> = Err("Error");
367 /// assert_eq!(x.as_ref(), Err(&"Error"));
370 #[stable(feature = "rust1", since = "1.0.0")]
371 pub fn as_ref(&self) -> Result<&T, &E> {
374 Err(ref x) => Err(x),
378 /// Converts from `Result<T, E>` to `Result<&mut T, &mut E>`
381 /// fn mutate(r: &mut Result<i32, i32>) {
382 /// match r.as_mut() {
383 /// Ok(&mut ref mut v) => *v = 42,
384 /// Err(&mut ref mut e) => *e = 0,
388 /// let mut x: Result<i32, i32> = Ok(2);
390 /// assert_eq!(x.unwrap(), 42);
392 /// let mut x: Result<i32, i32> = Err(13);
394 /// assert_eq!(x.unwrap_err(), 0);
397 #[stable(feature = "rust1", since = "1.0.0")]
398 pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
400 Ok(ref mut x) => Ok(x),
401 Err(ref mut x) => Err(x),
405 /// Converts from `Result<T, E>` to `&[T]` (without copying)
407 #[unstable(feature = "as_slice", reason = "unsure of the utility here",
409 #[deprecated(since = "1.4.0", reason = "niche API, unclear of usefulness")]
411 pub fn as_slice(&self) -> &[T] {
413 Ok(ref x) => slice::ref_slice(x),
415 // work around lack of implicit coercion from fixed-size array to slice
422 /// Converts from `Result<T, E>` to `&mut [T]` (without copying)
425 /// #![feature(as_slice)]
427 /// let mut x: Result<&str, u32> = Ok("Gold");
429 /// let v = x.as_mut_slice();
430 /// assert!(v == ["Gold"]);
432 /// assert!(v == ["Silver"]);
434 /// assert_eq!(x, Ok("Silver"));
436 /// let mut x: Result<&str, u32> = Err(45);
437 /// assert!(x.as_mut_slice().is_empty());
440 #[unstable(feature = "as_slice",
441 reason = "waiting for mut conventions",
443 #[deprecated(since = "1.4.0", reason = "niche API, unclear of usefulness")]
445 pub fn as_mut_slice(&mut self) -> &mut [T] {
447 Ok(ref mut x) => slice::mut_ref_slice(x),
449 // work around lack of implicit coercion from fixed-size array to slice
450 let emp: &mut [_] = &mut [];
456 /////////////////////////////////////////////////////////////////////////
457 // Transforming contained values
458 /////////////////////////////////////////////////////////////////////////
460 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to an
461 /// contained `Ok` value, leaving an `Err` value untouched.
463 /// This function can be used to compose the results of two functions.
467 /// Print the numbers on each line of a string multiplied by two.
470 /// let line = "1\n2\n3\n4\n";
472 /// for num in line.lines() {
473 /// match num.parse::<i32>().map(|i| i * 2) {
474 /// Ok(n) => println!("{}", n),
480 #[stable(feature = "rust1", since = "1.0.0")]
481 pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
488 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to an
489 /// contained `Err` value, leaving an `Ok` value untouched.
491 /// This function can be used to pass through a successful result while handling
497 /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
499 /// let x: Result<u32, u32> = Ok(2);
500 /// assert_eq!(x.map_err(stringify), Ok(2));
502 /// let x: Result<u32, u32> = Err(13);
503 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
506 #[stable(feature = "rust1", since = "1.0.0")]
507 pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> {
514 /////////////////////////////////////////////////////////////////////////
515 // Iterator constructors
516 /////////////////////////////////////////////////////////////////////////
518 /// Returns an iterator over the possibly contained value.
523 /// let x: Result<u32, &str> = Ok(7);
524 /// assert_eq!(x.iter().next(), Some(&7));
526 /// let x: Result<u32, &str> = Err("nothing!");
527 /// assert_eq!(x.iter().next(), None);
530 #[stable(feature = "rust1", since = "1.0.0")]
531 pub fn iter(&self) -> Iter<T> {
532 Iter { inner: self.as_ref().ok() }
535 /// Returns a mutable iterator over the possibly contained value.
540 /// let mut x: Result<u32, &str> = Ok(7);
541 /// match x.iter_mut().next() {
542 /// Some(v) => *v = 40,
545 /// assert_eq!(x, Ok(40));
547 /// let mut x: Result<u32, &str> = Err("nothing!");
548 /// assert_eq!(x.iter_mut().next(), None);
551 #[stable(feature = "rust1", since = "1.0.0")]
552 pub fn iter_mut(&mut self) -> IterMut<T> {
553 IterMut { inner: self.as_mut().ok() }
556 ////////////////////////////////////////////////////////////////////////
557 // Boolean operations on the values, eager and lazy
558 /////////////////////////////////////////////////////////////////////////
560 /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
565 /// let x: Result<u32, &str> = Ok(2);
566 /// let y: Result<&str, &str> = Err("late error");
567 /// assert_eq!(x.and(y), Err("late error"));
569 /// let x: Result<u32, &str> = Err("early error");
570 /// let y: Result<&str, &str> = Ok("foo");
571 /// assert_eq!(x.and(y), Err("early error"));
573 /// let x: Result<u32, &str> = Err("not a 2");
574 /// let y: Result<&str, &str> = Err("late error");
575 /// assert_eq!(x.and(y), Err("not a 2"));
577 /// let x: Result<u32, &str> = Ok(2);
578 /// let y: Result<&str, &str> = Ok("different result type");
579 /// assert_eq!(x.and(y), Ok("different result type"));
582 #[stable(feature = "rust1", since = "1.0.0")]
583 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
590 /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
592 /// This function can be used for control flow based on result values.
597 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
598 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
600 /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
601 /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
602 /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
603 /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
606 #[stable(feature = "rust1", since = "1.0.0")]
607 pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
614 /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
619 /// let x: Result<u32, &str> = Ok(2);
620 /// let y: Result<u32, &str> = Err("late error");
621 /// assert_eq!(x.or(y), Ok(2));
623 /// let x: Result<u32, &str> = Err("early error");
624 /// let y: Result<u32, &str> = Ok(2);
625 /// assert_eq!(x.or(y), Ok(2));
627 /// let x: Result<u32, &str> = Err("not a 2");
628 /// let y: Result<u32, &str> = Err("late error");
629 /// assert_eq!(x.or(y), Err("late error"));
631 /// let x: Result<u32, &str> = Ok(2);
632 /// let y: Result<u32, &str> = Ok(100);
633 /// assert_eq!(x.or(y), Ok(2));
636 #[stable(feature = "rust1", since = "1.0.0")]
637 pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
644 /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
646 /// This function can be used for control flow based on result values.
651 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
652 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
654 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
655 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
656 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
657 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
660 #[stable(feature = "rust1", since = "1.0.0")]
661 pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
668 /// Unwraps a result, yielding the content of an `Ok`.
669 /// Else it returns `optb`.
675 /// let x: Result<u32, &str> = Ok(9);
676 /// assert_eq!(x.unwrap_or(optb), 9);
678 /// let x: Result<u32, &str> = Err("error");
679 /// assert_eq!(x.unwrap_or(optb), optb);
682 #[stable(feature = "rust1", since = "1.0.0")]
683 pub fn unwrap_or(self, optb: T) -> T {
690 /// Unwraps a result, yielding the content of an `Ok`.
691 /// 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 #[stable(feature = "rust1", since = "1.0.0")]
712 impl<T, E: fmt::Debug> Result<T, E> {
713 /// Unwraps a result, yielding the content of an `Ok`.
717 /// Panics if the value is an `Err`, with a panic message provided by the
723 /// let x: Result<u32, &str> = Ok(2);
724 /// assert_eq!(x.unwrap(), 2);
727 /// ```{.should_panic}
728 /// let x: Result<u32, &str> = Err("emergency failure");
729 /// x.unwrap(); // panics with `emergency failure`
732 #[stable(feature = "rust1", since = "1.0.0")]
733 pub fn unwrap(self) -> T {
737 panic!("called `Result::unwrap()` on an `Err` value: {:?}", e)
741 /// Unwraps a result, yielding the content of an `Ok`.
743 /// Panics if the value is an `Err`, with a panic message including the
744 /// passed message, and the content of the `Err`.
747 /// ```{.should_panic}
748 /// let x: Result<u32, &str> = Err("emergency failure");
749 /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
752 #[stable(feature = "result_expect", since = "1.4.0")]
753 pub fn expect(self, msg: &str) -> T {
756 Err(e) => panic!("{}: {:?}", msg, e),
761 #[stable(feature = "rust1", since = "1.0.0")]
762 impl<T: fmt::Debug, E> Result<T, E> {
763 /// Unwraps a result, yielding the content of an `Err`.
767 /// Panics if the value is an `Ok`, with a custom panic message provided
768 /// by the `Ok`'s value.
772 /// ```{.should_panic}
773 /// let x: Result<u32, &str> = Ok(2);
774 /// x.unwrap_err(); // panics with `2`
778 /// let x: Result<u32, &str> = Err("emergency failure");
779 /// assert_eq!(x.unwrap_err(), "emergency failure");
782 #[stable(feature = "rust1", since = "1.0.0")]
783 pub fn unwrap_err(self) -> E {
786 panic!("called `Result::unwrap_err()` on an `Ok` value: {:?}", t),
792 /////////////////////////////////////////////////////////////////////////////
793 // Trait implementations
794 /////////////////////////////////////////////////////////////////////////////
796 #[stable(feature = "rust1", since = "1.0.0")]
797 impl<T, E> IntoIterator for Result<T, E> {
799 type IntoIter = IntoIter<T>;
801 /// Returns a consuming iterator over the possibly contained value.
806 /// let x: Result<u32, &str> = Ok(5);
807 /// let v: Vec<u32> = x.into_iter().collect();
808 /// assert_eq!(v, [5]);
810 /// let x: Result<u32, &str> = Err("nothing!");
811 /// let v: Vec<u32> = x.into_iter().collect();
812 /// assert_eq!(v, []);
815 fn into_iter(self) -> IntoIter<T> {
816 IntoIter { inner: self.ok() }
820 #[stable(since = "1.4.0", feature = "result_iter")]
821 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
823 type IntoIter = Iter<'a, T>;
825 fn into_iter(self) -> Iter<'a, T> {
830 #[stable(since = "1.4.0", feature = "result_iter")]
831 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
832 type Item = &'a mut T;
833 type IntoIter = IterMut<'a, T>;
835 fn into_iter(mut self) -> IterMut<'a, T> {
840 /////////////////////////////////////////////////////////////////////////////
841 // The Result Iterators
842 /////////////////////////////////////////////////////////////////////////////
844 /// An iterator over a reference to the `Ok` variant of a `Result`.
845 #[stable(feature = "rust1", since = "1.0.0")]
846 pub struct Iter<'a, T: 'a> { inner: Option<&'a T> }
848 #[stable(feature = "rust1", since = "1.0.0")]
849 impl<'a, T> Iterator for Iter<'a, T> {
853 fn next(&mut self) -> Option<&'a T> { self.inner.take() }
855 fn size_hint(&self) -> (usize, Option<usize>) {
856 let n = if self.inner.is_some() {1} else {0};
861 #[stable(feature = "rust1", since = "1.0.0")]
862 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
864 fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
867 #[stable(feature = "rust1", since = "1.0.0")]
868 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
870 impl<'a, T> Clone for Iter<'a, T> {
871 fn clone(&self) -> Iter<'a, T> { Iter { inner: self.inner } }
874 /// An iterator over a mutable reference to the `Ok` variant of a `Result`.
875 #[stable(feature = "rust1", since = "1.0.0")]
876 pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
878 #[stable(feature = "rust1", since = "1.0.0")]
879 impl<'a, T> Iterator for IterMut<'a, T> {
880 type Item = &'a mut T;
883 fn next(&mut self) -> Option<&'a mut T> { self.inner.take() }
885 fn size_hint(&self) -> (usize, Option<usize>) {
886 let n = if self.inner.is_some() {1} else {0};
891 #[stable(feature = "rust1", since = "1.0.0")]
892 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
894 fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
897 #[stable(feature = "rust1", since = "1.0.0")]
898 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
900 /// An iterator over the value in a `Ok` variant of a `Result`.
901 #[stable(feature = "rust1", since = "1.0.0")]
902 pub struct IntoIter<T> { inner: Option<T> }
904 #[stable(feature = "rust1", since = "1.0.0")]
905 impl<T> Iterator for IntoIter<T> {
909 fn next(&mut self) -> Option<T> { self.inner.take() }
911 fn size_hint(&self) -> (usize, Option<usize>) {
912 let n = if self.inner.is_some() {1} else {0};
917 #[stable(feature = "rust1", since = "1.0.0")]
918 impl<T> DoubleEndedIterator for IntoIter<T> {
920 fn next_back(&mut self) -> Option<T> { self.inner.take() }
923 #[stable(feature = "rust1", since = "1.0.0")]
924 impl<T> ExactSizeIterator for IntoIter<T> {}
926 /////////////////////////////////////////////////////////////////////////////
928 /////////////////////////////////////////////////////////////////////////////
930 #[stable(feature = "rust1", since = "1.0.0")]
931 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
932 /// Takes each element in the `Iterator`: if it is an `Err`, no further
933 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
934 /// container with the values of each `Result` is returned.
936 /// Here is an example which increments every integer in a vector,
937 /// checking for overflow:
942 /// let v = vec!(1, 2);
943 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|&x: &u32|
944 /// if x == u32::MAX { Err("Overflow!") }
945 /// else { Ok(x + 1) }
947 /// assert!(res == Ok(vec!(2, 3)));
950 fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
951 // FIXME(#11084): This could be replaced with Iterator::scan when this
952 // performance bug is closed.
954 struct Adapter<Iter, E> {
959 impl<T, E, Iter: Iterator<Item=Result<T, E>>> Iterator for Adapter<Iter, E> {
963 fn next(&mut self) -> Option<T> {
964 match self.iter.next() {
965 Some(Ok(value)) => Some(value),
967 self.err = Some(err);
975 let mut adapter = Adapter { iter: iter.into_iter(), err: None };
976 let v: V = FromIterator::from_iter(adapter.by_ref());
979 Some(err) => Err(err),