]> git.lizzy.rs Git - rust.git/blob - src/libcore/result.rs
Add Result::cloned{,_err} and Result::copied{,_err}
[rust.git] / src / libcore / result.rs
1 //! Error handling with the `Result` type.
2 //!
3 //! [`Result<T, E>`][`Result`] is the type used for returning and propagating
4 //! errors. It is an enum with the variants, [`Ok(T)`], representing
5 //! success and containing a value, and [`Err(E)`], representing error
6 //! and containing an error value.
7 //!
8 //! ```
9 //! # #[allow(dead_code)]
10 //! enum Result<T, E> {
11 //!    Ok(T),
12 //!    Err(E),
13 //! }
14 //! ```
15 //!
16 //! Functions return [`Result`] whenever errors are expected and
17 //! recoverable. In the `std` crate, [`Result`] is most prominently used
18 //! for [I/O](../../std/io/index.html).
19 //!
20 //! A simple function returning [`Result`] might be
21 //! defined and used like so:
22 //!
23 //! ```
24 //! #[derive(Debug)]
25 //! enum Version { Version1, Version2 }
26 //!
27 //! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
28 //!     match header.get(0) {
29 //!         None => Err("invalid header length"),
30 //!         Some(&1) => Ok(Version::Version1),
31 //!         Some(&2) => Ok(Version::Version2),
32 //!         Some(_) => Err("invalid version"),
33 //!     }
34 //! }
35 //!
36 //! let version = parse_version(&[1, 2, 3, 4]);
37 //! match version {
38 //!     Ok(v) => println!("working with version: {:?}", v),
39 //!     Err(e) => println!("error parsing header: {:?}", e),
40 //! }
41 //! ```
42 //!
43 //! Pattern matching on [`Result`]s is clear and straightforward for
44 //! simple cases, but [`Result`] comes with some convenience methods
45 //! that make working with it more succinct.
46 //!
47 //! ```
48 //! let good_result: Result<i32, i32> = Ok(10);
49 //! let bad_result: Result<i32, i32> = Err(10);
50 //!
51 //! // The `is_ok` and `is_err` methods do what they say.
52 //! assert!(good_result.is_ok() && !good_result.is_err());
53 //! assert!(bad_result.is_err() && !bad_result.is_ok());
54 //!
55 //! // `map` consumes the `Result` and produces another.
56 //! let good_result: Result<i32, i32> = good_result.map(|i| i + 1);
57 //! let bad_result: Result<i32, i32> = bad_result.map(|i| i - 1);
58 //!
59 //! // Use `and_then` to continue the computation.
60 //! let good_result: Result<bool, i32> = good_result.and_then(|i| Ok(i == 11));
61 //!
62 //! // Use `or_else` to handle the error.
63 //! let bad_result: Result<i32, i32> = bad_result.or_else(|i| Ok(i + 20));
64 //!
65 //! // Consume the result and return the contents with `unwrap`.
66 //! let final_awesome_result = good_result.unwrap();
67 //! ```
68 //!
69 //! # Results must be used
70 //!
71 //! A common problem with using return values to indicate errors is
72 //! that it is easy to ignore the return value, thus failing to handle
73 //! the error. [`Result`] is annotated with the `#[must_use]` attribute,
74 //! which will cause the compiler to issue a warning when a Result
75 //! value is ignored. This makes [`Result`] especially useful with
76 //! functions that may encounter errors but don't otherwise return a
77 //! useful value.
78 //!
79 //! Consider the [`write_all`] method defined for I/O types
80 //! by the [`Write`] trait:
81 //!
82 //! ```
83 //! use std::io;
84 //!
85 //! trait Write {
86 //!     fn write_all(&mut self, bytes: &[u8]) -> Result<(), io::Error>;
87 //! }
88 //! ```
89 //!
90 //! *Note: The actual definition of [`Write`] uses [`io::Result`], which
91 //! is just a synonym for [`Result`]`<T, `[`io::Error`]`>`.*
92 //!
93 //! This method doesn't produce a value, but the write may
94 //! fail. It's crucial to handle the error case, and *not* write
95 //! something like this:
96 //!
97 //! ```no_run
98 //! # #![allow(unused_must_use)] // \o/
99 //! use std::fs::File;
100 //! use std::io::prelude::*;
101 //!
102 //! let mut file = File::create("valuable_data.txt").unwrap();
103 //! // If `write_all` errors, then we'll never know, because the return
104 //! // value is ignored.
105 //! file.write_all(b"important message");
106 //! ```
107 //!
108 //! If you *do* write that in Rust, the compiler will give you a
109 //! warning (by default, controlled by the `unused_must_use` lint).
110 //!
111 //! You might instead, if you don't want to handle the error, simply
112 //! assert success with [`expect`]. This will panic if the
113 //! write fails, providing a marginally useful message indicating why:
114 //!
115 //! ```{.no_run}
116 //! use std::fs::File;
117 //! use std::io::prelude::*;
118 //!
119 //! let mut file = File::create("valuable_data.txt").unwrap();
120 //! file.write_all(b"important message").expect("failed to write message");
121 //! ```
122 //!
123 //! You might also simply assert success:
124 //!
125 //! ```{.no_run}
126 //! # use std::fs::File;
127 //! # use std::io::prelude::*;
128 //! # let mut file = File::create("valuable_data.txt").unwrap();
129 //! assert!(file.write_all(b"important message").is_ok());
130 //! ```
131 //!
132 //! Or propagate the error up the call stack with [`?`]:
133 //!
134 //! ```
135 //! # use std::fs::File;
136 //! # use std::io::prelude::*;
137 //! # use std::io;
138 //! # #[allow(dead_code)]
139 //! fn write_message() -> io::Result<()> {
140 //!     let mut file = File::create("valuable_data.txt")?;
141 //!     file.write_all(b"important message")?;
142 //!     Ok(())
143 //! }
144 //! ```
145 //!
146 //! # The question mark operator, `?`
147 //!
148 //! When writing code that calls many functions that return the
149 //! [`Result`] type, the error handling can be tedious. The question mark
150 //! operator, [`?`], hides some of the boilerplate of propagating errors
151 //! up the call stack.
152 //!
153 //! It replaces this:
154 //!
155 //! ```
156 //! # #![allow(dead_code)]
157 //! use std::fs::File;
158 //! use std::io::prelude::*;
159 //! use std::io;
160 //!
161 //! struct Info {
162 //!     name: String,
163 //!     age: i32,
164 //!     rating: i32,
165 //! }
166 //!
167 //! fn write_info(info: &Info) -> io::Result<()> {
168 //!     // Early return on error
169 //!     let mut file = match File::create("my_best_friends.txt") {
170 //!            Err(e) => return Err(e),
171 //!            Ok(f) => f,
172 //!     };
173 //!     if let Err(e) = file.write_all(format!("name: {}\n", info.name).as_bytes()) {
174 //!         return Err(e)
175 //!     }
176 //!     if let Err(e) = file.write_all(format!("age: {}\n", info.age).as_bytes()) {
177 //!         return Err(e)
178 //!     }
179 //!     if let Err(e) = file.write_all(format!("rating: {}\n", info.rating).as_bytes()) {
180 //!         return Err(e)
181 //!     }
182 //!     Ok(())
183 //! }
184 //! ```
185 //!
186 //! With this:
187 //!
188 //! ```
189 //! # #![allow(dead_code)]
190 //! use std::fs::File;
191 //! use std::io::prelude::*;
192 //! use std::io;
193 //!
194 //! struct Info {
195 //!     name: String,
196 //!     age: i32,
197 //!     rating: i32,
198 //! }
199 //!
200 //! fn write_info(info: &Info) -> io::Result<()> {
201 //!     let mut file = File::create("my_best_friends.txt")?;
202 //!     // Early return on error
203 //!     file.write_all(format!("name: {}\n", info.name).as_bytes())?;
204 //!     file.write_all(format!("age: {}\n", info.age).as_bytes())?;
205 //!     file.write_all(format!("rating: {}\n", info.rating).as_bytes())?;
206 //!     Ok(())
207 //! }
208 //! ```
209 //!
210 //! *It's much nicer!*
211 //!
212 //! Ending the expression with [`?`] will result in the unwrapped
213 //! success ([`Ok`]) value, unless the result is [`Err`], in which case
214 //! [`Err`] is returned early from the enclosing function.
215 //!
216 //! [`?`] can only be used in functions that return [`Result`] because of the
217 //! early return of [`Err`] that it provides.
218 //!
219 //! [`expect`]: enum.Result.html#method.expect
220 //! [`Write`]: ../../std/io/trait.Write.html
221 //! [`write_all`]: ../../std/io/trait.Write.html#method.write_all
222 //! [`io::Result`]: ../../std/io/type.Result.html
223 //! [`?`]: ../../std/macro.try.html
224 //! [`Result`]: enum.Result.html
225 //! [`Ok(T)`]: enum.Result.html#variant.Ok
226 //! [`Err(E)`]: enum.Result.html#variant.Err
227 //! [`io::Error`]: ../../std/io/struct.Error.html
228 //! [`Ok`]: enum.Result.html#variant.Ok
229 //! [`Err`]: enum.Result.html#variant.Err
230
231 #![stable(feature = "rust1", since = "1.0.0")]
232
233 use crate::fmt;
234 use crate::iter::{FromIterator, FusedIterator, TrustedLen, ResultShunt};
235 use crate::ops::{self, Deref, DerefMut};
236
237 /// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]).
238 ///
239 /// See the [`std::result`](index.html) module documentation for details.
240 ///
241 /// [`Ok`]: enum.Result.html#variant.Ok
242 /// [`Err`]: enum.Result.html#variant.Err
243 #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
244 #[must_use = "this `Result` may be an `Err` variant, which should be handled"]
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")]
249     Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
250
251     /// Contains the error value
252     #[stable(feature = "rust1", since = "1.0.0")]
253     Err(#[stable(feature = "rust1", since = "1.0.0")] E),
254 }
255
256 /////////////////////////////////////////////////////////////////////////////
257 // Type implementation
258 /////////////////////////////////////////////////////////////////////////////
259
260 impl<T, E> Result<T, E> {
261     /////////////////////////////////////////////////////////////////////////
262     // Querying the contained values
263     /////////////////////////////////////////////////////////////////////////
264
265     /// Returns `true` if the result is [`Ok`].
266     ///
267     /// [`Ok`]: enum.Result.html#variant.Ok
268     ///
269     /// # Examples
270     ///
271     /// Basic usage:
272     ///
273     /// ```
274     /// let x: Result<i32, &str> = Ok(-3);
275     /// assert_eq!(x.is_ok(), true);
276     ///
277     /// let x: Result<i32, &str> = Err("Some error message");
278     /// assert_eq!(x.is_ok(), false);
279     /// ```
280     #[must_use = "if you intended to assert that this is ok, consider `.unwrap()` instead"]
281     #[inline]
282     #[stable(feature = "rust1", since = "1.0.0")]
283     pub fn is_ok(&self) -> bool {
284         match *self {
285             Ok(_) => true,
286             Err(_) => false
287         }
288     }
289
290     /// Returns `true` if the result is [`Err`].
291     ///
292     /// [`Err`]: enum.Result.html#variant.Err
293     ///
294     /// # Examples
295     ///
296     /// Basic usage:
297     ///
298     /// ```
299     /// let x: Result<i32, &str> = Ok(-3);
300     /// assert_eq!(x.is_err(), false);
301     ///
302     /// let x: Result<i32, &str> = Err("Some error message");
303     /// assert_eq!(x.is_err(), true);
304     /// ```
305     #[must_use = "if you intended to assert that this is err, consider `.unwrap_err()` instead"]
306     #[inline]
307     #[stable(feature = "rust1", since = "1.0.0")]
308     pub fn is_err(&self) -> bool {
309         !self.is_ok()
310     }
311
312     /// Returns `true` if the result is an [`Ok`] value containing the given value.
313     ///
314     /// # Examples
315     ///
316     /// ```
317     /// #![feature(option_result_contains)]
318     ///
319     /// let x: Result<u32, &str> = Ok(2);
320     /// assert_eq!(x.contains(&2), true);
321     ///
322     /// let x: Result<u32, &str> = Ok(3);
323     /// assert_eq!(x.contains(&2), false);
324     ///
325     /// let x: Result<u32, &str> = Err("Some error message");
326     /// assert_eq!(x.contains(&2), false);
327     /// ```
328     #[must_use]
329     #[inline]
330     #[unstable(feature = "option_result_contains", issue = "62358")]
331     pub fn contains<U>(&self, x: &U) -> bool where U: PartialEq<T> {
332         match self {
333             Ok(y) => x == y,
334             Err(_) => false
335         }
336     }
337
338     /// Returns `true` if the result is an [`Err`] value containing the given value.
339     ///
340     /// # Examples
341     ///
342     /// ```
343     /// #![feature(result_contains_err)]
344     ///
345     /// let x: Result<u32, &str> = Ok(2);
346     /// assert_eq!(x.contains_err(&"Some error message"), false);
347     ///
348     /// let x: Result<u32, &str> = Err("Some error message");
349     /// assert_eq!(x.contains_err(&"Some error message"), true);
350     ///
351     /// let x: Result<u32, &str> = Err("Some other error message");
352     /// assert_eq!(x.contains_err(&"Some error message"), false);
353     /// ```
354     #[must_use]
355     #[inline]
356     #[unstable(feature = "result_contains_err", issue = "62358")]
357     pub fn contains_err<F>(&self, f: &F) -> bool where F: PartialEq<E> {
358         match self {
359             Ok(_) => false,
360             Err(e) => f == e
361         }
362     }
363
364     /////////////////////////////////////////////////////////////////////////
365     // Adapter for each variant
366     /////////////////////////////////////////////////////////////////////////
367
368     /// Converts from `Result<T, E>` to [`Option<T>`].
369     ///
370     /// Converts `self` into an [`Option<T>`], consuming `self`,
371     /// and discarding the error, if any.
372     ///
373     /// [`Option<T>`]: ../../std/option/enum.Option.html
374     ///
375     /// # Examples
376     ///
377     /// Basic usage:
378     ///
379     /// ```
380     /// let x: Result<u32, &str> = Ok(2);
381     /// assert_eq!(x.ok(), Some(2));
382     ///
383     /// let x: Result<u32, &str> = Err("Nothing here");
384     /// assert_eq!(x.ok(), None);
385     /// ```
386     #[inline]
387     #[stable(feature = "rust1", since = "1.0.0")]
388     pub fn ok(self) -> Option<T> {
389         match self {
390             Ok(x)  => Some(x),
391             Err(_) => None,
392         }
393     }
394
395     /// Converts from `Result<T, E>` to [`Option<E>`].
396     ///
397     /// Converts `self` into an [`Option<E>`], consuming `self`,
398     /// and discarding the success value, if any.
399     ///
400     /// [`Option<E>`]: ../../std/option/enum.Option.html
401     ///
402     /// # Examples
403     ///
404     /// Basic usage:
405     ///
406     /// ```
407     /// let x: Result<u32, &str> = Ok(2);
408     /// assert_eq!(x.err(), None);
409     ///
410     /// let x: Result<u32, &str> = Err("Nothing here");
411     /// assert_eq!(x.err(), Some("Nothing here"));
412     /// ```
413     #[inline]
414     #[stable(feature = "rust1", since = "1.0.0")]
415     pub fn err(self) -> Option<E> {
416         match self {
417             Ok(_)  => None,
418             Err(x) => Some(x),
419         }
420     }
421
422     /////////////////////////////////////////////////////////////////////////
423     // Adapter for working with references
424     /////////////////////////////////////////////////////////////////////////
425
426     /// Converts from `&Result<T, E>` to `Result<&T, &E>`.
427     ///
428     /// Produces a new `Result`, containing a reference
429     /// into the original, leaving the original in place.
430     ///
431     /// # Examples
432     ///
433     /// Basic usage:
434     ///
435     /// ```
436     /// let x: Result<u32, &str> = Ok(2);
437     /// assert_eq!(x.as_ref(), Ok(&2));
438     ///
439     /// let x: Result<u32, &str> = Err("Error");
440     /// assert_eq!(x.as_ref(), Err(&"Error"));
441     /// ```
442     #[inline]
443     #[stable(feature = "rust1", since = "1.0.0")]
444     pub fn as_ref(&self) -> Result<&T, &E> {
445         match *self {
446             Ok(ref x) => Ok(x),
447             Err(ref x) => Err(x),
448         }
449     }
450
451     /// Converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`.
452     ///
453     /// # Examples
454     ///
455     /// Basic usage:
456     ///
457     /// ```
458     /// fn mutate(r: &mut Result<i32, i32>) {
459     ///     match r.as_mut() {
460     ///         Ok(v) => *v = 42,
461     ///         Err(e) => *e = 0,
462     ///     }
463     /// }
464     ///
465     /// let mut x: Result<i32, i32> = Ok(2);
466     /// mutate(&mut x);
467     /// assert_eq!(x.unwrap(), 42);
468     ///
469     /// let mut x: Result<i32, i32> = Err(13);
470     /// mutate(&mut x);
471     /// assert_eq!(x.unwrap_err(), 0);
472     /// ```
473     #[inline]
474     #[stable(feature = "rust1", since = "1.0.0")]
475     pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
476         match *self {
477             Ok(ref mut x) => Ok(x),
478             Err(ref mut x) => Err(x),
479         }
480     }
481
482     /////////////////////////////////////////////////////////////////////////
483     // Transforming contained values
484     /////////////////////////////////////////////////////////////////////////
485
486     /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
487     /// contained [`Ok`] value, leaving an [`Err`] value untouched.
488     ///
489     /// This function can be used to compose the results of two functions.
490     ///
491     /// [`Ok`]: enum.Result.html#variant.Ok
492     /// [`Err`]: enum.Result.html#variant.Err
493     ///
494     /// # Examples
495     ///
496     /// Print the numbers on each line of a string multiplied by two.
497     ///
498     /// ```
499     /// let line = "1\n2\n3\n4\n";
500     ///
501     /// for num in line.lines() {
502     ///     match num.parse::<i32>().map(|i| i * 2) {
503     ///         Ok(n) => println!("{}", n),
504     ///         Err(..) => {}
505     ///     }
506     /// }
507     /// ```
508     #[inline]
509     #[stable(feature = "rust1", since = "1.0.0")]
510     pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
511         match self {
512             Ok(t) => Ok(op(t)),
513             Err(e) => Err(e)
514         }
515     }
516
517     /// Maps a `Result<T, E>` to `U` by applying a function to a
518     /// contained [`Ok`] value, or a fallback function to a
519     /// contained [`Err`] value.
520     ///
521     /// This function can be used to unpack a successful result
522     /// while handling an error.
523     ///
524     /// [`Ok`]: enum.Result.html#variant.Ok
525     /// [`Err`]: enum.Result.html#variant.Err
526     ///
527     /// # Examples
528     ///
529     /// Basic usage:
530     ///
531     /// ```
532     /// #![feature(result_map_or_else)]
533     /// let k = 21;
534     ///
535     /// let x : Result<_, &str> = Ok("foo");
536     /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);
537     ///
538     /// let x : Result<&str, _> = Err("bar");
539     /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
540     /// ```
541     #[inline]
542     #[unstable(feature = "result_map_or_else", issue = "53268")]
543     pub fn map_or_else<U, M: FnOnce(T) -> U, F: FnOnce(E) -> U>(self, fallback: F, map: M) -> U {
544         self.map(map).unwrap_or_else(fallback)
545     }
546
547     /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
548     /// contained [`Err`] value, leaving an [`Ok`] value untouched.
549     ///
550     /// This function can be used to pass through a successful result while handling
551     /// an error.
552     ///
553     /// [`Ok`]: enum.Result.html#variant.Ok
554     /// [`Err`]: enum.Result.html#variant.Err
555     ///
556     /// # Examples
557     ///
558     /// Basic usage:
559     ///
560     /// ```
561     /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
562     ///
563     /// let x: Result<u32, u32> = Ok(2);
564     /// assert_eq!(x.map_err(stringify), Ok(2));
565     ///
566     /// let x: Result<u32, u32> = Err(13);
567     /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
568     /// ```
569     #[inline]
570     #[stable(feature = "rust1", since = "1.0.0")]
571     pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> {
572         match self {
573             Ok(t) => Ok(t),
574             Err(e) => Err(op(e))
575         }
576     }
577
578     /////////////////////////////////////////////////////////////////////////
579     // Iterator constructors
580     /////////////////////////////////////////////////////////////////////////
581
582     /// Returns an iterator over the possibly contained value.
583     ///
584     /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
585     ///
586     /// # Examples
587     ///
588     /// Basic usage:
589     ///
590     /// ```
591     /// let x: Result<u32, &str> = Ok(7);
592     /// assert_eq!(x.iter().next(), Some(&7));
593     ///
594     /// let x: Result<u32, &str> = Err("nothing!");
595     /// assert_eq!(x.iter().next(), None);
596     /// ```
597     #[inline]
598     #[stable(feature = "rust1", since = "1.0.0")]
599     pub fn iter(&self) -> Iter<'_, T> {
600         Iter { inner: self.as_ref().ok() }
601     }
602
603     /// Returns a mutable iterator over the possibly contained value.
604     ///
605     /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
606     ///
607     /// # Examples
608     ///
609     /// Basic usage:
610     ///
611     /// ```
612     /// let mut x: Result<u32, &str> = Ok(7);
613     /// match x.iter_mut().next() {
614     ///     Some(v) => *v = 40,
615     ///     None => {},
616     /// }
617     /// assert_eq!(x, Ok(40));
618     ///
619     /// let mut x: Result<u32, &str> = Err("nothing!");
620     /// assert_eq!(x.iter_mut().next(), None);
621     /// ```
622     #[inline]
623     #[stable(feature = "rust1", since = "1.0.0")]
624     pub fn iter_mut(&mut self) -> IterMut<'_, T> {
625         IterMut { inner: self.as_mut().ok() }
626     }
627
628     ////////////////////////////////////////////////////////////////////////
629     // Boolean operations on the values, eager and lazy
630     /////////////////////////////////////////////////////////////////////////
631
632     /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
633     ///
634     /// [`Ok`]: enum.Result.html#variant.Ok
635     /// [`Err`]: enum.Result.html#variant.Err
636     ///
637     /// # Examples
638     ///
639     /// Basic usage:
640     ///
641     /// ```
642     /// let x: Result<u32, &str> = Ok(2);
643     /// let y: Result<&str, &str> = Err("late error");
644     /// assert_eq!(x.and(y), Err("late error"));
645     ///
646     /// let x: Result<u32, &str> = Err("early error");
647     /// let y: Result<&str, &str> = Ok("foo");
648     /// assert_eq!(x.and(y), Err("early error"));
649     ///
650     /// let x: Result<u32, &str> = Err("not a 2");
651     /// let y: Result<&str, &str> = Err("late error");
652     /// assert_eq!(x.and(y), Err("not a 2"));
653     ///
654     /// let x: Result<u32, &str> = Ok(2);
655     /// let y: Result<&str, &str> = Ok("different result type");
656     /// assert_eq!(x.and(y), Ok("different result type"));
657     /// ```
658     #[inline]
659     #[stable(feature = "rust1", since = "1.0.0")]
660     pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
661         match self {
662             Ok(_) => res,
663             Err(e) => Err(e),
664         }
665     }
666
667     /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
668     ///
669     /// [`Ok`]: enum.Result.html#variant.Ok
670     /// [`Err`]: enum.Result.html#variant.Err
671     ///
672     /// This function can be used for control flow based on `Result` values.
673     ///
674     /// # Examples
675     ///
676     /// Basic usage:
677     ///
678     /// ```
679     /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
680     /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
681     ///
682     /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
683     /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
684     /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
685     /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
686     /// ```
687     #[inline]
688     #[stable(feature = "rust1", since = "1.0.0")]
689     pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
690         match self {
691             Ok(t) => op(t),
692             Err(e) => Err(e),
693         }
694     }
695
696     /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
697     ///
698     /// Arguments passed to `or` are eagerly evaluated; if you are passing the
699     /// result of a function call, it is recommended to use [`or_else`], which is
700     /// lazily evaluated.
701     ///
702     /// [`Ok`]: enum.Result.html#variant.Ok
703     /// [`Err`]: enum.Result.html#variant.Err
704     /// [`or_else`]: #method.or_else
705     ///
706     /// # Examples
707     ///
708     /// Basic usage:
709     ///
710     /// ```
711     /// let x: Result<u32, &str> = Ok(2);
712     /// let y: Result<u32, &str> = Err("late error");
713     /// assert_eq!(x.or(y), Ok(2));
714     ///
715     /// let x: Result<u32, &str> = Err("early error");
716     /// let y: Result<u32, &str> = Ok(2);
717     /// assert_eq!(x.or(y), Ok(2));
718     ///
719     /// let x: Result<u32, &str> = Err("not a 2");
720     /// let y: Result<u32, &str> = Err("late error");
721     /// assert_eq!(x.or(y), Err("late error"));
722     ///
723     /// let x: Result<u32, &str> = Ok(2);
724     /// let y: Result<u32, &str> = Ok(100);
725     /// assert_eq!(x.or(y), Ok(2));
726     /// ```
727     #[inline]
728     #[stable(feature = "rust1", since = "1.0.0")]
729     pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
730         match self {
731             Ok(v) => Ok(v),
732             Err(_) => res,
733         }
734     }
735
736     /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
737     ///
738     /// This function can be used for control flow based on result values.
739     ///
740     /// [`Ok`]: enum.Result.html#variant.Ok
741     /// [`Err`]: enum.Result.html#variant.Err
742     ///
743     /// # Examples
744     ///
745     /// Basic usage:
746     ///
747     /// ```
748     /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
749     /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
750     ///
751     /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
752     /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
753     /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
754     /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
755     /// ```
756     #[inline]
757     #[stable(feature = "rust1", since = "1.0.0")]
758     pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
759         match self {
760             Ok(t) => Ok(t),
761             Err(e) => op(e),
762         }
763     }
764
765     /// Unwraps a result, yielding the content of an [`Ok`].
766     /// Else, it returns `optb`.
767     ///
768     /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
769     /// the result of a function call, it is recommended to use [`unwrap_or_else`],
770     /// which is lazily evaluated.
771     ///
772     /// [`Ok`]: enum.Result.html#variant.Ok
773     /// [`Err`]: enum.Result.html#variant.Err
774     /// [`unwrap_or_else`]: #method.unwrap_or_else
775     ///
776     /// # Examples
777     ///
778     /// Basic usage:
779     ///
780     /// ```
781     /// let optb = 2;
782     /// let x: Result<u32, &str> = Ok(9);
783     /// assert_eq!(x.unwrap_or(optb), 9);
784     ///
785     /// let x: Result<u32, &str> = Err("error");
786     /// assert_eq!(x.unwrap_or(optb), optb);
787     /// ```
788     #[inline]
789     #[stable(feature = "rust1", since = "1.0.0")]
790     pub fn unwrap_or(self, optb: T) -> T {
791         match self {
792             Ok(t) => t,
793             Err(_) => optb
794         }
795     }
796
797     /// Unwraps a result, yielding the content of an [`Ok`].
798     /// If the value is an [`Err`] then it calls `op` with its value.
799     ///
800     /// [`Ok`]: enum.Result.html#variant.Ok
801     /// [`Err`]: enum.Result.html#variant.Err
802     ///
803     /// # Examples
804     ///
805     /// Basic usage:
806     ///
807     /// ```
808     /// fn count(x: &str) -> usize { x.len() }
809     ///
810     /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
811     /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
812     /// ```
813     #[inline]
814     #[stable(feature = "rust1", since = "1.0.0")]
815     pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
816         match self {
817             Ok(t) => t,
818             Err(e) => op(e)
819         }
820     }
821 }
822
823 impl<T: Copy, E> Result<&T, E> {
824     /// Maps a `Result<&T, E>` to a `Result<T, E>` by copying the contents of the
825     /// `Ok` part.
826     ///
827     /// # Examples
828     ///
829     /// ```
830     /// #![feature(result_copied)]
831     /// let val = 12;
832     /// let x = Ok(&val);
833     /// assert_eq!(x, Ok(&12));
834     /// let copied = x.copied();
835     /// assert_eq!(copied, Ok(12));
836     /// ```
837     #[unstable(feature = "result_copied", reason = "newly added", issue = "XXXXX")]
838     fn copied(self) -> Result<T, E> {
839         self.map(|&t| t)
840     }
841 }
842
843 impl<T: Copy, E> Result<&mut T, E> {
844     /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by copying the contents of the
845     /// `Ok` part.
846     ///
847     /// # Examples
848     ///
849     /// ```
850     /// #![feature(result_copied)]
851     /// let val = 12;
852     /// let x = Ok(&mut val);
853     /// assert_eq!(x, Ok(&mut 12));
854     /// let copied = x.copied();
855     /// assert_eq!(copied, Ok(12));
856     /// ```
857     #[unstable(feature = "result_copied", reason = "newly added", issue = "XXXXX")]
858     fn copied(self) -> Result<T, E> {
859         self.map(|&mut t| t)
860     }
861 }
862
863 impl<T, E: Copy> Result<T, &E> {
864     /// Maps a `Result<T, &E>` to a `Result<T, E>` by copying the contents of the
865     /// `Err` part.
866     ///
867     /// # Examples
868     ///
869     /// ```
870     /// #![feature(result_copied)]
871     /// let val = 12;
872     /// let x = Err(&val);
873     /// assert_eq!(x, Err(&12));
874     /// let copied = x.copied_err();
875     /// assert_eq!(copied, Err(12));
876     /// ```
877     #[unstable(feature = "result_copied", reason = "newly added", issue = "XXXXX")]
878     fn copied_err(self) -> Result<T, E> {
879         self.map_err(|&e| e)
880     }
881 }
882
883 impl<T, E: Copy> Result<T, &mut E> {
884     /// Maps a `Result<T, &mut E>` to a `Result<T, E>` by copying the contents of the
885     /// `Err` part.
886     ///
887     /// # Examples
888     ///
889     /// ```
890     /// #![feature(result_copied)]
891     /// let val = 12;
892     /// let x = Err(&mut val);
893     /// assert_eq!(x, Err(&mut 12));
894     /// let copied = x.copied();
895     /// assert_eq!(cloned, Err(12));
896     /// ```
897     #[unstable(feature = "result_copied", reason = "newly added", issue = "XXXXX")]
898     fn copied_err(self) -> Result<T, E> {
899         self.map_err(|&mut e| e)
900     }
901 }
902
903 impl<T: Clone, E> Result<&T, E> {
904     /// Maps a `Result<&T, E>` to a `Result<T, E>` by cloning the contents of the
905     /// `Ok` part.
906     ///
907     /// # Examples
908     ///
909     /// ```
910     /// #![feature(result_cloned)]
911     /// let val = 12;
912     /// let x = Ok(&val);
913     /// assert_eq!(x, Ok(&12));
914     /// let cloned = x.cloned();
915     /// assert_eq!(cloned, Ok(12));
916     /// ```
917     #[unstable(feature = "result_cloned", reason = "newly added", issue = "XXXXX")]
918     fn cloned(self) -> Result<T, E> {
919         self.map(|t| t.clone())
920     }
921 }
922
923 impl<T: Clone, E> Result<&mut T, E> {
924     /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by cloning the contents of the
925     /// `Ok` part.
926     ///
927     /// # Examples
928     ///
929     /// ```
930     /// #![feature(result_cloned)]
931     /// let val = 12;
932     /// let x = Ok(&mut val);
933     /// assert_eq!(x, Ok(&mut 12));
934     /// let cloned = x.cloned();
935     /// assert_eq!(cloned, Ok(12));
936     /// ```
937     #[unstable(feature = "result_cloned", reason = "newly added", issue = "XXXXX")]
938     fn cloned(self) -> Result<T, E> {
939         self.map(|t| t.clone())
940     }
941 }
942
943 impl<T, E: Clone> Result<T, &mut E> {
944     /// Maps a `Result<T, &E>` to a `Result<T, E>` by cloning the contents of the
945     /// `Err` part.
946     ///
947     /// # Examples
948     ///
949     /// ```
950     /// #![feature(result_cloned)]
951     /// let val = 12;
952     /// let x = Err(&mut val);
953     /// assert_eq!(x, Err(&mut 12));
954     /// let cloned = x.cloned();
955     /// assert_eq!(cloned, Err(12));
956     /// ```
957     #[unstable(feature = "result_cloned", reason = "newly added", issue = "XXXXX")]
958     fn cloned_err(self) -> Result<T, E> {
959         self.map_err(|e| e.clone())
960     }
961 }
962
963 impl<T, E: Clone> Result<T, &mut E> {
964     /// Maps a `Result<T, &mut E>` to a `Result<T, E>` by cloning the contents of the
965     /// `Err` part.
966     ///
967     /// # Examples
968     ///
969     /// ```
970     /// #![feature(result_cloned)]
971     /// let val = 12;
972     /// let x = Err(&mut val);
973     /// assert_eq!(x, Err(&mut 12));
974     /// let cloned = x.cloned();
975     /// assert_eq!(cloned, Err(12));
976     /// ```
977     #[unstable(feature = "result_cloned", reason = "newly added", issue = "XXXXX")]
978     fn cloned_err(self) -> Result<T, E> {
979         self.map_err(|e| e.clone())
980     }
981 }
982
983 impl<T, E: fmt::Debug> Result<T, E> {
984     /// Unwraps a result, yielding the content of an [`Ok`].
985     ///
986     /// # Panics
987     ///
988     /// Panics if the value is an [`Err`], with a panic message provided by the
989     /// [`Err`]'s value.
990     ///
991     /// [`Ok`]: enum.Result.html#variant.Ok
992     /// [`Err`]: enum.Result.html#variant.Err
993     ///
994     /// # Examples
995     ///
996     /// Basic usage:
997     ///
998     /// ```
999     /// let x: Result<u32, &str> = Ok(2);
1000     /// assert_eq!(x.unwrap(), 2);
1001     /// ```
1002     ///
1003     /// ```{.should_panic}
1004     /// let x: Result<u32, &str> = Err("emergency failure");
1005     /// x.unwrap(); // panics with `emergency failure`
1006     /// ```
1007     #[inline]
1008     #[stable(feature = "rust1", since = "1.0.0")]
1009     pub fn unwrap(self) -> T {
1010         match self {
1011             Ok(t) => t,
1012             Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e),
1013         }
1014     }
1015
1016     /// Unwraps a result, yielding the content of an [`Ok`].
1017     ///
1018     /// # Panics
1019     ///
1020     /// Panics if the value is an [`Err`], with a panic message including the
1021     /// passed message, and the content of the [`Err`].
1022     ///
1023     /// [`Ok`]: enum.Result.html#variant.Ok
1024     /// [`Err`]: enum.Result.html#variant.Err
1025     ///
1026     /// # Examples
1027     ///
1028     /// Basic usage:
1029     ///
1030     /// ```{.should_panic}
1031     /// let x: Result<u32, &str> = Err("emergency failure");
1032     /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
1033     /// ```
1034     #[inline]
1035     #[stable(feature = "result_expect", since = "1.4.0")]
1036     pub fn expect(self, msg: &str) -> T {
1037         match self {
1038             Ok(t) => t,
1039             Err(e) => unwrap_failed(msg, &e),
1040         }
1041     }
1042 }
1043
1044 impl<T: fmt::Debug, E> Result<T, E> {
1045     /// Unwraps a result, yielding the content of an [`Err`].
1046     ///
1047     /// # Panics
1048     ///
1049     /// Panics if the value is an [`Ok`], with a custom panic message provided
1050     /// by the [`Ok`]'s value.
1051     ///
1052     /// [`Ok`]: enum.Result.html#variant.Ok
1053     /// [`Err`]: enum.Result.html#variant.Err
1054     ///
1055     ///
1056     /// # Examples
1057     ///
1058     /// ```{.should_panic}
1059     /// let x: Result<u32, &str> = Ok(2);
1060     /// x.unwrap_err(); // panics with `2`
1061     /// ```
1062     ///
1063     /// ```
1064     /// let x: Result<u32, &str> = Err("emergency failure");
1065     /// assert_eq!(x.unwrap_err(), "emergency failure");
1066     /// ```
1067     #[inline]
1068     #[stable(feature = "rust1", since = "1.0.0")]
1069     pub fn unwrap_err(self) -> E {
1070         match self {
1071             Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t),
1072             Err(e) => e,
1073         }
1074     }
1075
1076     /// Unwraps a result, yielding the content of an [`Err`].
1077     ///
1078     /// # Panics
1079     ///
1080     /// Panics if the value is an [`Ok`], with a panic message including the
1081     /// passed message, and the content of the [`Ok`].
1082     ///
1083     /// [`Ok`]: enum.Result.html#variant.Ok
1084     /// [`Err`]: enum.Result.html#variant.Err
1085     ///
1086     /// # Examples
1087     ///
1088     /// Basic usage:
1089     ///
1090     /// ```{.should_panic}
1091     /// let x: Result<u32, &str> = Ok(10);
1092     /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
1093     /// ```
1094     #[inline]
1095     #[stable(feature = "result_expect_err", since = "1.17.0")]
1096     pub fn expect_err(self, msg: &str) -> E {
1097         match self {
1098             Ok(t) => unwrap_failed(msg, &t),
1099             Err(e) => e,
1100         }
1101     }
1102 }
1103
1104 impl<T: Default, E> Result<T, E> {
1105     /// Returns the contained value or a default
1106     ///
1107     /// Consumes the `self` argument then, if [`Ok`], returns the contained
1108     /// value, otherwise if [`Err`], returns the default value for that
1109     /// type.
1110     ///
1111     /// # Examples
1112     ///
1113     /// Converts a string to an integer, turning poorly-formed strings
1114     /// into 0 (the default value for integers). [`parse`] converts
1115     /// a string to any other type that implements [`FromStr`], returning an
1116     /// [`Err`] on error.
1117     ///
1118     /// ```
1119     /// let good_year_from_input = "1909";
1120     /// let bad_year_from_input = "190blarg";
1121     /// let good_year = good_year_from_input.parse().unwrap_or_default();
1122     /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
1123     ///
1124     /// assert_eq!(1909, good_year);
1125     /// assert_eq!(0, bad_year);
1126     /// ```
1127     ///
1128     /// [`parse`]: ../../std/primitive.str.html#method.parse
1129     /// [`FromStr`]: ../../std/str/trait.FromStr.html
1130     /// [`Ok`]: enum.Result.html#variant.Ok
1131     /// [`Err`]: enum.Result.html#variant.Err
1132     #[inline]
1133     #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
1134     pub fn unwrap_or_default(self) -> T {
1135         match self {
1136             Ok(x) => x,
1137             Err(_) => Default::default(),
1138         }
1139     }
1140 }
1141
1142 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1143 impl<T: Deref, E> Result<T, E> {
1144     /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&T::Target, &E>`.
1145     ///
1146     /// Leaves the original `Result` in-place, creating a new one containing a reference to the
1147     /// `Ok` type's `Deref::Target` type.
1148     pub fn as_deref_ok(&self) -> Result<&T::Target, &E> {
1149         self.as_ref().map(|t| t.deref())
1150     }
1151 }
1152
1153 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1154 impl<T, E: Deref> Result<T, E> {
1155     /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&T, &E::Target>`.
1156     ///
1157     /// Leaves the original `Result` in-place, creating a new one containing a reference to the
1158     /// `Err` type's `Deref::Target` type.
1159     pub fn as_deref_err(&self) -> Result<&T, &E::Target>
1160     {
1161         self.as_ref().map_err(|e| e.deref())
1162     }
1163 }
1164
1165 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1166 impl<T: Deref, E: Deref> Result<T, E> {
1167     /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&T::Target, &E::Target>`.
1168     ///
1169     /// Leaves the original `Result` in-place, creating a new one containing a reference to both
1170     /// the `Ok` and `Err` types' `Deref::Target` types.
1171     pub fn as_deref(&self) -> Result<&T::Target, &E::Target>
1172     {
1173         self.as_ref().map(|t| t.deref()).map_err(|e| e.deref())
1174     }
1175 }
1176
1177 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1178 impl<T: DerefMut, E> Result<T, E> {
1179     /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut T::Target, &mut E>`.
1180     ///
1181     /// Leaves the original `Result` in-place, creating a new one containing a mutable reference to
1182     /// the `Ok` type's `Deref::Target` type.
1183     pub fn as_deref_mut_ok(&mut self) -> Result<&mut T::Target, &mut E> {
1184         self.as_mut().map(|t| t.deref_mut())
1185     }
1186 }
1187
1188 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1189 impl<T, E: DerefMut> Result<T, E> {
1190     /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut T, &mut E::Target>`.
1191     ///
1192     /// Leaves the original `Result` in-place, creating a new one containing a mutable reference to
1193     /// the `Err` type's `Deref::Target` type.
1194     pub fn as_deref_mut_err(&mut self) -> Result<&mut T, &mut E::Target>
1195     {
1196         self.as_mut().map_err(|e| e.deref_mut())
1197     }
1198 }
1199
1200 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1201 impl<T: DerefMut, E: DerefMut> Result<T, E> {
1202     /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to
1203     /// `Result<&mut T::Target, &mut E::Target>`.
1204     ///
1205     /// Leaves the original `Result` in-place, creating a new one containing a mutable reference to
1206     /// both the `Ok` and `Err` types' `Deref::Target` types.
1207     pub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E::Target>
1208     {
1209         self.as_mut().map(|t| t.deref_mut()).map_err(|e| e.deref_mut())
1210     }
1211 }
1212
1213 impl<T, E> Result<Option<T>, E> {
1214     /// Transposes a `Result` of an `Option` into an `Option` of a `Result`.
1215     ///
1216     /// `Ok(None)` will be mapped to `None`.
1217     /// `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`.
1218     ///
1219     /// # Examples
1220     ///
1221     /// ```
1222     /// #[derive(Debug, Eq, PartialEq)]
1223     /// struct SomeErr;
1224     ///
1225     /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1226     /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1227     /// assert_eq!(x.transpose(), y);
1228     /// ```
1229     #[inline]
1230     #[stable(feature = "transpose_result", since = "1.33.0")]
1231     pub fn transpose(self) -> Option<Result<T, E>> {
1232         match self {
1233             Ok(Some(x)) => Some(Ok(x)),
1234             Ok(None) => None,
1235             Err(e) => Some(Err(e)),
1236         }
1237     }
1238 }
1239
1240 // This is a separate function to reduce the code size of the methods
1241 #[inline(never)]
1242 #[cold]
1243 fn unwrap_failed(msg: &str, error: &dyn fmt::Debug) -> ! {
1244     panic!("{}: {:?}", msg, error)
1245 }
1246
1247 /////////////////////////////////////////////////////////////////////////////
1248 // Trait implementations
1249 /////////////////////////////////////////////////////////////////////////////
1250
1251 #[stable(feature = "rust1", since = "1.0.0")]
1252 impl<T: Clone, E: Clone> Clone for Result<T, E> {
1253     #[inline]
1254     fn clone(&self) -> Self {
1255         match self {
1256             Ok(x) => Ok(x.clone()),
1257             Err(x) => Err(x.clone()),
1258         }
1259     }
1260
1261     #[inline]
1262     fn clone_from(&mut self, source: &Self) {
1263         match (self, source) {
1264             (Ok(to), Ok(from)) => to.clone_from(from),
1265             (Err(to), Err(from)) => to.clone_from(from),
1266             (to, from) => *to = from.clone(),
1267         }
1268     }
1269 }
1270
1271
1272 #[stable(feature = "rust1", since = "1.0.0")]
1273 impl<T, E> IntoIterator for Result<T, E> {
1274     type Item = T;
1275     type IntoIter = IntoIter<T>;
1276
1277     /// Returns a consuming iterator over the possibly contained value.
1278     ///
1279     /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
1280     ///
1281     /// # Examples
1282     ///
1283     /// Basic usage:
1284     ///
1285     /// ```
1286     /// let x: Result<u32, &str> = Ok(5);
1287     /// let v: Vec<u32> = x.into_iter().collect();
1288     /// assert_eq!(v, [5]);
1289     ///
1290     /// let x: Result<u32, &str> = Err("nothing!");
1291     /// let v: Vec<u32> = x.into_iter().collect();
1292     /// assert_eq!(v, []);
1293     /// ```
1294     #[inline]
1295     fn into_iter(self) -> IntoIter<T> {
1296         IntoIter { inner: self.ok() }
1297     }
1298 }
1299
1300 #[stable(since = "1.4.0", feature = "result_iter")]
1301 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
1302     type Item = &'a T;
1303     type IntoIter = Iter<'a, T>;
1304
1305     fn into_iter(self) -> Iter<'a, T> {
1306         self.iter()
1307     }
1308 }
1309
1310 #[stable(since = "1.4.0", feature = "result_iter")]
1311 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
1312     type Item = &'a mut T;
1313     type IntoIter = IterMut<'a, T>;
1314
1315     fn into_iter(self) -> IterMut<'a, T> {
1316         self.iter_mut()
1317     }
1318 }
1319
1320 /////////////////////////////////////////////////////////////////////////////
1321 // The Result Iterators
1322 /////////////////////////////////////////////////////////////////////////////
1323
1324 /// An iterator over a reference to the [`Ok`] variant of a [`Result`].
1325 ///
1326 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1327 ///
1328 /// Created by [`Result::iter`].
1329 ///
1330 /// [`Ok`]: enum.Result.html#variant.Ok
1331 /// [`Result`]: enum.Result.html
1332 /// [`Result::iter`]: enum.Result.html#method.iter
1333 #[derive(Debug)]
1334 #[stable(feature = "rust1", since = "1.0.0")]
1335 pub struct Iter<'a, T: 'a> { inner: Option<&'a T> }
1336
1337 #[stable(feature = "rust1", since = "1.0.0")]
1338 impl<'a, T> Iterator for Iter<'a, T> {
1339     type Item = &'a T;
1340
1341     #[inline]
1342     fn next(&mut self) -> Option<&'a T> { self.inner.take() }
1343     #[inline]
1344     fn size_hint(&self) -> (usize, Option<usize>) {
1345         let n = if self.inner.is_some() {1} else {0};
1346         (n, Some(n))
1347     }
1348 }
1349
1350 #[stable(feature = "rust1", since = "1.0.0")]
1351 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1352     #[inline]
1353     fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
1354 }
1355
1356 #[stable(feature = "rust1", since = "1.0.0")]
1357 impl<T> ExactSizeIterator for Iter<'_, T> {}
1358
1359 #[stable(feature = "fused", since = "1.26.0")]
1360 impl<T> FusedIterator for Iter<'_, T> {}
1361
1362 #[unstable(feature = "trusted_len", issue = "37572")]
1363 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1364
1365 #[stable(feature = "rust1", since = "1.0.0")]
1366 impl<T> Clone for Iter<'_, T> {
1367     #[inline]
1368     fn clone(&self) -> Self { Iter { inner: self.inner } }
1369 }
1370
1371 /// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
1372 ///
1373 /// Created by [`Result::iter_mut`].
1374 ///
1375 /// [`Ok`]: enum.Result.html#variant.Ok
1376 /// [`Result`]: enum.Result.html
1377 /// [`Result::iter_mut`]: enum.Result.html#method.iter_mut
1378 #[derive(Debug)]
1379 #[stable(feature = "rust1", since = "1.0.0")]
1380 pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
1381
1382 #[stable(feature = "rust1", since = "1.0.0")]
1383 impl<'a, T> Iterator for IterMut<'a, T> {
1384     type Item = &'a mut T;
1385
1386     #[inline]
1387     fn next(&mut self) -> Option<&'a mut T> { self.inner.take() }
1388     #[inline]
1389     fn size_hint(&self) -> (usize, Option<usize>) {
1390         let n = if self.inner.is_some() {1} else {0};
1391         (n, Some(n))
1392     }
1393 }
1394
1395 #[stable(feature = "rust1", since = "1.0.0")]
1396 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1397     #[inline]
1398     fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
1399 }
1400
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 impl<T> ExactSizeIterator for IterMut<'_, T> {}
1403
1404 #[stable(feature = "fused", since = "1.26.0")]
1405 impl<T> FusedIterator for IterMut<'_, T> {}
1406
1407 #[unstable(feature = "trusted_len", issue = "37572")]
1408 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1409
1410 /// An iterator over the value in a [`Ok`] variant of a [`Result`].
1411 ///
1412 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1413 ///
1414 /// This struct is created by the [`into_iter`] method on
1415 /// [`Result`][`Result`] (provided by the [`IntoIterator`] trait).
1416 ///
1417 /// [`Ok`]: enum.Result.html#variant.Ok
1418 /// [`Result`]: enum.Result.html
1419 /// [`into_iter`]: ../iter/trait.IntoIterator.html#tymethod.into_iter
1420 /// [`IntoIterator`]: ../iter/trait.IntoIterator.html
1421 #[derive(Clone, Debug)]
1422 #[stable(feature = "rust1", since = "1.0.0")]
1423 pub struct IntoIter<T> { inner: Option<T> }
1424
1425 #[stable(feature = "rust1", since = "1.0.0")]
1426 impl<T> Iterator for IntoIter<T> {
1427     type Item = T;
1428
1429     #[inline]
1430     fn next(&mut self) -> Option<T> { self.inner.take() }
1431     #[inline]
1432     fn size_hint(&self) -> (usize, Option<usize>) {
1433         let n = if self.inner.is_some() {1} else {0};
1434         (n, Some(n))
1435     }
1436 }
1437
1438 #[stable(feature = "rust1", since = "1.0.0")]
1439 impl<T> DoubleEndedIterator for IntoIter<T> {
1440     #[inline]
1441     fn next_back(&mut self) -> Option<T> { self.inner.take() }
1442 }
1443
1444 #[stable(feature = "rust1", since = "1.0.0")]
1445 impl<T> ExactSizeIterator for IntoIter<T> {}
1446
1447 #[stable(feature = "fused", since = "1.26.0")]
1448 impl<T> FusedIterator for IntoIter<T> {}
1449
1450 #[unstable(feature = "trusted_len", issue = "37572")]
1451 unsafe impl<A> TrustedLen for IntoIter<A> {}
1452
1453 /////////////////////////////////////////////////////////////////////////////
1454 // FromIterator
1455 /////////////////////////////////////////////////////////////////////////////
1456
1457 #[stable(feature = "rust1", since = "1.0.0")]
1458 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
1459     /// Takes each element in the `Iterator`: if it is an `Err`, no further
1460     /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
1461     /// container with the values of each `Result` is returned.
1462     ///
1463     /// Here is an example which increments every integer in a vector,
1464     /// checking for overflow:
1465     ///
1466     /// ```
1467     /// let v = vec![1, 2];
1468     /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1469     ///     x.checked_add(1).ok_or("Overflow!")
1470     /// ).collect();
1471     /// assert_eq!(res, Ok(vec![2, 3]));
1472     /// ```
1473     ///
1474     /// Here is another example that tries to subtract one from another list
1475     /// of integers, this time checking for underflow:
1476     ///
1477     /// ```
1478     /// let v = vec![1, 2, 0];
1479     /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1480     ///     x.checked_sub(1).ok_or("Underflow!")
1481     /// ).collect();
1482     /// assert_eq!(res, Err("Underflow!"));
1483     /// ```
1484     ///
1485     /// Here is a variation on the previous example, showing that no
1486     /// further elements are taken from `iter` after the first `Err`.
1487     ///
1488     /// ```
1489     /// let v = vec![3, 2, 1, 10];
1490     /// let mut shared = 0;
1491     /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {
1492     ///     shared += x;
1493     ///     x.checked_sub(2).ok_or("Underflow!")
1494     /// }).collect();
1495     /// assert_eq!(res, Err("Underflow!"));
1496     /// assert_eq!(shared, 6);
1497     /// ```
1498     ///
1499     /// Since the third element caused an underflow, no further elements were taken,
1500     /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1501     #[inline]
1502     fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
1503         // FIXME(#11084): This could be replaced with Iterator::scan when this
1504         // performance bug is closed.
1505
1506         ResultShunt::process(iter.into_iter(), |i| i.collect())
1507     }
1508 }
1509
1510 #[unstable(feature = "try_trait", issue = "42327")]
1511 impl<T,E> ops::Try for Result<T, E> {
1512     type Ok = T;
1513     type Error = E;
1514
1515     #[inline]
1516     fn into_result(self) -> Self {
1517         self
1518     }
1519
1520     #[inline]
1521     fn from_ok(v: T) -> Self {
1522         Ok(v)
1523     }
1524
1525     #[inline]
1526     fn from_error(v: E) -> Self {
1527         Err(v)
1528     }
1529 }