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