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