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