]> git.lizzy.rs Git - rust.git/blob - src/libcore/result.rs
Add some type-alias-impl-trait regression tests
[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::{self, FromIterator, FusedIterator, TrustedLen};
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     #[rustc_const_unstable(feature = "const_result", issue = "67520")]
282     #[inline]
283     #[stable(feature = "rust1", since = "1.0.0")]
284     pub const fn is_ok(&self) -> bool {
285         matches!(*self, Ok(_))
286     }
287
288     /// Returns `true` if the result is [`Err`].
289     ///
290     /// [`Err`]: enum.Result.html#variant.Err
291     ///
292     /// # Examples
293     ///
294     /// Basic usage:
295     ///
296     /// ```
297     /// let x: Result<i32, &str> = Ok(-3);
298     /// assert_eq!(x.is_err(), false);
299     ///
300     /// let x: Result<i32, &str> = Err("Some error message");
301     /// assert_eq!(x.is_err(), true);
302     /// ```
303     #[must_use = "if you intended to assert that this is err, consider `.unwrap_err()` instead"]
304     #[rustc_const_unstable(feature = "const_result", issue = "67520")]
305     #[inline]
306     #[stable(feature = "rust1", since = "1.0.0")]
307     pub const fn is_err(&self) -> bool {
308         !self.is_ok()
309     }
310
311     /// Returns `true` if the result is an [`Ok`] value containing the given value.
312     ///
313     /// # Examples
314     ///
315     /// ```
316     /// #![feature(option_result_contains)]
317     ///
318     /// let x: Result<u32, &str> = Ok(2);
319     /// assert_eq!(x.contains(&2), true);
320     ///
321     /// let x: Result<u32, &str> = Ok(3);
322     /// assert_eq!(x.contains(&2), false);
323     ///
324     /// let x: Result<u32, &str> = Err("Some error message");
325     /// assert_eq!(x.contains(&2), false);
326     /// ```
327     #[must_use]
328     #[inline]
329     #[unstable(feature = "option_result_contains", issue = "62358")]
330     pub fn contains<U>(&self, x: &U) -> bool
331     where
332         U: PartialEq<T>,
333     {
334         match self {
335             Ok(y) => x == y,
336             Err(_) => false,
337         }
338     }
339
340     /// Returns `true` if the result is an [`Err`] value containing the given value.
341     ///
342     /// # Examples
343     ///
344     /// ```
345     /// #![feature(result_contains_err)]
346     ///
347     /// let x: Result<u32, &str> = Ok(2);
348     /// assert_eq!(x.contains_err(&"Some error message"), false);
349     ///
350     /// let x: Result<u32, &str> = Err("Some error message");
351     /// assert_eq!(x.contains_err(&"Some error message"), true);
352     ///
353     /// let x: Result<u32, &str> = Err("Some other error message");
354     /// assert_eq!(x.contains_err(&"Some error message"), false);
355     /// ```
356     #[must_use]
357     #[inline]
358     #[unstable(feature = "result_contains_err", issue = "62358")]
359     pub fn contains_err<F>(&self, f: &F) -> bool
360     where
361         F: PartialEq<E>,
362     {
363         match self {
364             Ok(_) => false,
365             Err(e) => f == e,
366         }
367     }
368
369     /////////////////////////////////////////////////////////////////////////
370     // Adapter for each variant
371     /////////////////////////////////////////////////////////////////////////
372
373     /// Converts from `Result<T, E>` to [`Option<T>`].
374     ///
375     /// Converts `self` into an [`Option<T>`], consuming `self`,
376     /// and discarding the error, if any.
377     ///
378     /// [`Option<T>`]: ../../std/option/enum.Option.html
379     ///
380     /// # Examples
381     ///
382     /// Basic usage:
383     ///
384     /// ```
385     /// let x: Result<u32, &str> = Ok(2);
386     /// assert_eq!(x.ok(), Some(2));
387     ///
388     /// let x: Result<u32, &str> = Err("Nothing here");
389     /// assert_eq!(x.ok(), None);
390     /// ```
391     #[inline]
392     #[stable(feature = "rust1", since = "1.0.0")]
393     pub fn ok(self) -> Option<T> {
394         match self {
395             Ok(x) => Some(x),
396             Err(_) => None,
397         }
398     }
399
400     /// Converts from `Result<T, E>` to [`Option<E>`].
401     ///
402     /// Converts `self` into an [`Option<E>`], consuming `self`,
403     /// and discarding the success value, if any.
404     ///
405     /// [`Option<E>`]: ../../std/option/enum.Option.html
406     ///
407     /// # Examples
408     ///
409     /// Basic usage:
410     ///
411     /// ```
412     /// let x: Result<u32, &str> = Ok(2);
413     /// assert_eq!(x.err(), None);
414     ///
415     /// let x: Result<u32, &str> = Err("Nothing here");
416     /// assert_eq!(x.err(), Some("Nothing here"));
417     /// ```
418     #[inline]
419     #[stable(feature = "rust1", since = "1.0.0")]
420     pub fn err(self) -> Option<E> {
421         match self {
422             Ok(_) => None,
423             Err(x) => Some(x),
424         }
425     }
426
427     /////////////////////////////////////////////////////////////////////////
428     // Adapter for working with references
429     /////////////////////////////////////////////////////////////////////////
430
431     /// Converts from `&Result<T, E>` to `Result<&T, &E>`.
432     ///
433     /// Produces a new `Result`, containing a reference
434     /// into the original, leaving the original in place.
435     ///
436     /// # Examples
437     ///
438     /// Basic usage:
439     ///
440     /// ```
441     /// let x: Result<u32, &str> = Ok(2);
442     /// assert_eq!(x.as_ref(), Ok(&2));
443     ///
444     /// let x: Result<u32, &str> = Err("Error");
445     /// assert_eq!(x.as_ref(), Err(&"Error"));
446     /// ```
447     #[inline]
448     #[rustc_const_unstable(feature = "const_result", issue = "67520")]
449     #[stable(feature = "rust1", since = "1.0.0")]
450     pub const fn as_ref(&self) -> Result<&T, &E> {
451         match *self {
452             Ok(ref x) => Ok(x),
453             Err(ref x) => Err(x),
454         }
455     }
456
457     /// Converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`.
458     ///
459     /// # Examples
460     ///
461     /// Basic usage:
462     ///
463     /// ```
464     /// fn mutate(r: &mut Result<i32, i32>) {
465     ///     match r.as_mut() {
466     ///         Ok(v) => *v = 42,
467     ///         Err(e) => *e = 0,
468     ///     }
469     /// }
470     ///
471     /// let mut x: Result<i32, i32> = Ok(2);
472     /// mutate(&mut x);
473     /// assert_eq!(x.unwrap(), 42);
474     ///
475     /// let mut x: Result<i32, i32> = Err(13);
476     /// mutate(&mut x);
477     /// assert_eq!(x.unwrap_err(), 0);
478     /// ```
479     #[inline]
480     #[stable(feature = "rust1", since = "1.0.0")]
481     pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
482         match *self {
483             Ok(ref mut x) => Ok(x),
484             Err(ref mut x) => Err(x),
485         }
486     }
487
488     /////////////////////////////////////////////////////////////////////////
489     // Transforming contained values
490     /////////////////////////////////////////////////////////////////////////
491
492     /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
493     /// contained [`Ok`] value, leaving an [`Err`] value untouched.
494     ///
495     /// This function can be used to compose the results of two functions.
496     ///
497     /// [`Ok`]: enum.Result.html#variant.Ok
498     /// [`Err`]: enum.Result.html#variant.Err
499     ///
500     /// # Examples
501     ///
502     /// Print the numbers on each line of a string multiplied by two.
503     ///
504     /// ```
505     /// let line = "1\n2\n3\n4\n";
506     ///
507     /// for num in line.lines() {
508     ///     match num.parse::<i32>().map(|i| i * 2) {
509     ///         Ok(n) => println!("{}", n),
510     ///         Err(..) => {}
511     ///     }
512     /// }
513     /// ```
514     #[inline]
515     #[stable(feature = "rust1", since = "1.0.0")]
516     pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U, E> {
517         match self {
518             Ok(t) => Ok(op(t)),
519             Err(e) => Err(e),
520         }
521     }
522
523     /// Applies a function to the contained value (if any),
524     /// or returns the provided default (if not).
525     ///
526     /// # Examples
527     ///
528     /// ```
529     /// let x: Result<_, &str> = Ok("foo");
530     /// assert_eq!(x.map_or(42, |v| v.len()), 3);
531     ///
532     /// let x: Result<&str, _> = Err("bar");
533     /// assert_eq!(x.map_or(42, |v| v.len()), 42);
534     /// ```
535     #[inline]
536     #[stable(feature = "result_map_or", since = "1.41.0")]
537     pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
538         match self {
539             Ok(t) => f(t),
540             Err(_) => default,
541         }
542     }
543
544     /// Maps a `Result<T, E>` to `U` by applying a function to a
545     /// contained [`Ok`] value, or a fallback function to a
546     /// contained [`Err`] value.
547     ///
548     /// This function can be used to unpack a successful result
549     /// while handling an error.
550     ///
551     /// [`Ok`]: enum.Result.html#variant.Ok
552     /// [`Err`]: enum.Result.html#variant.Err
553     ///
554     /// # Examples
555     ///
556     /// Basic usage:
557     ///
558     /// ```
559     /// let k = 21;
560     ///
561     /// let x : Result<_, &str> = Ok("foo");
562     /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);
563     ///
564     /// let x : Result<&str, _> = Err("bar");
565     /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
566     /// ```
567     #[inline]
568     #[stable(feature = "result_map_or_else", since = "1.41.0")]
569     pub fn map_or_else<U, D: FnOnce(E) -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
570         match self {
571             Ok(t) => f(t),
572             Err(e) => default(e),
573         }
574     }
575
576     /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
577     /// contained [`Err`] value, leaving an [`Ok`] value untouched.
578     ///
579     /// This function can be used to pass through a successful result while handling
580     /// an error.
581     ///
582     /// [`Ok`]: enum.Result.html#variant.Ok
583     /// [`Err`]: enum.Result.html#variant.Err
584     ///
585     /// # Examples
586     ///
587     /// Basic usage:
588     ///
589     /// ```
590     /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
591     ///
592     /// let x: Result<u32, u32> = Ok(2);
593     /// assert_eq!(x.map_err(stringify), Ok(2));
594     ///
595     /// let x: Result<u32, u32> = Err(13);
596     /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
597     /// ```
598     #[inline]
599     #[stable(feature = "rust1", since = "1.0.0")]
600     pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T, F> {
601         match self {
602             Ok(t) => Ok(t),
603             Err(e) => Err(op(e)),
604         }
605     }
606
607     /////////////////////////////////////////////////////////////////////////
608     // Iterator constructors
609     /////////////////////////////////////////////////////////////////////////
610
611     /// Returns an iterator over the possibly contained value.
612     ///
613     /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
614     ///
615     /// # Examples
616     ///
617     /// Basic usage:
618     ///
619     /// ```
620     /// let x: Result<u32, &str> = Ok(7);
621     /// assert_eq!(x.iter().next(), Some(&7));
622     ///
623     /// let x: Result<u32, &str> = Err("nothing!");
624     /// assert_eq!(x.iter().next(), None);
625     /// ```
626     #[inline]
627     #[stable(feature = "rust1", since = "1.0.0")]
628     pub fn iter(&self) -> Iter<'_, T> {
629         Iter { inner: self.as_ref().ok() }
630     }
631
632     /// Returns a mutable iterator over the possibly contained value.
633     ///
634     /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
635     ///
636     /// # Examples
637     ///
638     /// Basic usage:
639     ///
640     /// ```
641     /// let mut x: Result<u32, &str> = Ok(7);
642     /// match x.iter_mut().next() {
643     ///     Some(v) => *v = 40,
644     ///     None => {},
645     /// }
646     /// assert_eq!(x, Ok(40));
647     ///
648     /// let mut x: Result<u32, &str> = Err("nothing!");
649     /// assert_eq!(x.iter_mut().next(), None);
650     /// ```
651     #[inline]
652     #[stable(feature = "rust1", since = "1.0.0")]
653     pub fn iter_mut(&mut self) -> IterMut<'_, T> {
654         IterMut { inner: self.as_mut().ok() }
655     }
656
657     ////////////////////////////////////////////////////////////////////////
658     // Boolean operations on the values, eager and lazy
659     /////////////////////////////////////////////////////////////////////////
660
661     /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
662     ///
663     /// [`Ok`]: enum.Result.html#variant.Ok
664     /// [`Err`]: enum.Result.html#variant.Err
665     ///
666     /// # Examples
667     ///
668     /// Basic usage:
669     ///
670     /// ```
671     /// let x: Result<u32, &str> = Ok(2);
672     /// let y: Result<&str, &str> = Err("late error");
673     /// assert_eq!(x.and(y), Err("late error"));
674     ///
675     /// let x: Result<u32, &str> = Err("early error");
676     /// let y: Result<&str, &str> = Ok("foo");
677     /// assert_eq!(x.and(y), Err("early error"));
678     ///
679     /// let x: Result<u32, &str> = Err("not a 2");
680     /// let y: Result<&str, &str> = Err("late error");
681     /// assert_eq!(x.and(y), Err("not a 2"));
682     ///
683     /// let x: Result<u32, &str> = Ok(2);
684     /// let y: Result<&str, &str> = Ok("different result type");
685     /// assert_eq!(x.and(y), Ok("different result type"));
686     /// ```
687     #[inline]
688     #[stable(feature = "rust1", since = "1.0.0")]
689     pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
690         match self {
691             Ok(_) => res,
692             Err(e) => Err(e),
693         }
694     }
695
696     /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
697     ///
698     /// [`Ok`]: enum.Result.html#variant.Ok
699     /// [`Err`]: enum.Result.html#variant.Err
700     ///
701     /// This function can be used for control flow based on `Result` values.
702     ///
703     /// # Examples
704     ///
705     /// Basic usage:
706     ///
707     /// ```
708     /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
709     /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
710     ///
711     /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
712     /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
713     /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
714     /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
715     /// ```
716     #[inline]
717     #[stable(feature = "rust1", since = "1.0.0")]
718     pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
719         match self {
720             Ok(t) => op(t),
721             Err(e) => Err(e),
722         }
723     }
724
725     /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
726     ///
727     /// Arguments passed to `or` are eagerly evaluated; if you are passing the
728     /// result of a function call, it is recommended to use [`or_else`], which is
729     /// lazily evaluated.
730     ///
731     /// [`Ok`]: enum.Result.html#variant.Ok
732     /// [`Err`]: enum.Result.html#variant.Err
733     /// [`or_else`]: #method.or_else
734     ///
735     /// # Examples
736     ///
737     /// Basic usage:
738     ///
739     /// ```
740     /// let x: Result<u32, &str> = Ok(2);
741     /// let y: Result<u32, &str> = Err("late error");
742     /// assert_eq!(x.or(y), Ok(2));
743     ///
744     /// let x: Result<u32, &str> = Err("early error");
745     /// let y: Result<u32, &str> = Ok(2);
746     /// assert_eq!(x.or(y), Ok(2));
747     ///
748     /// let x: Result<u32, &str> = Err("not a 2");
749     /// let y: Result<u32, &str> = Err("late error");
750     /// assert_eq!(x.or(y), Err("late error"));
751     ///
752     /// let x: Result<u32, &str> = Ok(2);
753     /// let y: Result<u32, &str> = Ok(100);
754     /// assert_eq!(x.or(y), Ok(2));
755     /// ```
756     #[inline]
757     #[stable(feature = "rust1", since = "1.0.0")]
758     pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
759         match self {
760             Ok(v) => Ok(v),
761             Err(_) => res,
762         }
763     }
764
765     /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
766     ///
767     /// This function can be used for control flow based on result values.
768     ///
769     /// [`Ok`]: enum.Result.html#variant.Ok
770     /// [`Err`]: enum.Result.html#variant.Err
771     ///
772     /// # Examples
773     ///
774     /// Basic usage:
775     ///
776     /// ```
777     /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
778     /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
779     ///
780     /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
781     /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
782     /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
783     /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
784     /// ```
785     #[inline]
786     #[stable(feature = "rust1", since = "1.0.0")]
787     pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
788         match self {
789             Ok(t) => Ok(t),
790             Err(e) => op(e),
791         }
792     }
793
794     /// Unwraps a result, yielding the content of an [`Ok`].
795     /// Else, it returns `optb`.
796     ///
797     /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
798     /// the result of a function call, it is recommended to use [`unwrap_or_else`],
799     /// which is lazily evaluated.
800     ///
801     /// [`Ok`]: enum.Result.html#variant.Ok
802     /// [`Err`]: enum.Result.html#variant.Err
803     /// [`unwrap_or_else`]: #method.unwrap_or_else
804     ///
805     /// # Examples
806     ///
807     /// Basic usage:
808     ///
809     /// ```
810     /// let optb = 2;
811     /// let x: Result<u32, &str> = Ok(9);
812     /// assert_eq!(x.unwrap_or(optb), 9);
813     ///
814     /// let x: Result<u32, &str> = Err("error");
815     /// assert_eq!(x.unwrap_or(optb), optb);
816     /// ```
817     #[inline]
818     #[stable(feature = "rust1", since = "1.0.0")]
819     pub fn unwrap_or(self, optb: T) -> T {
820         match self {
821             Ok(t) => t,
822             Err(_) => optb,
823         }
824     }
825
826     /// Unwraps a result, yielding the content of an [`Ok`].
827     /// If the value is an [`Err`] then it calls `op` with its value.
828     ///
829     /// [`Ok`]: enum.Result.html#variant.Ok
830     /// [`Err`]: enum.Result.html#variant.Err
831     ///
832     /// # Examples
833     ///
834     /// Basic usage:
835     ///
836     /// ```
837     /// fn count(x: &str) -> usize { x.len() }
838     ///
839     /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
840     /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
841     /// ```
842     #[inline]
843     #[stable(feature = "rust1", since = "1.0.0")]
844     pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
845         match self {
846             Ok(t) => t,
847             Err(e) => op(e),
848         }
849     }
850 }
851
852 impl<T: Copy, E> Result<&T, E> {
853     /// Maps a `Result<&T, E>` to a `Result<T, E>` by copying the contents of the
854     /// `Ok` part.
855     ///
856     /// # Examples
857     ///
858     /// ```
859     /// #![feature(result_copied)]
860     /// let val = 12;
861     /// let x: Result<&i32, i32> = Ok(&val);
862     /// assert_eq!(x, Ok(&12));
863     /// let copied = x.copied();
864     /// assert_eq!(copied, Ok(12));
865     /// ```
866     #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
867     pub fn copied(self) -> Result<T, E> {
868         self.map(|&t| t)
869     }
870 }
871
872 impl<T: Copy, E> Result<&mut T, E> {
873     /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by copying the contents of the
874     /// `Ok` part.
875     ///
876     /// # Examples
877     ///
878     /// ```
879     /// #![feature(result_copied)]
880     /// let mut val = 12;
881     /// let x: Result<&mut i32, i32> = Ok(&mut val);
882     /// assert_eq!(x, Ok(&mut 12));
883     /// let copied = x.copied();
884     /// assert_eq!(copied, Ok(12));
885     /// ```
886     #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
887     pub fn copied(self) -> Result<T, E> {
888         self.map(|&mut t| t)
889     }
890 }
891
892 impl<T: Clone, E> Result<&T, E> {
893     /// Maps a `Result<&T, E>` to a `Result<T, E>` by cloning the contents of the
894     /// `Ok` part.
895     ///
896     /// # Examples
897     ///
898     /// ```
899     /// #![feature(result_cloned)]
900     /// let val = 12;
901     /// let x: Result<&i32, i32> = Ok(&val);
902     /// assert_eq!(x, Ok(&12));
903     /// let cloned = x.cloned();
904     /// assert_eq!(cloned, Ok(12));
905     /// ```
906     #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
907     pub fn cloned(self) -> Result<T, E> {
908         self.map(|t| t.clone())
909     }
910 }
911
912 impl<T: Clone, E> Result<&mut T, E> {
913     /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by cloning the contents of the
914     /// `Ok` part.
915     ///
916     /// # Examples
917     ///
918     /// ```
919     /// #![feature(result_cloned)]
920     /// let mut val = 12;
921     /// let x: Result<&mut i32, i32> = Ok(&mut val);
922     /// assert_eq!(x, Ok(&mut 12));
923     /// let cloned = x.cloned();
924     /// assert_eq!(cloned, Ok(12));
925     /// ```
926     #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
927     pub fn cloned(self) -> Result<T, E> {
928         self.map(|t| t.clone())
929     }
930 }
931
932 impl<T, E: fmt::Debug> Result<T, E> {
933     /// Unwraps a result, yielding the content of an [`Ok`].
934     ///
935     /// # Panics
936     ///
937     /// Panics if the value is an [`Err`], with a panic message provided by the
938     /// [`Err`]'s value.
939     ///
940     /// [`Ok`]: enum.Result.html#variant.Ok
941     /// [`Err`]: enum.Result.html#variant.Err
942     ///
943     /// # Examples
944     ///
945     /// Basic usage:
946     ///
947     /// ```
948     /// let x: Result<u32, &str> = Ok(2);
949     /// assert_eq!(x.unwrap(), 2);
950     /// ```
951     ///
952     /// ```{.should_panic}
953     /// let x: Result<u32, &str> = Err("emergency failure");
954     /// x.unwrap(); // panics with `emergency failure`
955     /// ```
956     #[inline]
957     #[track_caller]
958     #[stable(feature = "rust1", since = "1.0.0")]
959     pub fn unwrap(self) -> T {
960         match self {
961             Ok(t) => t,
962             Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e),
963         }
964     }
965
966     /// Unwraps a result, yielding the content of an [`Ok`].
967     ///
968     /// # Panics
969     ///
970     /// Panics if the value is an [`Err`], with a panic message including the
971     /// passed message, and the content of the [`Err`].
972     ///
973     /// [`Ok`]: enum.Result.html#variant.Ok
974     /// [`Err`]: enum.Result.html#variant.Err
975     ///
976     /// # Examples
977     ///
978     /// Basic usage:
979     ///
980     /// ```{.should_panic}
981     /// let x: Result<u32, &str> = Err("emergency failure");
982     /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
983     /// ```
984     #[inline]
985     #[track_caller]
986     #[stable(feature = "result_expect", since = "1.4.0")]
987     pub fn expect(self, msg: &str) -> T {
988         match self {
989             Ok(t) => t,
990             Err(e) => unwrap_failed(msg, &e),
991         }
992     }
993 }
994
995 impl<T: fmt::Debug, E> Result<T, E> {
996     /// Unwraps a result, yielding the content of an [`Err`].
997     ///
998     /// # Panics
999     ///
1000     /// Panics if the value is an [`Ok`], with a custom panic message provided
1001     /// by the [`Ok`]'s value.
1002     ///
1003     /// [`Ok`]: enum.Result.html#variant.Ok
1004     /// [`Err`]: enum.Result.html#variant.Err
1005     ///
1006     ///
1007     /// # Examples
1008     ///
1009     /// ```{.should_panic}
1010     /// let x: Result<u32, &str> = Ok(2);
1011     /// x.unwrap_err(); // panics with `2`
1012     /// ```
1013     ///
1014     /// ```
1015     /// let x: Result<u32, &str> = Err("emergency failure");
1016     /// assert_eq!(x.unwrap_err(), "emergency failure");
1017     /// ```
1018     #[inline]
1019     #[track_caller]
1020     #[stable(feature = "rust1", since = "1.0.0")]
1021     pub fn unwrap_err(self) -> E {
1022         match self {
1023             Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t),
1024             Err(e) => e,
1025         }
1026     }
1027
1028     /// Unwraps a result, yielding the content of an [`Err`].
1029     ///
1030     /// # Panics
1031     ///
1032     /// Panics if the value is an [`Ok`], with a panic message including the
1033     /// passed message, and the content of the [`Ok`].
1034     ///
1035     /// [`Ok`]: enum.Result.html#variant.Ok
1036     /// [`Err`]: enum.Result.html#variant.Err
1037     ///
1038     /// # Examples
1039     ///
1040     /// Basic usage:
1041     ///
1042     /// ```{.should_panic}
1043     /// let x: Result<u32, &str> = Ok(10);
1044     /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
1045     /// ```
1046     #[inline]
1047     #[track_caller]
1048     #[stable(feature = "result_expect_err", since = "1.17.0")]
1049     pub fn expect_err(self, msg: &str) -> E {
1050         match self {
1051             Ok(t) => unwrap_failed(msg, &t),
1052             Err(e) => e,
1053         }
1054     }
1055 }
1056
1057 impl<T: Default, E> Result<T, E> {
1058     /// Returns the contained value or a default
1059     ///
1060     /// Consumes the `self` argument then, if [`Ok`], returns the contained
1061     /// value, otherwise if [`Err`], returns the default value for that
1062     /// type.
1063     ///
1064     /// # Examples
1065     ///
1066     /// Converts a string to an integer, turning poorly-formed strings
1067     /// into 0 (the default value for integers). [`parse`] converts
1068     /// a string to any other type that implements [`FromStr`], returning an
1069     /// [`Err`] on error.
1070     ///
1071     /// ```
1072     /// let good_year_from_input = "1909";
1073     /// let bad_year_from_input = "190blarg";
1074     /// let good_year = good_year_from_input.parse().unwrap_or_default();
1075     /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
1076     ///
1077     /// assert_eq!(1909, good_year);
1078     /// assert_eq!(0, bad_year);
1079     /// ```
1080     ///
1081     /// [`parse`]: ../../std/primitive.str.html#method.parse
1082     /// [`FromStr`]: ../../std/str/trait.FromStr.html
1083     /// [`Ok`]: enum.Result.html#variant.Ok
1084     /// [`Err`]: enum.Result.html#variant.Err
1085     #[inline]
1086     #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
1087     pub fn unwrap_or_default(self) -> T {
1088         match self {
1089             Ok(x) => x,
1090             Err(_) => Default::default(),
1091         }
1092     }
1093 }
1094
1095 #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
1096 impl<T, E: Into<!>> Result<T, E> {
1097     /// Unwraps a result that can never be an [`Err`], yielding the content of the [`Ok`].
1098     ///
1099     /// Unlike [`unwrap`], this method is known to never panic on the
1100     /// result types it is implemented for. Therefore, it can be used
1101     /// instead of `unwrap` as a maintainability safeguard that will fail
1102     /// to compile if the error type of the `Result` is later changed
1103     /// to an error that can actually occur.
1104     ///
1105     /// [`Ok`]: enum.Result.html#variant.Ok
1106     /// [`Err`]: enum.Result.html#variant.Err
1107     /// [`unwrap`]: enum.Result.html#method.unwrap
1108     ///
1109     /// # Examples
1110     ///
1111     /// Basic usage:
1112     ///
1113     /// ```
1114     /// # #![feature(never_type)]
1115     /// # #![feature(unwrap_infallible)]
1116     ///
1117     /// fn only_good_news() -> Result<String, !> {
1118     ///     Ok("this is fine".into())
1119     /// }
1120     ///
1121     /// let s: String = only_good_news().into_ok();
1122     /// println!("{}", s);
1123     /// ```
1124     #[inline]
1125     pub fn into_ok(self) -> T {
1126         match self {
1127             Ok(x) => x,
1128             Err(e) => e.into(),
1129         }
1130     }
1131 }
1132
1133 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1134 impl<T: Deref, E> Result<T, E> {
1135     /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&T::Target, &E>`.
1136     ///
1137     /// Leaves the original `Result` in-place, creating a new one containing a reference to the
1138     /// `Ok` type's `Deref::Target` type.
1139     pub fn as_deref(&self) -> Result<&T::Target, &E> {
1140         self.as_ref().map(|t| t.deref())
1141     }
1142 }
1143
1144 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1145 impl<T, E: Deref> Result<T, E> {
1146     /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&T, &E::Target>`.
1147     ///
1148     /// Leaves the original `Result` in-place, creating a new one containing a reference to the
1149     /// `Err` type's `Deref::Target` type.
1150     pub fn as_deref_err(&self) -> Result<&T, &E::Target> {
1151         self.as_ref().map_err(|e| e.deref())
1152     }
1153 }
1154
1155 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1156 impl<T: DerefMut, E> Result<T, E> {
1157     /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut T::Target, &mut E>`.
1158     ///
1159     /// Leaves the original `Result` in-place, creating a new one containing a mutable reference to
1160     /// the `Ok` type's `Deref::Target` type.
1161     pub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E> {
1162         self.as_mut().map(|t| t.deref_mut())
1163     }
1164 }
1165
1166 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
1167 impl<T, E: DerefMut> Result<T, E> {
1168     /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut T, &mut E::Target>`.
1169     ///
1170     /// Leaves the original `Result` in-place, creating a new one containing a mutable reference to
1171     /// the `Err` type's `Deref::Target` type.
1172     pub fn as_deref_mut_err(&mut self) -> Result<&mut T, &mut E::Target> {
1173         self.as_mut().map_err(|e| e.deref_mut())
1174     }
1175 }
1176
1177 impl<T, E> Result<Option<T>, E> {
1178     /// Transposes a `Result` of an `Option` into an `Option` of a `Result`.
1179     ///
1180     /// `Ok(None)` will be mapped to `None`.
1181     /// `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`.
1182     ///
1183     /// # Examples
1184     ///
1185     /// ```
1186     /// #[derive(Debug, Eq, PartialEq)]
1187     /// struct SomeErr;
1188     ///
1189     /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1190     /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1191     /// assert_eq!(x.transpose(), y);
1192     /// ```
1193     #[inline]
1194     #[stable(feature = "transpose_result", since = "1.33.0")]
1195     pub fn transpose(self) -> Option<Result<T, E>> {
1196         match self {
1197             Ok(Some(x)) => Some(Ok(x)),
1198             Ok(None) => None,
1199             Err(e) => Some(Err(e)),
1200         }
1201     }
1202 }
1203
1204 // This is a separate function to reduce the code size of the methods
1205 #[inline(never)]
1206 #[cold]
1207 #[track_caller]
1208 fn unwrap_failed(msg: &str, error: &dyn fmt::Debug) -> ! {
1209     panic!("{}: {:?}", msg, error)
1210 }
1211
1212 /////////////////////////////////////////////////////////////////////////////
1213 // Trait implementations
1214 /////////////////////////////////////////////////////////////////////////////
1215
1216 #[stable(feature = "rust1", since = "1.0.0")]
1217 impl<T: Clone, E: Clone> Clone for Result<T, E> {
1218     #[inline]
1219     fn clone(&self) -> Self {
1220         match self {
1221             Ok(x) => Ok(x.clone()),
1222             Err(x) => Err(x.clone()),
1223         }
1224     }
1225
1226     #[inline]
1227     fn clone_from(&mut self, source: &Self) {
1228         match (self, source) {
1229             (Ok(to), Ok(from)) => to.clone_from(from),
1230             (Err(to), Err(from)) => to.clone_from(from),
1231             (to, from) => *to = from.clone(),
1232         }
1233     }
1234 }
1235
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 impl<T, E> IntoIterator for Result<T, E> {
1238     type Item = T;
1239     type IntoIter = IntoIter<T>;
1240
1241     /// Returns a consuming iterator over the possibly contained value.
1242     ///
1243     /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
1244     ///
1245     /// # Examples
1246     ///
1247     /// Basic usage:
1248     ///
1249     /// ```
1250     /// let x: Result<u32, &str> = Ok(5);
1251     /// let v: Vec<u32> = x.into_iter().collect();
1252     /// assert_eq!(v, [5]);
1253     ///
1254     /// let x: Result<u32, &str> = Err("nothing!");
1255     /// let v: Vec<u32> = x.into_iter().collect();
1256     /// assert_eq!(v, []);
1257     /// ```
1258     #[inline]
1259     fn into_iter(self) -> IntoIter<T> {
1260         IntoIter { inner: self.ok() }
1261     }
1262 }
1263
1264 #[stable(since = "1.4.0", feature = "result_iter")]
1265 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
1266     type Item = &'a T;
1267     type IntoIter = Iter<'a, T>;
1268
1269     fn into_iter(self) -> Iter<'a, T> {
1270         self.iter()
1271     }
1272 }
1273
1274 #[stable(since = "1.4.0", feature = "result_iter")]
1275 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
1276     type Item = &'a mut T;
1277     type IntoIter = IterMut<'a, T>;
1278
1279     fn into_iter(self) -> IterMut<'a, T> {
1280         self.iter_mut()
1281     }
1282 }
1283
1284 /////////////////////////////////////////////////////////////////////////////
1285 // The Result Iterators
1286 /////////////////////////////////////////////////////////////////////////////
1287
1288 /// An iterator over a reference to the [`Ok`] variant of a [`Result`].
1289 ///
1290 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1291 ///
1292 /// Created by [`Result::iter`].
1293 ///
1294 /// [`Ok`]: enum.Result.html#variant.Ok
1295 /// [`Result`]: enum.Result.html
1296 /// [`Result::iter`]: enum.Result.html#method.iter
1297 #[derive(Debug)]
1298 #[stable(feature = "rust1", since = "1.0.0")]
1299 pub struct Iter<'a, T: 'a> {
1300     inner: Option<&'a T>,
1301 }
1302
1303 #[stable(feature = "rust1", since = "1.0.0")]
1304 impl<'a, T> Iterator for Iter<'a, T> {
1305     type Item = &'a T;
1306
1307     #[inline]
1308     fn next(&mut self) -> Option<&'a T> {
1309         self.inner.take()
1310     }
1311     #[inline]
1312     fn size_hint(&self) -> (usize, Option<usize>) {
1313         let n = if self.inner.is_some() { 1 } else { 0 };
1314         (n, Some(n))
1315     }
1316 }
1317
1318 #[stable(feature = "rust1", since = "1.0.0")]
1319 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1320     #[inline]
1321     fn next_back(&mut self) -> Option<&'a T> {
1322         self.inner.take()
1323     }
1324 }
1325
1326 #[stable(feature = "rust1", since = "1.0.0")]
1327 impl<T> ExactSizeIterator for Iter<'_, T> {}
1328
1329 #[stable(feature = "fused", since = "1.26.0")]
1330 impl<T> FusedIterator for Iter<'_, T> {}
1331
1332 #[unstable(feature = "trusted_len", issue = "37572")]
1333 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1334
1335 #[stable(feature = "rust1", since = "1.0.0")]
1336 impl<T> Clone for Iter<'_, T> {
1337     #[inline]
1338     fn clone(&self) -> Self {
1339         Iter { inner: self.inner }
1340     }
1341 }
1342
1343 /// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
1344 ///
1345 /// Created by [`Result::iter_mut`].
1346 ///
1347 /// [`Ok`]: enum.Result.html#variant.Ok
1348 /// [`Result`]: enum.Result.html
1349 /// [`Result::iter_mut`]: enum.Result.html#method.iter_mut
1350 #[derive(Debug)]
1351 #[stable(feature = "rust1", since = "1.0.0")]
1352 pub struct IterMut<'a, T: 'a> {
1353     inner: Option<&'a mut T>,
1354 }
1355
1356 #[stable(feature = "rust1", since = "1.0.0")]
1357 impl<'a, T> Iterator for IterMut<'a, T> {
1358     type Item = &'a mut T;
1359
1360     #[inline]
1361     fn next(&mut self) -> Option<&'a mut T> {
1362         self.inner.take()
1363     }
1364     #[inline]
1365     fn size_hint(&self) -> (usize, Option<usize>) {
1366         let n = if self.inner.is_some() { 1 } else { 0 };
1367         (n, Some(n))
1368     }
1369 }
1370
1371 #[stable(feature = "rust1", since = "1.0.0")]
1372 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1373     #[inline]
1374     fn next_back(&mut self) -> Option<&'a mut T> {
1375         self.inner.take()
1376     }
1377 }
1378
1379 #[stable(feature = "rust1", since = "1.0.0")]
1380 impl<T> ExactSizeIterator for IterMut<'_, T> {}
1381
1382 #[stable(feature = "fused", since = "1.26.0")]
1383 impl<T> FusedIterator for IterMut<'_, T> {}
1384
1385 #[unstable(feature = "trusted_len", issue = "37572")]
1386 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1387
1388 /// An iterator over the value in a [`Ok`] variant of a [`Result`].
1389 ///
1390 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1391 ///
1392 /// This struct is created by the [`into_iter`] method on
1393 /// [`Result`] (provided by the [`IntoIterator`] trait).
1394 ///
1395 /// [`Ok`]: enum.Result.html#variant.Ok
1396 /// [`Result`]: enum.Result.html
1397 /// [`into_iter`]: ../iter/trait.IntoIterator.html#tymethod.into_iter
1398 /// [`IntoIterator`]: ../iter/trait.IntoIterator.html
1399 #[derive(Clone, Debug)]
1400 #[stable(feature = "rust1", since = "1.0.0")]
1401 pub struct IntoIter<T> {
1402     inner: Option<T>,
1403 }
1404
1405 #[stable(feature = "rust1", since = "1.0.0")]
1406 impl<T> Iterator for IntoIter<T> {
1407     type Item = T;
1408
1409     #[inline]
1410     fn next(&mut self) -> Option<T> {
1411         self.inner.take()
1412     }
1413     #[inline]
1414     fn size_hint(&self) -> (usize, Option<usize>) {
1415         let n = if self.inner.is_some() { 1 } else { 0 };
1416         (n, Some(n))
1417     }
1418 }
1419
1420 #[stable(feature = "rust1", since = "1.0.0")]
1421 impl<T> DoubleEndedIterator for IntoIter<T> {
1422     #[inline]
1423     fn next_back(&mut self) -> Option<T> {
1424         self.inner.take()
1425     }
1426 }
1427
1428 #[stable(feature = "rust1", since = "1.0.0")]
1429 impl<T> ExactSizeIterator for IntoIter<T> {}
1430
1431 #[stable(feature = "fused", since = "1.26.0")]
1432 impl<T> FusedIterator for IntoIter<T> {}
1433
1434 #[unstable(feature = "trusted_len", issue = "37572")]
1435 unsafe impl<A> TrustedLen for IntoIter<A> {}
1436
1437 /////////////////////////////////////////////////////////////////////////////
1438 // FromIterator
1439 /////////////////////////////////////////////////////////////////////////////
1440
1441 #[stable(feature = "rust1", since = "1.0.0")]
1442 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
1443     /// Takes each element in the `Iterator`: if it is an `Err`, no further
1444     /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
1445     /// container with the values of each `Result` is returned.
1446     ///
1447     /// Here is an example which increments every integer in a vector,
1448     /// checking for overflow:
1449     ///
1450     /// ```
1451     /// let v = vec![1, 2];
1452     /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1453     ///     x.checked_add(1).ok_or("Overflow!")
1454     /// ).collect();
1455     /// assert_eq!(res, Ok(vec![2, 3]));
1456     /// ```
1457     ///
1458     /// Here is another example that tries to subtract one from another list
1459     /// of integers, this time checking for underflow:
1460     ///
1461     /// ```
1462     /// let v = vec![1, 2, 0];
1463     /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1464     ///     x.checked_sub(1).ok_or("Underflow!")
1465     /// ).collect();
1466     /// assert_eq!(res, Err("Underflow!"));
1467     /// ```
1468     ///
1469     /// Here is a variation on the previous example, showing that no
1470     /// further elements are taken from `iter` after the first `Err`.
1471     ///
1472     /// ```
1473     /// let v = vec![3, 2, 1, 10];
1474     /// let mut shared = 0;
1475     /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {
1476     ///     shared += x;
1477     ///     x.checked_sub(2).ok_or("Underflow!")
1478     /// }).collect();
1479     /// assert_eq!(res, Err("Underflow!"));
1480     /// assert_eq!(shared, 6);
1481     /// ```
1482     ///
1483     /// Since the third element caused an underflow, no further elements were taken,
1484     /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1485     #[inline]
1486     fn from_iter<I: IntoIterator<Item = Result<A, E>>>(iter: I) -> Result<V, E> {
1487         // FIXME(#11084): This could be replaced with Iterator::scan when this
1488         // performance bug is closed.
1489
1490         iter::process_results(iter.into_iter(), |i| i.collect())
1491     }
1492 }
1493
1494 #[unstable(feature = "try_trait", issue = "42327")]
1495 impl<T, E> ops::Try for Result<T, E> {
1496     type Ok = T;
1497     type Error = E;
1498
1499     #[inline]
1500     fn into_result(self) -> Self {
1501         self
1502     }
1503
1504     #[inline]
1505     fn from_ok(v: T) -> Self {
1506         Ok(v)
1507     }
1508
1509     #[inline]
1510     fn from_error(v: E) -> Self {
1511         Err(v)
1512     }
1513 }