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