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