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 //! panic, by converting to an `Option` with `ok`, then asserting
121 //! success with `expect`. This will panic if the write fails, proving
122 //! a marginally useful message indicating why:
125 //! use std::fs::File;
126 //! use std::io::prelude::*;
128 //! let mut file = File::create("valuable_data.txt").unwrap();
129 //! file.write_all(b"important message").ok().expect("failed to write message");
132 //! You might also simply assert success:
135 //! # use std::fs::File;
136 //! # use std::io::prelude::*;
137 //! # let mut file = File::create("valuable_data.txt").unwrap();
138 //! assert!(file.write_all(b"important message").is_ok());
141 //! Or propagate the error up the call stack with `try!`:
144 //! # use std::fs::File;
145 //! # use std::io::prelude::*;
147 //! fn write_message() -> io::Result<()> {
148 //! let mut file = try!(File::create("valuable_data.txt"));
149 //! try!(file.write_all(b"important message"));
154 //! # The `try!` macro
156 //! When writing code that calls many functions that return the
157 //! `Result` type, the error handling can be tedious. The `try!`
158 //! macro hides some of the boilerplate of propagating errors up the
161 //! It replaces this:
164 //! use std::fs::File;
165 //! use std::io::prelude::*;
174 //! fn write_info(info: &Info) -> io::Result<()> {
175 //! let mut file = try!(File::create("my_best_friends.txt"));
176 //! // Early return on error
177 //! if let Err(e) = file.write_all(format!("name: {}\n", info.name).as_bytes()) {
180 //! if let Err(e) = file.write_all(format!("age: {}\n", info.age).as_bytes()) {
183 //! if let Err(e) = file.write_all(format!("rating: {}\n", info.rating).as_bytes()) {
193 //! use std::fs::File;
194 //! use std::io::prelude::*;
203 //! fn write_info(info: &Info) -> io::Result<()> {
204 //! let mut file = try!(File::create("my_best_friends.txt"));
205 //! // Early return on error
206 //! try!(file.write_all(format!("name: {}\n", info.name).as_bytes()));
207 //! try!(file.write_all(format!("age: {}\n", info.age).as_bytes()));
208 //! try!(file.write_all(format!("rating: {}\n", info.rating).as_bytes()));
213 //! *It's much nicer!*
215 //! Wrapping an expression in `try!` will result in the unwrapped
216 //! success (`Ok`) value, unless the result is `Err`, in which case
217 //! `Err` is returned early from the enclosing function. Its simple definition
221 //! macro_rules! try {
222 //! ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
226 //! `try!` is imported by the prelude, and is available everywhere.
228 #![stable(feature = "rust1", since = "1.0.0")]
230 use self::Result
::{Ok, Err}
;
234 use iter
::{Iterator, DoubleEndedIterator, FromIterator, ExactSizeIterator, IntoIterator}
;
235 use ops
::{FnMut, FnOnce}
;
236 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<i32, &str> = Ok(-3);
271 /// assert_eq!(x.is_ok(), true);
273 /// let x: Result<i32, &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<i32, &str> = Ok(-3);
291 /// assert_eq!(x.is_err(), false);
293 /// let x: Result<i32, &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 /// Converts 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<u32, &str> = Ok(2);
315 /// assert_eq!(x.ok(), Some(2));
317 /// let x: Result<u32, &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 /// Converts from `Result<T, E>` to `Option<E>`
331 /// Converts `self` into an `Option<E>`, consuming `self`,
332 /// and discarding the success value, if any.
337 /// let x: Result<u32, &str> = Ok(2);
338 /// assert_eq!(x.err(), None);
340 /// let x: Result<u32, &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 /// Converts 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<u32, &str> = Ok(2);
363 /// assert_eq!(x.as_ref(), Ok(&2));
365 /// let x: Result<u32, &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 /// Converts from `Result<T, E>` to `Result<&mut T, &mut E>`
380 /// fn mutate(r: &mut Result<i32, i32>) {
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<i32, i32> = Ok(2);
389 /// assert_eq!(x.unwrap(), 42);
391 /// let mut x: Result<i32, i32> = 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 /// Converts from `Result<T, E>` to `&[T]` (without copying)
406 #[unstable(feature = "as_slice", since = "unsure of the utility here")]
407 pub fn as_slice(&self) -> &[T
] {
409 Ok(ref x
) => slice
::ref_slice(x
),
411 // work around lack of implicit coercion from fixed-size array to slice
418 /// Converts from `Result<T, E>` to `&mut [T]` (without copying)
421 /// # #![feature(core)]
422 /// let mut x: Result<&str, u32> = Ok("Gold");
424 /// let v = x.as_mut_slice();
425 /// assert!(v == ["Gold"]);
427 /// assert!(v == ["Silver"]);
429 /// assert_eq!(x, Ok("Silver"));
431 /// let mut x: Result<&str, u32> = Err(45);
432 /// assert!(x.as_mut_slice().is_empty());
435 #[unstable(feature = "core",
436 reason
= "waiting for mut conventions")]
437 pub fn as_mut_slice(&mut self) -> &mut [T
] {
439 Ok(ref mut x
) => slice
::mut_ref_slice(x
),
441 // work around lack of implicit coercion from fixed-size array to slice
442 let emp
: &mut [_
] = &mut [];
448 /////////////////////////////////////////////////////////////////////////
449 // Transforming contained values
450 /////////////////////////////////////////////////////////////////////////
452 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to an
453 /// contained `Ok` value, leaving an `Err` value untouched.
455 /// This function can be used to compose the results of two functions.
459 /// Print the numbers on each line of a string multiplied by two.
462 /// let line = "1\n2\n3\n4\n";
464 /// for num in line.lines() {
465 /// match num.parse::<i32>().map(|i| i * 2) {
466 /// Ok(n) => println!("{}", n),
472 #[stable(feature = "rust1", since = "1.0.0")]
473 pub fn map
<U
, F
: FnOnce(T
) -> U
>(self, op
: F
) -> Result
<U
,E
> {
480 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to an
481 /// contained `Err` value, leaving an `Ok` value untouched.
483 /// This function can be used to pass through a successful result while handling
489 /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
491 /// let x: Result<u32, u32> = Ok(2);
492 /// assert_eq!(x.map_err(stringify), Ok(2));
494 /// let x: Result<u32, u32> = Err(13);
495 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
498 #[stable(feature = "rust1", since = "1.0.0")]
499 pub fn map_err
<F
, O
: FnOnce(E
) -> F
>(self, op
: O
) -> Result
<T
,F
> {
506 /////////////////////////////////////////////////////////////////////////
507 // Iterator constructors
508 /////////////////////////////////////////////////////////////////////////
510 /// Returns an iterator over the possibly contained value.
515 /// let x: Result<u32, &str> = Ok(7);
516 /// assert_eq!(x.iter().next(), Some(&7));
518 /// let x: Result<u32, &str> = Err("nothing!");
519 /// assert_eq!(x.iter().next(), None);
522 #[stable(feature = "rust1", since = "1.0.0")]
523 pub fn iter(&self) -> Iter
<T
> {
524 Iter { inner: self.as_ref().ok() }
527 /// Returns a mutable iterator over the possibly contained value.
532 /// let mut x: Result<u32, &str> = Ok(7);
533 /// match x.iter_mut().next() {
534 /// Some(&mut ref mut x) => *x = 40,
537 /// assert_eq!(x, Ok(40));
539 /// let mut x: Result<u32, &str> = Err("nothing!");
540 /// assert_eq!(x.iter_mut().next(), None);
543 #[stable(feature = "rust1", since = "1.0.0")]
544 pub fn iter_mut(&mut self) -> IterMut
<T
> {
545 IterMut { inner: self.as_mut().ok() }
548 ////////////////////////////////////////////////////////////////////////
549 // Boolean operations on the values, eager and lazy
550 /////////////////////////////////////////////////////////////////////////
552 /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
557 /// let x: Result<u32, &str> = Ok(2);
558 /// let y: Result<&str, &str> = Err("late error");
559 /// assert_eq!(x.and(y), Err("late error"));
561 /// let x: Result<u32, &str> = Err("early error");
562 /// let y: Result<&str, &str> = Ok("foo");
563 /// assert_eq!(x.and(y), Err("early error"));
565 /// let x: Result<u32, &str> = Err("not a 2");
566 /// let y: Result<&str, &str> = Err("late error");
567 /// assert_eq!(x.and(y), Err("not a 2"));
569 /// let x: Result<u32, &str> = Ok(2);
570 /// let y: Result<&str, &str> = Ok("different result type");
571 /// assert_eq!(x.and(y), Ok("different result type"));
574 #[stable(feature = "rust1", since = "1.0.0")]
575 pub fn and
<U
>(self, res
: Result
<U
, E
>) -> Result
<U
, E
> {
582 /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
584 /// This function can be used for control flow based on result values.
589 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
590 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
592 /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
593 /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
594 /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
595 /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
598 #[stable(feature = "rust1", since = "1.0.0")]
599 pub fn and_then
<U
, F
: FnOnce(T
) -> Result
<U
, E
>>(self, op
: F
) -> Result
<U
, E
> {
606 /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
611 /// let x: Result<u32, &str> = Ok(2);
612 /// let y: Result<u32, &str> = Err("late error");
613 /// assert_eq!(x.or(y), Ok(2));
615 /// let x: Result<u32, &str> = Err("early error");
616 /// let y: Result<u32, &str> = Ok(2);
617 /// assert_eq!(x.or(y), Ok(2));
619 /// let x: Result<u32, &str> = Err("not a 2");
620 /// let y: Result<u32, &str> = Err("late error");
621 /// assert_eq!(x.or(y), Err("late error"));
623 /// let x: Result<u32, &str> = Ok(2);
624 /// let y: Result<u32, &str> = Ok(100);
625 /// assert_eq!(x.or(y), Ok(2));
628 #[stable(feature = "rust1", since = "1.0.0")]
629 pub fn or
<F
>(self, res
: Result
<T
, F
>) -> Result
<T
, F
> {
636 /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
638 /// This function can be used for control flow based on result values.
643 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
644 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
646 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
647 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
648 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
649 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
652 #[stable(feature = "rust1", since = "1.0.0")]
653 pub fn or_else
<F
, O
: FnOnce(E
) -> Result
<T
, F
>>(self, op
: O
) -> Result
<T
, F
> {
660 /// Unwraps a result, yielding the content of an `Ok`.
661 /// Else it returns `optb`.
667 /// let x: Result<u32, &str> = Ok(9);
668 /// assert_eq!(x.unwrap_or(optb), 9);
670 /// let x: Result<u32, &str> = Err("error");
671 /// assert_eq!(x.unwrap_or(optb), optb);
674 #[stable(feature = "rust1", since = "1.0.0")]
675 pub fn unwrap_or(self, optb
: T
) -> T
{
682 /// Unwraps a result, yielding the content of an `Ok`.
683 /// If the value is an `Err` then it calls `op` with its value.
688 /// fn count(x: &str) -> usize { x.len() }
690 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
691 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
694 #[stable(feature = "rust1", since = "1.0.0")]
695 pub fn unwrap_or_else
<F
: FnOnce(E
) -> T
>(self, op
: F
) -> T
{
703 #[stable(feature = "rust1", since = "1.0.0")]
704 impl<T
, E
: fmt
::Debug
> Result
<T
, E
> {
705 /// Unwraps a result, yielding the content of an `Ok`.
709 /// Panics if the value is an `Err`, with a panic message provided by the
715 /// let x: Result<u32, &str> = Ok(2);
716 /// assert_eq!(x.unwrap(), 2);
719 /// ```{.should_panic}
720 /// let x: Result<u32, &str> = Err("emergency failure");
721 /// x.unwrap(); // panics with `emergency failure`
724 #[stable(feature = "rust1", since = "1.0.0")]
725 pub fn unwrap(self) -> T
{
729 panic
!("called `Result::unwrap()` on an `Err` value: {:?}", e
)
734 #[stable(feature = "rust1", since = "1.0.0")]
735 impl<T
: fmt
::Debug
, E
> Result
<T
, E
> {
736 /// Unwraps a result, yielding the content of an `Err`.
740 /// Panics if the value is an `Ok`, with a custom panic message provided
741 /// by the `Ok`'s value.
745 /// ```{.should_panic}
746 /// let x: Result<u32, &str> = Ok(2);
747 /// x.unwrap_err(); // panics with `2`
751 /// let x: Result<u32, &str> = Err("emergency failure");
752 /// assert_eq!(x.unwrap_err(), "emergency failure");
755 #[stable(feature = "rust1", since = "1.0.0")]
756 pub fn unwrap_err(self) -> E
{
759 panic
!("called `Result::unwrap_err()` on an `Ok` value: {:?}", t
),
765 /////////////////////////////////////////////////////////////////////////////
766 // Trait implementations
767 /////////////////////////////////////////////////////////////////////////////
769 #[stable(feature = "rust1", since = "1.0.0")]
770 impl<T
, E
> IntoIterator
for Result
<T
, E
> {
772 type IntoIter
= IntoIter
<T
>;
774 /// Returns a consuming iterator over the possibly contained value.
779 /// let x: Result<u32, &str> = Ok(5);
780 /// let v: Vec<u32> = x.into_iter().collect();
781 /// assert_eq!(v, [5]);
783 /// let x: Result<u32, &str> = Err("nothing!");
784 /// let v: Vec<u32> = x.into_iter().collect();
785 /// assert_eq!(v, []);
788 fn into_iter(self) -> IntoIter
<T
> {
789 IntoIter { inner: self.ok() }
793 /////////////////////////////////////////////////////////////////////////////
794 // The Result Iterators
795 /////////////////////////////////////////////////////////////////////////////
797 /// An iterator over a reference to the `Ok` variant of a `Result`.
798 #[stable(feature = "rust1", since = "1.0.0")]
799 pub struct Iter
<'a
, T
: 'a
> { inner: Option<&'a T> }
801 #[stable(feature = "rust1", since = "1.0.0")]
802 impl<'a
, T
> Iterator
for Iter
<'a
, T
> {
806 fn next(&mut self) -> Option
<&'a T
> { self.inner.take() }
808 fn size_hint(&self) -> (usize, Option
<usize>) {
809 let n
= if self.inner
.is_some() {1}
else {0}
;
814 #[stable(feature = "rust1", since = "1.0.0")]
815 impl<'a
, T
> DoubleEndedIterator
for Iter
<'a
, T
> {
817 fn next_back(&mut self) -> Option
<&'a T
> { self.inner.take() }
820 #[stable(feature = "rust1", since = "1.0.0")]
821 impl<'a
, T
> ExactSizeIterator
for Iter
<'a
, T
> {}
823 impl<'a
, T
> Clone
for Iter
<'a
, T
> {
824 fn clone(&self) -> Iter
<'a
, T
> { Iter { inner: self.inner }
}
827 /// An iterator over a mutable reference to the `Ok` variant of a `Result`.
828 #[stable(feature = "rust1", since = "1.0.0")]
829 pub struct IterMut
<'a
, T
: 'a
> { inner: Option<&'a mut T> }
831 #[stable(feature = "rust1", since = "1.0.0")]
832 impl<'a
, T
> Iterator
for IterMut
<'a
, T
> {
833 type Item
= &'a
mut T
;
836 fn next(&mut self) -> Option
<&'a
mut T
> { self.inner.take() }
838 fn size_hint(&self) -> (usize, Option
<usize>) {
839 let n
= if self.inner
.is_some() {1}
else {0}
;
844 #[stable(feature = "rust1", since = "1.0.0")]
845 impl<'a
, T
> DoubleEndedIterator
for IterMut
<'a
, T
> {
847 fn next_back(&mut self) -> Option
<&'a
mut T
> { self.inner.take() }
850 #[stable(feature = "rust1", since = "1.0.0")]
851 impl<'a
, T
> ExactSizeIterator
for IterMut
<'a
, T
> {}
853 /// An iterator over the value in a `Ok` variant of a `Result`.
854 #[stable(feature = "rust1", since = "1.0.0")]
855 pub struct IntoIter
<T
> { inner: Option<T> }
857 #[stable(feature = "rust1", since = "1.0.0")]
858 impl<T
> Iterator
for IntoIter
<T
> {
862 fn next(&mut self) -> Option
<T
> { self.inner.take() }
864 fn size_hint(&self) -> (usize, Option
<usize>) {
865 let n
= if self.inner
.is_some() {1}
else {0}
;
870 #[stable(feature = "rust1", since = "1.0.0")]
871 impl<T
> DoubleEndedIterator
for IntoIter
<T
> {
873 fn next_back(&mut self) -> Option
<T
> { self.inner.take() }
876 #[stable(feature = "rust1", since = "1.0.0")]
877 impl<T
> ExactSizeIterator
for IntoIter
<T
> {}
879 /////////////////////////////////////////////////////////////////////////////
881 /////////////////////////////////////////////////////////////////////////////
883 #[stable(feature = "rust1", since = "1.0.0")]
884 impl<A
, E
, V
: FromIterator
<A
>> FromIterator
<Result
<A
, E
>> for Result
<V
, E
> {
885 /// Takes each element in the `Iterator`: if it is an `Err`, no further
886 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
887 /// container with the values of each `Result` is returned.
889 /// Here is an example which increments every integer in a vector,
890 /// checking for overflow:
895 /// let v = vec!(1, 2);
896 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|&x: &u32|
897 /// if x == u32::MAX { Err("Overflow!") }
898 /// else { Ok(x + 1) }
900 /// assert!(res == Ok(vec!(2, 3)));
903 fn from_iter
<I
: IntoIterator
<Item
=Result
<A
, E
>>>(iter
: I
) -> Result
<V
, E
> {
904 // FIXME(#11084): This could be replaced with Iterator::scan when this
905 // performance bug is closed.
907 struct Adapter
<Iter
, E
> {
912 impl<T
, E
, Iter
: Iterator
<Item
=Result
<T
, E
>>> Iterator
for Adapter
<Iter
, E
> {
916 fn next(&mut self) -> Option
<T
> {
917 match self.iter
.next() {
918 Some(Ok(value
)) => Some(value
),
920 self.err
= Some(err
);
928 let mut adapter
= Adapter { iter: iter.into_iter(), err: None }
;
929 let v
: V
= FromIterator
::from_iter(adapter
.by_ref());
932 Some(err
) => Err(err
),
938 /////////////////////////////////////////////////////////////////////////////
940 /////////////////////////////////////////////////////////////////////////////
942 /// Performs a fold operation over the result values from an iterator.
944 /// If an `Err` is encountered, it is immediately returned.
945 /// Otherwise, the folded value is returned.
947 #[unstable(feature = "core")]
952 Iter
: Iterator
<Item
=Result
<T
, E
>>>(
959 Ok(v
) => init
= f(init
, v
),
960 Err(u
) => return Err(u
)