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