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 //! let mut file = try!(File::create("my_best_friends.txt"));
179 //! // Early return on error
180 //! if let Err(e) = file.write_all(format!("name: {}\n", info.name).as_bytes()) {
183 //! if let Err(e) = file.write_all(format!("age: {}\n", info.age).as_bytes()) {
186 //! if let Err(e) = file.write_all(format!("rating: {}\n", info.rating).as_bytes()) {
196 //! # #![allow(dead_code)]
197 //! use std::fs::File;
198 //! use std::io::prelude::*;
207 //! fn write_info(info: &Info) -> io::Result<()> {
208 //! let mut file = try!(File::create("my_best_friends.txt"));
209 //! // Early return on error
210 //! try!(file.write_all(format!("name: {}\n", info.name).as_bytes()));
211 //! try!(file.write_all(format!("age: {}\n", info.age).as_bytes()));
212 //! try!(file.write_all(format!("rating: {}\n", info.rating).as_bytes()));
217 //! *It's much nicer!*
219 //! Wrapping an expression in `try!` will result in the unwrapped
220 //! success (`Ok`) value, unless the result is `Err`, in which case
221 //! `Err` is returned early from the enclosing function. Its simple definition
225 //! macro_rules! try {
226 //! ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
230 //! `try!` is imported by the prelude and is available everywhere, but it can only
231 //! be used in functions that return `Result` because of the early return of
232 //! `Err` that it provides.
234 #![stable(feature = "rust1", since = "1.0.0")]
236 use self::Result
::{Ok, Err}
;
240 use iter
::{Iterator, DoubleEndedIterator, FromIterator, ExactSizeIterator, IntoIterator}
;
242 use option
::Option
::{self, None, Some}
;
244 /// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
246 /// See the [`std::result`](index.html) module documentation for details.
247 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
249 #[stable(feature = "rust1", since = "1.0.0")]
250 pub enum Result
<T
, E
> {
251 /// Contains the success value
252 #[stable(feature = "rust1", since = "1.0.0")]
253 Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
255 /// Contains the error value
256 #[stable(feature = "rust1", since = "1.0.0")]
257 Err(#[stable(feature = "rust1", since = "1.0.0")] E)
260 /////////////////////////////////////////////////////////////////////////////
261 // Type implementation
262 /////////////////////////////////////////////////////////////////////////////
264 impl<T
, E
> Result
<T
, E
> {
265 /////////////////////////////////////////////////////////////////////////
266 // Querying the contained values
267 /////////////////////////////////////////////////////////////////////////
269 /// Returns true if the result is `Ok`
274 /// let x: Result<i32, &str> = Ok(-3);
275 /// assert_eq!(x.is_ok(), true);
277 /// let x: Result<i32, &str> = Err("Some error message");
278 /// assert_eq!(x.is_ok(), false);
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub fn is_ok(&self) -> bool
{
289 /// Returns true if the result is `Err`
294 /// let x: Result<i32, &str> = Ok(-3);
295 /// assert_eq!(x.is_err(), false);
297 /// let x: Result<i32, &str> = Err("Some error message");
298 /// assert_eq!(x.is_err(), true);
301 #[stable(feature = "rust1", since = "1.0.0")]
302 pub fn is_err(&self) -> bool
{
306 /////////////////////////////////////////////////////////////////////////
307 // Adapter for each variant
308 /////////////////////////////////////////////////////////////////////////
310 /// Converts from `Result<T, E>` to `Option<T>`
312 /// Converts `self` into an `Option<T>`, consuming `self`,
313 /// and discarding the error, if any.
318 /// let x: Result<u32, &str> = Ok(2);
319 /// assert_eq!(x.ok(), Some(2));
321 /// let x: Result<u32, &str> = Err("Nothing here");
322 /// assert_eq!(x.ok(), None);
325 #[stable(feature = "rust1", since = "1.0.0")]
326 pub fn ok(self) -> Option
<T
> {
333 /// Converts from `Result<T, E>` to `Option<E>`
335 /// Converts `self` into an `Option<E>`, consuming `self`,
336 /// and discarding the success value, if any.
341 /// let x: Result<u32, &str> = Ok(2);
342 /// assert_eq!(x.err(), None);
344 /// let x: Result<u32, &str> = Err("Nothing here");
345 /// assert_eq!(x.err(), Some("Nothing here"));
348 #[stable(feature = "rust1", since = "1.0.0")]
349 pub fn err(self) -> Option
<E
> {
356 /////////////////////////////////////////////////////////////////////////
357 // Adapter for working with references
358 /////////////////////////////////////////////////////////////////////////
360 /// Converts from `Result<T, E>` to `Result<&T, &E>`
362 /// Produces a new `Result`, containing a reference
363 /// into the original, leaving the original in place.
366 /// let x: Result<u32, &str> = Ok(2);
367 /// assert_eq!(x.as_ref(), Ok(&2));
369 /// let x: Result<u32, &str> = Err("Error");
370 /// assert_eq!(x.as_ref(), Err(&"Error"));
373 #[stable(feature = "rust1", since = "1.0.0")]
374 pub fn as_ref(&self) -> Result
<&T
, &E
> {
377 Err(ref x
) => Err(x
),
381 /// Converts from `Result<T, E>` to `Result<&mut T, &mut E>`
384 /// fn mutate(r: &mut Result<i32, i32>) {
385 /// match r.as_mut() {
386 /// Ok(&mut ref mut v) => *v = 42,
387 /// Err(&mut ref mut e) => *e = 0,
391 /// let mut x: Result<i32, i32> = Ok(2);
393 /// assert_eq!(x.unwrap(), 42);
395 /// let mut x: Result<i32, i32> = Err(13);
397 /// assert_eq!(x.unwrap_err(), 0);
400 #[stable(feature = "rust1", since = "1.0.0")]
401 pub fn as_mut(&mut self) -> Result
<&mut T
, &mut E
> {
403 Ok(ref mut x
) => Ok(x
),
404 Err(ref mut x
) => Err(x
),
408 /////////////////////////////////////////////////////////////////////////
409 // Transforming contained values
410 /////////////////////////////////////////////////////////////////////////
412 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
413 /// contained `Ok` value, leaving an `Err` value untouched.
415 /// This function can be used to compose the results of two functions.
419 /// Print the numbers on each line of a string multiplied by two.
422 /// let line = "1\n2\n3\n4\n";
424 /// for num in line.lines() {
425 /// match num.parse::<i32>().map(|i| i * 2) {
426 /// Ok(n) => println!("{}", n),
432 #[stable(feature = "rust1", since = "1.0.0")]
433 pub fn map
<U
, F
: FnOnce(T
) -> U
>(self, op
: F
) -> Result
<U
,E
> {
440 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
441 /// contained `Err` value, leaving an `Ok` value untouched.
443 /// This function can be used to pass through a successful result while handling
449 /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
451 /// let x: Result<u32, u32> = Ok(2);
452 /// assert_eq!(x.map_err(stringify), Ok(2));
454 /// let x: Result<u32, u32> = Err(13);
455 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
458 #[stable(feature = "rust1", since = "1.0.0")]
459 pub fn map_err
<F
, O
: FnOnce(E
) -> F
>(self, op
: O
) -> Result
<T
,F
> {
466 /////////////////////////////////////////////////////////////////////////
467 // Iterator constructors
468 /////////////////////////////////////////////////////////////////////////
470 /// Returns an iterator over the possibly contained value.
475 /// let x: Result<u32, &str> = Ok(7);
476 /// assert_eq!(x.iter().next(), Some(&7));
478 /// let x: Result<u32, &str> = Err("nothing!");
479 /// assert_eq!(x.iter().next(), None);
482 #[stable(feature = "rust1", since = "1.0.0")]
483 pub fn iter(&self) -> Iter
<T
> {
484 Iter { inner: self.as_ref().ok() }
487 /// Returns a mutable iterator over the possibly contained value.
492 /// let mut x: Result<u32, &str> = Ok(7);
493 /// match x.iter_mut().next() {
494 /// Some(v) => *v = 40,
497 /// assert_eq!(x, Ok(40));
499 /// let mut x: Result<u32, &str> = Err("nothing!");
500 /// assert_eq!(x.iter_mut().next(), None);
503 #[stable(feature = "rust1", since = "1.0.0")]
504 pub fn iter_mut(&mut self) -> IterMut
<T
> {
505 IterMut { inner: self.as_mut().ok() }
508 ////////////////////////////////////////////////////////////////////////
509 // Boolean operations on the values, eager and lazy
510 /////////////////////////////////////////////////////////////////////////
512 /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
517 /// let x: Result<u32, &str> = Ok(2);
518 /// let y: Result<&str, &str> = Err("late error");
519 /// assert_eq!(x.and(y), Err("late error"));
521 /// let x: Result<u32, &str> = Err("early error");
522 /// let y: Result<&str, &str> = Ok("foo");
523 /// assert_eq!(x.and(y), Err("early error"));
525 /// let x: Result<u32, &str> = Err("not a 2");
526 /// let y: Result<&str, &str> = Err("late error");
527 /// assert_eq!(x.and(y), Err("not a 2"));
529 /// let x: Result<u32, &str> = Ok(2);
530 /// let y: Result<&str, &str> = Ok("different result type");
531 /// assert_eq!(x.and(y), Ok("different result type"));
534 #[stable(feature = "rust1", since = "1.0.0")]
535 pub fn and
<U
>(self, res
: Result
<U
, E
>) -> Result
<U
, E
> {
542 /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
544 /// This function can be used for control flow based on result values.
549 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
550 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
552 /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
553 /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
554 /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
555 /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
558 #[stable(feature = "rust1", since = "1.0.0")]
559 pub fn and_then
<U
, F
: FnOnce(T
) -> Result
<U
, E
>>(self, op
: F
) -> Result
<U
, E
> {
566 /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
571 /// let x: Result<u32, &str> = Ok(2);
572 /// let y: Result<u32, &str> = Err("late error");
573 /// assert_eq!(x.or(y), Ok(2));
575 /// let x: Result<u32, &str> = Err("early error");
576 /// let y: Result<u32, &str> = Ok(2);
577 /// assert_eq!(x.or(y), Ok(2));
579 /// let x: Result<u32, &str> = Err("not a 2");
580 /// let y: Result<u32, &str> = Err("late error");
581 /// assert_eq!(x.or(y), Err("late error"));
583 /// let x: Result<u32, &str> = Ok(2);
584 /// let y: Result<u32, &str> = Ok(100);
585 /// assert_eq!(x.or(y), Ok(2));
588 #[stable(feature = "rust1", since = "1.0.0")]
589 pub fn or
<F
>(self, res
: Result
<T
, F
>) -> Result
<T
, F
> {
596 /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
598 /// This function can be used for control flow based on result values.
603 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
604 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
606 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
607 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
608 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
609 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
612 #[stable(feature = "rust1", since = "1.0.0")]
613 pub fn or_else
<F
, O
: FnOnce(E
) -> Result
<T
, F
>>(self, op
: O
) -> Result
<T
, F
> {
620 /// Unwraps a result, yielding the content of an `Ok`.
621 /// Else it returns `optb`.
627 /// let x: Result<u32, &str> = Ok(9);
628 /// assert_eq!(x.unwrap_or(optb), 9);
630 /// let x: Result<u32, &str> = Err("error");
631 /// assert_eq!(x.unwrap_or(optb), optb);
634 #[stable(feature = "rust1", since = "1.0.0")]
635 pub fn unwrap_or(self, optb
: T
) -> T
{
642 /// Unwraps a result, yielding the content of an `Ok`.
643 /// If the value is an `Err` then it calls `op` with its value.
648 /// fn count(x: &str) -> usize { x.len() }
650 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
651 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
654 #[stable(feature = "rust1", since = "1.0.0")]
655 pub fn unwrap_or_else
<F
: FnOnce(E
) -> T
>(self, op
: F
) -> T
{
663 impl<T
, E
: fmt
::Debug
> Result
<T
, E
> {
664 /// Unwraps a result, yielding the content of an `Ok`.
668 /// Panics if the value is an `Err`, with a panic message provided by the
674 /// let x: Result<u32, &str> = Ok(2);
675 /// assert_eq!(x.unwrap(), 2);
678 /// ```{.should_panic}
679 /// let x: Result<u32, &str> = Err("emergency failure");
680 /// x.unwrap(); // panics with `emergency failure`
683 #[stable(feature = "rust1", since = "1.0.0")]
684 pub fn unwrap(self) -> T
{
687 Err(e
) => unwrap_failed("called `Result::unwrap()` on an `Err` value", e
),
691 /// Unwraps a result, yielding the content of an `Ok`.
695 /// Panics if the value is an `Err`, with a panic message including the
696 /// passed message, and the content of the `Err`.
699 /// ```{.should_panic}
700 /// let x: Result<u32, &str> = Err("emergency failure");
701 /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
704 #[stable(feature = "result_expect", since = "1.4.0")]
705 pub fn expect(self, msg
: &str) -> T
{
708 Err(e
) => unwrap_failed(msg
, e
),
713 impl<T
: fmt
::Debug
, E
> Result
<T
, E
> {
714 /// Unwraps a result, yielding the content of an `Err`.
718 /// Panics if the value is an `Ok`, with a custom panic message provided
719 /// by the `Ok`'s value.
723 /// ```{.should_panic}
724 /// let x: Result<u32, &str> = Ok(2);
725 /// x.unwrap_err(); // panics with `2`
729 /// let x: Result<u32, &str> = Err("emergency failure");
730 /// assert_eq!(x.unwrap_err(), "emergency failure");
733 #[stable(feature = "rust1", since = "1.0.0")]
734 pub fn unwrap_err(self) -> E
{
736 Ok(t
) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", t
),
742 // This is a separate function to reduce the code size of the methods
745 fn unwrap_failed
<E
: fmt
::Debug
>(msg
: &str, error
: E
) -> ! {
746 panic
!("{}: {:?}", msg
, error
)
749 /////////////////////////////////////////////////////////////////////////////
750 // Trait implementations
751 /////////////////////////////////////////////////////////////////////////////
753 #[stable(feature = "rust1", since = "1.0.0")]
754 impl<T
, E
> IntoIterator
for Result
<T
, E
> {
756 type IntoIter
= IntoIter
<T
>;
758 /// Returns a consuming iterator over the possibly contained value.
763 /// let x: Result<u32, &str> = Ok(5);
764 /// let v: Vec<u32> = x.into_iter().collect();
765 /// assert_eq!(v, [5]);
767 /// let x: Result<u32, &str> = Err("nothing!");
768 /// let v: Vec<u32> = x.into_iter().collect();
769 /// assert_eq!(v, []);
772 fn into_iter(self) -> IntoIter
<T
> {
773 IntoIter { inner: self.ok() }
777 #[stable(since = "1.4.0", feature = "result_iter")]
778 impl<'a
, T
, E
> IntoIterator
for &'a Result
<T
, E
> {
780 type IntoIter
= Iter
<'a
, T
>;
782 fn into_iter(self) -> Iter
<'a
, T
> {
787 #[stable(since = "1.4.0", feature = "result_iter")]
788 impl<'a
, T
, E
> IntoIterator
for &'a
mut Result
<T
, E
> {
789 type Item
= &'a
mut T
;
790 type IntoIter
= IterMut
<'a
, T
>;
792 fn into_iter(mut self) -> IterMut
<'a
, T
> {
797 /////////////////////////////////////////////////////////////////////////////
798 // The Result Iterators
799 /////////////////////////////////////////////////////////////////////////////
801 /// An iterator over a reference to the `Ok` variant of a `Result`.
803 #[stable(feature = "rust1", since = "1.0.0")]
804 pub struct Iter
<'a
, T
: 'a
> { inner: Option<&'a T> }
806 #[stable(feature = "rust1", since = "1.0.0")]
807 impl<'a
, T
> Iterator
for Iter
<'a
, T
> {
811 fn next(&mut self) -> Option
<&'a T
> { self.inner.take() }
813 fn size_hint(&self) -> (usize, Option
<usize>) {
814 let n
= if self.inner
.is_some() {1}
else {0}
;
819 #[stable(feature = "rust1", since = "1.0.0")]
820 impl<'a
, T
> DoubleEndedIterator
for Iter
<'a
, T
> {
822 fn next_back(&mut self) -> Option
<&'a T
> { self.inner.take() }
825 #[stable(feature = "rust1", since = "1.0.0")]
826 impl<'a
, T
> ExactSizeIterator
for Iter
<'a
, T
> {}
828 #[stable(feature = "rust1", since = "1.0.0")]
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`.
835 #[stable(feature = "rust1", since = "1.0.0")]
836 pub struct IterMut
<'a
, T
: 'a
> { inner: Option<&'a mut T> }
838 #[stable(feature = "rust1", since = "1.0.0")]
839 impl<'a
, T
> Iterator
for IterMut
<'a
, T
> {
840 type Item
= &'a
mut T
;
843 fn next(&mut self) -> Option
<&'a
mut T
> { self.inner.take() }
845 fn size_hint(&self) -> (usize, Option
<usize>) {
846 let n
= if self.inner
.is_some() {1}
else {0}
;
851 #[stable(feature = "rust1", since = "1.0.0")]
852 impl<'a
, T
> DoubleEndedIterator
for IterMut
<'a
, T
> {
854 fn next_back(&mut self) -> Option
<&'a
mut T
> { self.inner.take() }
857 #[stable(feature = "rust1", since = "1.0.0")]
858 impl<'a
, T
> ExactSizeIterator
for IterMut
<'a
, T
> {}
860 /// An iterator over the value in a `Ok` variant of a `Result`.
862 #[stable(feature = "rust1", since = "1.0.0")]
863 pub struct IntoIter
<T
> { inner: Option<T> }
865 #[stable(feature = "rust1", since = "1.0.0")]
866 impl<T
> Iterator
for IntoIter
<T
> {
870 fn next(&mut self) -> Option
<T
> { self.inner.take() }
872 fn size_hint(&self) -> (usize, Option
<usize>) {
873 let n
= if self.inner
.is_some() {1}
else {0}
;
878 #[stable(feature = "rust1", since = "1.0.0")]
879 impl<T
> DoubleEndedIterator
for IntoIter
<T
> {
881 fn next_back(&mut self) -> Option
<T
> { self.inner.take() }
884 #[stable(feature = "rust1", since = "1.0.0")]
885 impl<T
> ExactSizeIterator
for IntoIter
<T
> {}
887 /////////////////////////////////////////////////////////////////////////////
889 /////////////////////////////////////////////////////////////////////////////
891 #[stable(feature = "rust1", since = "1.0.0")]
892 impl<A
, E
, V
: FromIterator
<A
>> FromIterator
<Result
<A
, E
>> for Result
<V
, E
> {
893 /// Takes each element in the `Iterator`: if it is an `Err`, no further
894 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
895 /// container with the values of each `Result` is returned.
897 /// Here is an example which increments every integer in a vector,
898 /// checking for overflow:
903 /// let v = vec!(1, 2);
904 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|&x: &u32|
905 /// if x == u32::MAX { Err("Overflow!") }
906 /// else { Ok(x + 1) }
908 /// assert!(res == Ok(vec!(2, 3)));
911 fn from_iter
<I
: IntoIterator
<Item
=Result
<A
, E
>>>(iter
: I
) -> Result
<V
, E
> {
912 // FIXME(#11084): This could be replaced with Iterator::scan when this
913 // performance bug is closed.
915 struct Adapter
<Iter
, E
> {
920 impl<T
, E
, Iter
: Iterator
<Item
=Result
<T
, E
>>> Iterator
for Adapter
<Iter
, E
> {
924 fn next(&mut self) -> Option
<T
> {
925 match self.iter
.next() {
926 Some(Ok(value
)) => Some(value
),
928 self.err
= Some(err
);
936 let mut adapter
= Adapter { iter: iter.into_iter(), err: None }
;
937 let v
: V
= FromIterator
::from_iter(adapter
.by_ref());
940 Some(err
) => Err(err
),