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