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, but it can only
227 //! be used in functions that return `Result` because of the early return of
228 //! `Err` that it provides.
230 #![stable(feature = "rust1", since = "1.0.0")]
232 use self::Result::{Ok, Err};
236 use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSizeIterator, IntoIterator};
238 use option::Option::{self, None, Some};
241 /// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
243 /// See the [`std::result`](index.html) module documentation for details.
244 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
246 #[stable(feature = "rust1", since = "1.0.0")]
247 pub enum Result<T, E> {
248 /// Contains the success value
249 #[stable(feature = "rust1", since = "1.0.0")]
252 /// Contains the error value
253 #[stable(feature = "rust1", since = "1.0.0")]
257 /////////////////////////////////////////////////////////////////////////////
258 // Type implementation
259 /////////////////////////////////////////////////////////////////////////////
261 #[stable(feature = "rust1", since = "1.0.0")]
262 impl<T, E> Result<T, E> {
263 /////////////////////////////////////////////////////////////////////////
264 // Querying the contained values
265 /////////////////////////////////////////////////////////////////////////
267 /// Returns true if the result is `Ok`
272 /// let x: Result<i32, &str> = Ok(-3);
273 /// assert_eq!(x.is_ok(), true);
275 /// let x: Result<i32, &str> = Err("Some error message");
276 /// assert_eq!(x.is_ok(), false);
279 #[stable(feature = "rust1", since = "1.0.0")]
280 pub fn is_ok(&self) -> bool {
287 /// Returns true if the result is `Err`
292 /// let x: Result<i32, &str> = Ok(-3);
293 /// assert_eq!(x.is_err(), false);
295 /// let x: Result<i32, &str> = Err("Some error message");
296 /// assert_eq!(x.is_err(), true);
299 #[stable(feature = "rust1", since = "1.0.0")]
300 pub fn is_err(&self) -> bool {
304 /////////////////////////////////////////////////////////////////////////
305 // Adapter for each variant
306 /////////////////////////////////////////////////////////////////////////
308 /// Converts from `Result<T, E>` to `Option<T>`
310 /// Converts `self` into an `Option<T>`, consuming `self`,
311 /// and discarding the error, if any.
316 /// let x: Result<u32, &str> = Ok(2);
317 /// assert_eq!(x.ok(), Some(2));
319 /// let x: Result<u32, &str> = Err("Nothing here");
320 /// assert_eq!(x.ok(), None);
323 #[stable(feature = "rust1", since = "1.0.0")]
324 pub fn ok(self) -> Option<T> {
331 /// Converts from `Result<T, E>` to `Option<E>`
333 /// Converts `self` into an `Option<E>`, consuming `self`,
334 /// and discarding the success value, if any.
339 /// let x: Result<u32, &str> = Ok(2);
340 /// assert_eq!(x.err(), None);
342 /// let x: Result<u32, &str> = Err("Nothing here");
343 /// assert_eq!(x.err(), Some("Nothing here"));
346 #[stable(feature = "rust1", since = "1.0.0")]
347 pub fn err(self) -> Option<E> {
354 /////////////////////////////////////////////////////////////////////////
355 // Adapter for working with references
356 /////////////////////////////////////////////////////////////////////////
358 /// Converts from `Result<T, E>` to `Result<&T, &E>`
360 /// Produces a new `Result`, containing a reference
361 /// into the original, leaving the original in place.
364 /// let x: Result<u32, &str> = Ok(2);
365 /// assert_eq!(x.as_ref(), Ok(&2));
367 /// let x: Result<u32, &str> = Err("Error");
368 /// assert_eq!(x.as_ref(), Err(&"Error"));
371 #[stable(feature = "rust1", since = "1.0.0")]
372 pub fn as_ref(&self) -> Result<&T, &E> {
375 Err(ref x) => Err(x),
379 /// Converts from `Result<T, E>` to `Result<&mut T, &mut E>`
382 /// fn mutate(r: &mut Result<i32, i32>) {
383 /// match r.as_mut() {
384 /// Ok(&mut ref mut v) => *v = 42,
385 /// Err(&mut ref mut e) => *e = 0,
389 /// let mut x: Result<i32, i32> = Ok(2);
391 /// assert_eq!(x.unwrap(), 42);
393 /// let mut x: Result<i32, i32> = Err(13);
395 /// assert_eq!(x.unwrap_err(), 0);
398 #[stable(feature = "rust1", since = "1.0.0")]
399 pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
401 Ok(ref mut x) => Ok(x),
402 Err(ref mut x) => Err(x),
406 /// Converts from `Result<T, E>` to `&[T]` (without copying)
408 #[unstable(feature = "as_slice", reason = "unsure of the utility here",
410 #[deprecated(since = "1.4.0", reason = "niche API, unclear of usefulness")]
412 pub fn as_slice(&self) -> &[T] {
414 Ok(ref x) => slice::ref_slice(x),
416 // work around lack of implicit coercion from fixed-size array to slice
423 /// Converts from `Result<T, E>` to `&mut [T]` (without copying)
426 /// #![feature(as_slice)]
428 /// let mut x: Result<&str, u32> = Ok("Gold");
430 /// let v = x.as_mut_slice();
431 /// assert!(v == ["Gold"]);
433 /// assert!(v == ["Silver"]);
435 /// assert_eq!(x, Ok("Silver"));
437 /// let mut x: Result<&str, u32> = Err(45);
438 /// assert!(x.as_mut_slice().is_empty());
441 #[unstable(feature = "as_slice",
442 reason = "waiting for mut conventions",
444 #[deprecated(since = "1.4.0", reason = "niche API, unclear of usefulness")]
446 pub fn as_mut_slice(&mut self) -> &mut [T] {
448 Ok(ref mut x) => slice::mut_ref_slice(x),
450 // work around lack of implicit coercion from fixed-size array to slice
451 let emp: &mut [_] = &mut [];
457 /////////////////////////////////////////////////////////////////////////
458 // Transforming contained values
459 /////////////////////////////////////////////////////////////////////////
461 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to an
462 /// contained `Ok` value, leaving an `Err` value untouched.
464 /// This function can be used to compose the results of two functions.
468 /// Print the numbers on each line of a string multiplied by two.
471 /// let line = "1\n2\n3\n4\n";
473 /// for num in line.lines() {
474 /// match num.parse::<i32>().map(|i| i * 2) {
475 /// Ok(n) => println!("{}", n),
481 #[stable(feature = "rust1", since = "1.0.0")]
482 pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
489 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to an
490 /// contained `Err` value, leaving an `Ok` value untouched.
492 /// This function can be used to pass through a successful result while handling
498 /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
500 /// let x: Result<u32, u32> = Ok(2);
501 /// assert_eq!(x.map_err(stringify), Ok(2));
503 /// let x: Result<u32, u32> = Err(13);
504 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
507 #[stable(feature = "rust1", since = "1.0.0")]
508 pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> {
515 /////////////////////////////////////////////////////////////////////////
516 // Iterator constructors
517 /////////////////////////////////////////////////////////////////////////
519 /// Returns an iterator over the possibly contained value.
524 /// let x: Result<u32, &str> = Ok(7);
525 /// assert_eq!(x.iter().next(), Some(&7));
527 /// let x: Result<u32, &str> = Err("nothing!");
528 /// assert_eq!(x.iter().next(), None);
531 #[stable(feature = "rust1", since = "1.0.0")]
532 pub fn iter(&self) -> Iter<T> {
533 Iter { inner: self.as_ref().ok() }
536 /// Returns a mutable iterator over the possibly contained value.
541 /// let mut x: Result<u32, &str> = Ok(7);
542 /// match x.iter_mut().next() {
543 /// Some(v) => *v = 40,
546 /// assert_eq!(x, Ok(40));
548 /// let mut x: Result<u32, &str> = Err("nothing!");
549 /// assert_eq!(x.iter_mut().next(), None);
552 #[stable(feature = "rust1", since = "1.0.0")]
553 pub fn iter_mut(&mut self) -> IterMut<T> {
554 IterMut { inner: self.as_mut().ok() }
557 ////////////////////////////////////////////////////////////////////////
558 // Boolean operations on the values, eager and lazy
559 /////////////////////////////////////////////////////////////////////////
561 /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
566 /// let x: Result<u32, &str> = Ok(2);
567 /// let y: Result<&str, &str> = Err("late error");
568 /// assert_eq!(x.and(y), Err("late error"));
570 /// let x: Result<u32, &str> = Err("early error");
571 /// let y: Result<&str, &str> = Ok("foo");
572 /// assert_eq!(x.and(y), Err("early error"));
574 /// let x: Result<u32, &str> = Err("not a 2");
575 /// let y: Result<&str, &str> = Err("late error");
576 /// assert_eq!(x.and(y), Err("not a 2"));
578 /// let x: Result<u32, &str> = Ok(2);
579 /// let y: Result<&str, &str> = Ok("different result type");
580 /// assert_eq!(x.and(y), Ok("different result type"));
583 #[stable(feature = "rust1", since = "1.0.0")]
584 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
591 /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
593 /// This function can be used for control flow based on result values.
598 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
599 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
601 /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
602 /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
603 /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
604 /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
607 #[stable(feature = "rust1", since = "1.0.0")]
608 pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
615 /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
620 /// let x: Result<u32, &str> = Ok(2);
621 /// let y: Result<u32, &str> = Err("late error");
622 /// assert_eq!(x.or(y), Ok(2));
624 /// let x: Result<u32, &str> = Err("early error");
625 /// let y: Result<u32, &str> = Ok(2);
626 /// assert_eq!(x.or(y), Ok(2));
628 /// let x: Result<u32, &str> = Err("not a 2");
629 /// let y: Result<u32, &str> = Err("late error");
630 /// assert_eq!(x.or(y), Err("late error"));
632 /// let x: Result<u32, &str> = Ok(2);
633 /// let y: Result<u32, &str> = Ok(100);
634 /// assert_eq!(x.or(y), Ok(2));
637 #[stable(feature = "rust1", since = "1.0.0")]
638 pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
645 /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
647 /// This function can be used for control flow based on result values.
652 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
653 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
655 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
656 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
657 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
658 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
661 #[stable(feature = "rust1", since = "1.0.0")]
662 pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
669 /// Unwraps a result, yielding the content of an `Ok`.
670 /// Else it returns `optb`.
676 /// let x: Result<u32, &str> = Ok(9);
677 /// assert_eq!(x.unwrap_or(optb), 9);
679 /// let x: Result<u32, &str> = Err("error");
680 /// assert_eq!(x.unwrap_or(optb), optb);
683 #[stable(feature = "rust1", since = "1.0.0")]
684 pub fn unwrap_or(self, optb: T) -> T {
691 /// Unwraps a result, yielding the content of an `Ok`.
692 /// If the value is an `Err` then it calls `op` with its value.
697 /// fn count(x: &str) -> usize { x.len() }
699 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
700 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
703 #[stable(feature = "rust1", since = "1.0.0")]
704 pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
712 #[stable(feature = "rust1", since = "1.0.0")]
713 impl<T, E: fmt::Debug> Result<T, E> {
714 /// Unwraps a result, yielding the content of an `Ok`.
718 /// Panics if the value is an `Err`, with a panic message provided by the
724 /// let x: Result<u32, &str> = Ok(2);
725 /// assert_eq!(x.unwrap(), 2);
728 /// ```{.should_panic}
729 /// let x: Result<u32, &str> = Err("emergency failure");
730 /// x.unwrap(); // panics with `emergency failure`
733 #[stable(feature = "rust1", since = "1.0.0")]
734 pub fn unwrap(self) -> T {
738 panic!("called `Result::unwrap()` on an `Err` value: {:?}", e)
742 /// Unwraps a result, yielding the content of an `Ok`.
744 /// Panics if the value is an `Err`, with a panic message including the
745 /// passed message, and the content of the `Err`.
748 /// ```{.should_panic}
749 /// let x: Result<u32, &str> = Err("emergency failure");
750 /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
753 #[stable(feature = "result_expect", since = "1.4.0")]
754 pub fn expect(self, msg: &str) -> T {
757 Err(e) => panic!("{}: {:?}", msg, e),
762 #[stable(feature = "rust1", since = "1.0.0")]
763 impl<T: fmt::Debug, E> Result<T, E> {
764 /// Unwraps a result, yielding the content of an `Err`.
768 /// Panics if the value is an `Ok`, with a custom panic message provided
769 /// by the `Ok`'s value.
773 /// ```{.should_panic}
774 /// let x: Result<u32, &str> = Ok(2);
775 /// x.unwrap_err(); // panics with `2`
779 /// let x: Result<u32, &str> = Err("emergency failure");
780 /// assert_eq!(x.unwrap_err(), "emergency failure");
783 #[stable(feature = "rust1", since = "1.0.0")]
784 pub fn unwrap_err(self) -> E {
787 panic!("called `Result::unwrap_err()` on an `Ok` value: {:?}", t),
793 /////////////////////////////////////////////////////////////////////////////
794 // Trait implementations
795 /////////////////////////////////////////////////////////////////////////////
797 #[stable(feature = "rust1", since = "1.0.0")]
798 impl<T, E> IntoIterator for Result<T, E> {
800 type IntoIter = IntoIter<T>;
802 /// Returns a consuming iterator over the possibly contained value.
807 /// let x: Result<u32, &str> = Ok(5);
808 /// let v: Vec<u32> = x.into_iter().collect();
809 /// assert_eq!(v, [5]);
811 /// let x: Result<u32, &str> = Err("nothing!");
812 /// let v: Vec<u32> = x.into_iter().collect();
813 /// assert_eq!(v, []);
816 fn into_iter(self) -> IntoIter<T> {
817 IntoIter { inner: self.ok() }
821 #[stable(since = "1.4.0", feature = "result_iter")]
822 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
824 type IntoIter = Iter<'a, T>;
826 fn into_iter(self) -> Iter<'a, T> {
831 #[stable(since = "1.4.0", feature = "result_iter")]
832 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
833 type Item = &'a mut T;
834 type IntoIter = IterMut<'a, T>;
836 fn into_iter(mut self) -> IterMut<'a, T> {
841 /////////////////////////////////////////////////////////////////////////////
842 // The Result Iterators
843 /////////////////////////////////////////////////////////////////////////////
845 /// An iterator over a reference to the `Ok` variant of a `Result`.
846 #[stable(feature = "rust1", since = "1.0.0")]
847 pub struct Iter<'a, T: 'a> { inner: Option<&'a T> }
849 #[stable(feature = "rust1", since = "1.0.0")]
850 impl<'a, T> Iterator for Iter<'a, T> {
854 fn next(&mut self) -> Option<&'a T> { self.inner.take() }
856 fn size_hint(&self) -> (usize, Option<usize>) {
857 let n = if self.inner.is_some() {1} else {0};
862 #[stable(feature = "rust1", since = "1.0.0")]
863 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
865 fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
868 #[stable(feature = "rust1", since = "1.0.0")]
869 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
871 impl<'a, T> Clone for Iter<'a, T> {
872 fn clone(&self) -> Iter<'a, T> { Iter { inner: self.inner } }
875 /// An iterator over a mutable reference to the `Ok` variant of a `Result`.
876 #[stable(feature = "rust1", since = "1.0.0")]
877 pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
879 #[stable(feature = "rust1", since = "1.0.0")]
880 impl<'a, T> Iterator for IterMut<'a, T> {
881 type Item = &'a mut T;
884 fn next(&mut self) -> Option<&'a mut T> { self.inner.take() }
886 fn size_hint(&self) -> (usize, Option<usize>) {
887 let n = if self.inner.is_some() {1} else {0};
892 #[stable(feature = "rust1", since = "1.0.0")]
893 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
895 fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
898 #[stable(feature = "rust1", since = "1.0.0")]
899 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
901 /// An iterator over the value in a `Ok` variant of a `Result`.
902 #[stable(feature = "rust1", since = "1.0.0")]
903 pub struct IntoIter<T> { inner: Option<T> }
905 #[stable(feature = "rust1", since = "1.0.0")]
906 impl<T> Iterator for IntoIter<T> {
910 fn next(&mut self) -> Option<T> { self.inner.take() }
912 fn size_hint(&self) -> (usize, Option<usize>) {
913 let n = if self.inner.is_some() {1} else {0};
918 #[stable(feature = "rust1", since = "1.0.0")]
919 impl<T> DoubleEndedIterator for IntoIter<T> {
921 fn next_back(&mut self) -> Option<T> { self.inner.take() }
924 #[stable(feature = "rust1", since = "1.0.0")]
925 impl<T> ExactSizeIterator for IntoIter<T> {}
927 /////////////////////////////////////////////////////////////////////////////
929 /////////////////////////////////////////////////////////////////////////////
931 #[stable(feature = "rust1", since = "1.0.0")]
932 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
933 /// Takes each element in the `Iterator`: if it is an `Err`, no further
934 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
935 /// container with the values of each `Result` is returned.
937 /// Here is an example which increments every integer in a vector,
938 /// checking for overflow:
943 /// let v = vec!(1, 2);
944 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|&x: &u32|
945 /// if x == u32::MAX { Err("Overflow!") }
946 /// else { Ok(x + 1) }
948 /// assert!(res == Ok(vec!(2, 3)));
951 fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
952 // FIXME(#11084): This could be replaced with Iterator::scan when this
953 // performance bug is closed.
955 struct Adapter<Iter, E> {
960 impl<T, E, Iter: Iterator<Item=Result<T, E>>> Iterator for Adapter<Iter, E> {
964 fn next(&mut self) -> Option<T> {
965 match self.iter.next() {
966 Some(Ok(value)) => Some(value),
968 self.err = Some(err);
976 let mut adapter = Adapter { iter: iter.into_iter(), err: None };
977 let v: V = FromIterator::from_iter(adapter.by_ref());
980 Some(err) => Err(err),