]> git.lizzy.rs Git - rust.git/blob - src/libcore/result.rs
Auto merge of #35627 - apasel422:coerce-cell, r=alexcrichton
[rust.git] / src / libcore / result.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Error handling with the `Result` type.
12 //!
13 //! `Result<T, E>` is the type used for returning and propagating
14 //! errors. It is an enum with the variants, `Ok(T)`, representing
15 //! success and containing a value, and `Err(E)`, representing error
16 //! and containing an error value.
17 //!
18 //! ```
19 //! # #[allow(dead_code)]
20 //! enum Result<T, E> {
21 //!    Ok(T),
22 //!    Err(E),
23 //! }
24 //! ```
25 //!
26 //! Functions return `Result` whenever errors are expected and
27 //! recoverable. In the `std` crate `Result` is most prominently used
28 //! for [I/O](../../std/io/index.html).
29 //!
30 //! A simple function returning `Result` might be
31 //! defined and used like so:
32 //!
33 //! ```
34 //! #[derive(Debug)]
35 //! enum Version { Version1, Version2 }
36 //!
37 //! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
38 //!     match header.get(0) {
39 //!         None => Err("invalid header length"),
40 //!         Some(&1) => Ok(Version::Version1),
41 //!         Some(&2) => Ok(Version::Version2),
42 //!         Some(_) => Err("invalid version"),
43 //!     }
44 //! }
45 //!
46 //! let version = parse_version(&[1, 2, 3, 4]);
47 //! match version {
48 //!     Ok(v) => println!("working with version: {:?}", v),
49 //!     Err(e) => println!("error parsing header: {:?}", e),
50 //! }
51 //! ```
52 //!
53 //! Pattern matching on `Result`s is clear and straightforward for
54 //! simple cases, but `Result` comes with some convenience methods
55 //! that make working with it more succinct.
56 //!
57 //! ```
58 //! let good_result: Result<i32, i32> = Ok(10);
59 //! let bad_result: Result<i32, i32> = Err(10);
60 //!
61 //! // The `is_ok` and `is_err` methods do what they say.
62 //! assert!(good_result.is_ok() && !good_result.is_err());
63 //! assert!(bad_result.is_err() && !bad_result.is_ok());
64 //!
65 //! // `map` consumes the `Result` and produces another.
66 //! let good_result: Result<i32, i32> = good_result.map(|i| i + 1);
67 //! let bad_result: Result<i32, i32> = bad_result.map(|i| i - 1);
68 //!
69 //! // Use `and_then` to continue the computation.
70 //! let good_result: Result<bool, i32> = good_result.and_then(|i| Ok(i == 11));
71 //!
72 //! // Use `or_else` to handle the error.
73 //! let bad_result: Result<i32, i32> = bad_result.or_else(|i| Ok(i + 20));
74 //!
75 //! // Consume the result and return the contents with `unwrap`.
76 //! let final_awesome_result = good_result.unwrap();
77 //! ```
78 //!
79 //! # Results must be used
80 //!
81 //! A common problem with using return values to indicate errors is
82 //! that it is easy to ignore the return value, thus failing to handle
83 //! the error. Result is annotated with the #[must_use] attribute,
84 //! which will cause the compiler to issue a warning when a Result
85 //! value is ignored. This makes `Result` especially useful with
86 //! functions that may encounter errors but don't otherwise return a
87 //! useful value.
88 //!
89 //! Consider the `write_all` method defined for I/O types
90 //! by the [`Write`](../../std/io/trait.Write.html) trait:
91 //!
92 //! ```
93 //! use std::io;
94 //!
95 //! trait Write {
96 //!     fn write_all(&mut self, bytes: &[u8]) -> Result<(), io::Error>;
97 //! }
98 //! ```
99 //!
100 //! *Note: The actual definition of `Write` uses `io::Result`, which
101 //! is just a synonym for `Result<T, io::Error>`.*
102 //!
103 //! This method doesn't produce a value, but the write may
104 //! fail. It's crucial to handle the error case, and *not* write
105 //! something like this:
106 //!
107 //! ```no_run
108 //! # #![allow(unused_must_use)] // \o/
109 //! use std::fs::File;
110 //! use std::io::prelude::*;
111 //!
112 //! let mut file = File::create("valuable_data.txt").unwrap();
113 //! // If `write_all` errors, then we'll never know, because the return
114 //! // value is ignored.
115 //! file.write_all(b"important message");
116 //! ```
117 //!
118 //! If you *do* write that in Rust, the compiler will give you a
119 //! warning (by default, controlled by the `unused_must_use` lint).
120 //!
121 //! You might instead, if you don't want to handle the error, simply
122 //! assert success with `expect`. This will panic if the
123 //! write fails, providing a marginally useful message indicating why:
124 //!
125 //! ```{.no_run}
126 //! use std::fs::File;
127 //! use std::io::prelude::*;
128 //!
129 //! let mut file = File::create("valuable_data.txt").unwrap();
130 //! file.write_all(b"important message").expect("failed to write message");
131 //! ```
132 //!
133 //! You might also simply assert success:
134 //!
135 //! ```{.no_run}
136 //! # use std::fs::File;
137 //! # use std::io::prelude::*;
138 //! # let mut file = File::create("valuable_data.txt").unwrap();
139 //! assert!(file.write_all(b"important message").is_ok());
140 //! ```
141 //!
142 //! Or propagate the error up the call stack with `try!`:
143 //!
144 //! ```
145 //! # use std::fs::File;
146 //! # use std::io::prelude::*;
147 //! # use std::io;
148 //! # #[allow(dead_code)]
149 //! fn write_message() -> io::Result<()> {
150 //!     let mut file = try!(File::create("valuable_data.txt"));
151 //!     try!(file.write_all(b"important message"));
152 //!     Ok(())
153 //! }
154 //! ```
155 //!
156 //! # The `try!` macro
157 //!
158 //! When writing code that calls many functions that return the
159 //! `Result` type, the error handling can be tedious.  The `try!`
160 //! macro hides some of the boilerplate of propagating errors up the
161 //! call stack.
162 //!
163 //! It replaces this:
164 //!
165 //! ```
166 //! # #![allow(dead_code)]
167 //! use std::fs::File;
168 //! use std::io::prelude::*;
169 //! use std::io;
170 //!
171 //! struct Info {
172 //!     name: String,
173 //!     age: i32,
174 //!     rating: i32,
175 //! }
176 //!
177 //! fn write_info(info: &Info) -> io::Result<()> {
178 //!     // Early return on error
179 //!     let mut file = match File::create("my_best_friends.txt") {
180 //!            Err(e) => return Err(e),
181 //!            Ok(f) => f,
182 //!     };
183 //!     if let Err(e) = file.write_all(format!("name: {}\n", info.name).as_bytes()) {
184 //!         return Err(e)
185 //!     }
186 //!     if let Err(e) = file.write_all(format!("age: {}\n", info.age).as_bytes()) {
187 //!         return Err(e)
188 //!     }
189 //!     if let Err(e) = file.write_all(format!("rating: {}\n", info.rating).as_bytes()) {
190 //!         return Err(e)
191 //!     }
192 //!     Ok(())
193 //! }
194 //! ```
195 //!
196 //! With this:
197 //!
198 //! ```
199 //! # #![allow(dead_code)]
200 //! use std::fs::File;
201 //! use std::io::prelude::*;
202 //! use std::io;
203 //!
204 //! struct Info {
205 //!     name: String,
206 //!     age: i32,
207 //!     rating: i32,
208 //! }
209 //!
210 //! fn write_info(info: &Info) -> io::Result<()> {
211 //!     let mut file = try!(File::create("my_best_friends.txt"));
212 //!     // Early return on error
213 //!     try!(file.write_all(format!("name: {}\n", info.name).as_bytes()));
214 //!     try!(file.write_all(format!("age: {}\n", info.age).as_bytes()));
215 //!     try!(file.write_all(format!("rating: {}\n", info.rating).as_bytes()));
216 //!     Ok(())
217 //! }
218 //! ```
219 //!
220 //! *It's much nicer!*
221 //!
222 //! Wrapping an expression in `try!` will result in the unwrapped
223 //! success (`Ok`) value, unless the result is `Err`, in which case
224 //! `Err` is returned early from the enclosing function. Its simple definition
225 //! makes it clear:
226 //!
227 //! ```
228 //! macro_rules! try {
229 //!     ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
230 //! }
231 //! ```
232 //!
233 //! `try!` is imported by the prelude and is available everywhere, but it can only
234 //! be used in functions that return `Result` because of the early return of
235 //! `Err` that it provides.
236
237 #![stable(feature = "rust1", since = "1.0.0")]
238
239 use self::Result::{Ok, Err};
240
241 use clone::Clone;
242 use fmt;
243 use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSizeIterator, IntoIterator};
244 use ops::FnOnce;
245 use option::Option::{self, None, Some};
246
247 /// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
248 ///
249 /// See the [`std::result`](index.html) module documentation for details.
250 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
251 #[must_use]
252 #[stable(feature = "rust1", since = "1.0.0")]
253 pub enum Result<T, E> {
254     /// Contains the success value
255     #[stable(feature = "rust1", since = "1.0.0")]
256     Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
257
258     /// Contains the error value
259     #[stable(feature = "rust1", since = "1.0.0")]
260     Err(#[stable(feature = "rust1", since = "1.0.0")] E),
261 }
262
263 /////////////////////////////////////////////////////////////////////////////
264 // Type implementation
265 /////////////////////////////////////////////////////////////////////////////
266
267 impl<T, E> Result<T, E> {
268     /////////////////////////////////////////////////////////////////////////
269     // Querying the contained values
270     /////////////////////////////////////////////////////////////////////////
271
272     /// Returns true if the result is `Ok`
273     ///
274     /// # Examples
275     ///
276     /// Basic usage:
277     ///
278     /// ```
279     /// let x: Result<i32, &str> = Ok(-3);
280     /// assert_eq!(x.is_ok(), true);
281     ///
282     /// let x: Result<i32, &str> = Err("Some error message");
283     /// assert_eq!(x.is_ok(), false);
284     /// ```
285     #[inline]
286     #[stable(feature = "rust1", since = "1.0.0")]
287     pub fn is_ok(&self) -> bool {
288         match *self {
289             Ok(_) => true,
290             Err(_) => false
291         }
292     }
293
294     /// Returns true if the result is `Err`
295     ///
296     /// # Examples
297     ///
298     /// Basic usage:
299     ///
300     /// ```
301     /// let x: Result<i32, &str> = Ok(-3);
302     /// assert_eq!(x.is_err(), false);
303     ///
304     /// let x: Result<i32, &str> = Err("Some error message");
305     /// assert_eq!(x.is_err(), true);
306     /// ```
307     #[inline]
308     #[stable(feature = "rust1", since = "1.0.0")]
309     pub fn is_err(&self) -> bool {
310         !self.is_ok()
311     }
312
313     /////////////////////////////////////////////////////////////////////////
314     // Adapter for each variant
315     /////////////////////////////////////////////////////////////////////////
316
317     /// Converts from `Result<T, E>` to `Option<T>`
318     ///
319     /// Converts `self` into an `Option<T>`, consuming `self`,
320     /// and discarding the error, if any.
321     ///
322     /// # Examples
323     ///
324     /// Basic usage:
325     ///
326     /// ```
327     /// let x: Result<u32, &str> = Ok(2);
328     /// assert_eq!(x.ok(), Some(2));
329     ///
330     /// let x: Result<u32, &str> = Err("Nothing here");
331     /// assert_eq!(x.ok(), None);
332     /// ```
333     #[inline]
334     #[stable(feature = "rust1", since = "1.0.0")]
335     pub fn ok(self) -> Option<T> {
336         match self {
337             Ok(x)  => Some(x),
338             Err(_) => None,
339         }
340     }
341
342     /// Converts from `Result<T, E>` to `Option<E>`
343     ///
344     /// Converts `self` into an `Option<E>`, consuming `self`,
345     /// and discarding the success value, if any.
346     ///
347     /// # Examples
348     ///
349     /// Basic usage:
350     ///
351     /// ```
352     /// let x: Result<u32, &str> = Ok(2);
353     /// assert_eq!(x.err(), None);
354     ///
355     /// let x: Result<u32, &str> = Err("Nothing here");
356     /// assert_eq!(x.err(), Some("Nothing here"));
357     /// ```
358     #[inline]
359     #[stable(feature = "rust1", since = "1.0.0")]
360     pub fn err(self) -> Option<E> {
361         match self {
362             Ok(_)  => None,
363             Err(x) => Some(x),
364         }
365     }
366
367     /////////////////////////////////////////////////////////////////////////
368     // Adapter for working with references
369     /////////////////////////////////////////////////////////////////////////
370
371     /// Converts from `Result<T, E>` to `Result<&T, &E>`
372     ///
373     /// Produces a new `Result`, containing a reference
374     /// into the original, leaving the original in place.
375     ///
376     /// # Examples
377     ///
378     /// Basic usage:
379     ///
380     /// ```
381     /// let x: Result<u32, &str> = Ok(2);
382     /// assert_eq!(x.as_ref(), Ok(&2));
383     ///
384     /// let x: Result<u32, &str> = Err("Error");
385     /// assert_eq!(x.as_ref(), Err(&"Error"));
386     /// ```
387     #[inline]
388     #[stable(feature = "rust1", since = "1.0.0")]
389     pub fn as_ref(&self) -> Result<&T, &E> {
390         match *self {
391             Ok(ref x) => Ok(x),
392             Err(ref x) => Err(x),
393         }
394     }
395
396     /// Converts from `Result<T, E>` to `Result<&mut T, &mut E>`
397     ///
398     /// # Examples
399     ///
400     /// Basic usage:
401     ///
402     /// ```
403     /// fn mutate(r: &mut Result<i32, i32>) {
404     ///     match r.as_mut() {
405     ///         Ok(v) => *v = 42,
406     ///         Err(e) => *e = 0,
407     ///     }
408     /// }
409     ///
410     /// let mut x: Result<i32, i32> = Ok(2);
411     /// mutate(&mut x);
412     /// assert_eq!(x.unwrap(), 42);
413     ///
414     /// let mut x: Result<i32, i32> = Err(13);
415     /// mutate(&mut x);
416     /// assert_eq!(x.unwrap_err(), 0);
417     /// ```
418     #[inline]
419     #[stable(feature = "rust1", since = "1.0.0")]
420     pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
421         match *self {
422             Ok(ref mut x) => Ok(x),
423             Err(ref mut x) => Err(x),
424         }
425     }
426
427     /////////////////////////////////////////////////////////////////////////
428     // Transforming contained values
429     /////////////////////////////////////////////////////////////////////////
430
431     /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
432     /// contained `Ok` value, leaving an `Err` value untouched.
433     ///
434     /// This function can be used to compose the results of two functions.
435     ///
436     /// # Examples
437     ///
438     /// Print the numbers on each line of a string multiplied by two.
439     ///
440     /// ```
441     /// let line = "1\n2\n3\n4\n";
442     ///
443     /// for num in line.lines() {
444     ///     match num.parse::<i32>().map(|i| i * 2) {
445     ///         Ok(n) => println!("{}", n),
446     ///         Err(..) => {}
447     ///     }
448     /// }
449     /// ```
450     #[inline]
451     #[stable(feature = "rust1", since = "1.0.0")]
452     pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
453         match self {
454             Ok(t) => Ok(op(t)),
455             Err(e) => Err(e)
456         }
457     }
458
459     /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
460     /// contained `Err` value, leaving an `Ok` value untouched.
461     ///
462     /// This function can be used to pass through a successful result while handling
463     /// an error.
464     ///
465     /// # Examples
466     ///
467     /// Basic usage:
468     ///
469     /// ```
470     /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
471     ///
472     /// let x: Result<u32, u32> = Ok(2);
473     /// assert_eq!(x.map_err(stringify), Ok(2));
474     ///
475     /// let x: Result<u32, u32> = Err(13);
476     /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
477     /// ```
478     #[inline]
479     #[stable(feature = "rust1", since = "1.0.0")]
480     pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> {
481         match self {
482             Ok(t) => Ok(t),
483             Err(e) => Err(op(e))
484         }
485     }
486
487     /////////////////////////////////////////////////////////////////////////
488     // Iterator constructors
489     /////////////////////////////////////////////////////////////////////////
490
491     /// Returns an iterator over the possibly contained value.
492     ///
493     /// # Examples
494     ///
495     /// Basic usage:
496     ///
497     /// ```
498     /// let x: Result<u32, &str> = Ok(7);
499     /// assert_eq!(x.iter().next(), Some(&7));
500     ///
501     /// let x: Result<u32, &str> = Err("nothing!");
502     /// assert_eq!(x.iter().next(), None);
503     /// ```
504     #[inline]
505     #[stable(feature = "rust1", since = "1.0.0")]
506     pub fn iter(&self) -> Iter<T> {
507         Iter { inner: self.as_ref().ok() }
508     }
509
510     /// Returns a mutable iterator over the possibly contained value.
511     ///
512     /// # Examples
513     ///
514     /// Basic usage:
515     ///
516     /// ```
517     /// let mut x: Result<u32, &str> = Ok(7);
518     /// match x.iter_mut().next() {
519     ///     Some(v) => *v = 40,
520     ///     None => {},
521     /// }
522     /// assert_eq!(x, Ok(40));
523     ///
524     /// let mut x: Result<u32, &str> = Err("nothing!");
525     /// assert_eq!(x.iter_mut().next(), None);
526     /// ```
527     #[inline]
528     #[stable(feature = "rust1", since = "1.0.0")]
529     pub fn iter_mut(&mut self) -> IterMut<T> {
530         IterMut { inner: self.as_mut().ok() }
531     }
532
533     ////////////////////////////////////////////////////////////////////////
534     // Boolean operations on the values, eager and lazy
535     /////////////////////////////////////////////////////////////////////////
536
537     /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
538     ///
539     /// # Examples
540     ///
541     /// Basic usage:
542     ///
543     /// ```
544     /// let x: Result<u32, &str> = Ok(2);
545     /// let y: Result<&str, &str> = Err("late error");
546     /// assert_eq!(x.and(y), Err("late error"));
547     ///
548     /// let x: Result<u32, &str> = Err("early error");
549     /// let y: Result<&str, &str> = Ok("foo");
550     /// assert_eq!(x.and(y), Err("early error"));
551     ///
552     /// let x: Result<u32, &str> = Err("not a 2");
553     /// let y: Result<&str, &str> = Err("late error");
554     /// assert_eq!(x.and(y), Err("not a 2"));
555     ///
556     /// let x: Result<u32, &str> = Ok(2);
557     /// let y: Result<&str, &str> = Ok("different result type");
558     /// assert_eq!(x.and(y), Ok("different result type"));
559     /// ```
560     #[inline]
561     #[stable(feature = "rust1", since = "1.0.0")]
562     pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
563         match self {
564             Ok(_) => res,
565             Err(e) => Err(e),
566         }
567     }
568
569     /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
570     ///
571     /// This function can be used for control flow based on result values.
572     ///
573     /// # Examples
574     ///
575     /// Basic usage:
576     ///
577     /// ```
578     /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
579     /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
580     ///
581     /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
582     /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
583     /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
584     /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
585     /// ```
586     #[inline]
587     #[stable(feature = "rust1", since = "1.0.0")]
588     pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
589         match self {
590             Ok(t) => op(t),
591             Err(e) => Err(e),
592         }
593     }
594
595     /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
596     ///
597     /// # Examples
598     ///
599     /// Basic usage:
600     ///
601     /// ```
602     /// let x: Result<u32, &str> = Ok(2);
603     /// let y: Result<u32, &str> = Err("late error");
604     /// assert_eq!(x.or(y), Ok(2));
605     ///
606     /// let x: Result<u32, &str> = Err("early error");
607     /// let y: Result<u32, &str> = Ok(2);
608     /// assert_eq!(x.or(y), Ok(2));
609     ///
610     /// let x: Result<u32, &str> = Err("not a 2");
611     /// let y: Result<u32, &str> = Err("late error");
612     /// assert_eq!(x.or(y), Err("late error"));
613     ///
614     /// let x: Result<u32, &str> = Ok(2);
615     /// let y: Result<u32, &str> = Ok(100);
616     /// assert_eq!(x.or(y), Ok(2));
617     /// ```
618     #[inline]
619     #[stable(feature = "rust1", since = "1.0.0")]
620     pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
621         match self {
622             Ok(v) => Ok(v),
623             Err(_) => res,
624         }
625     }
626
627     /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
628     ///
629     /// This function can be used for control flow based on result values.
630     ///
631     /// # Examples
632     ///
633     /// Basic usage:
634     ///
635     /// ```
636     /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
637     /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
638     ///
639     /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
640     /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
641     /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
642     /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
643     /// ```
644     #[inline]
645     #[stable(feature = "rust1", since = "1.0.0")]
646     pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
647         match self {
648             Ok(t) => Ok(t),
649             Err(e) => op(e),
650         }
651     }
652
653     /// Unwraps a result, yielding the content of an `Ok`.
654     /// Else it returns `optb`.
655     ///
656     /// # Examples
657     ///
658     /// Basic usage:
659     ///
660     /// ```
661     /// let optb = 2;
662     /// let x: Result<u32, &str> = Ok(9);
663     /// assert_eq!(x.unwrap_or(optb), 9);
664     ///
665     /// let x: Result<u32, &str> = Err("error");
666     /// assert_eq!(x.unwrap_or(optb), optb);
667     /// ```
668     #[inline]
669     #[stable(feature = "rust1", since = "1.0.0")]
670     pub fn unwrap_or(self, optb: T) -> T {
671         match self {
672             Ok(t) => t,
673             Err(_) => optb
674         }
675     }
676
677     /// Unwraps a result, yielding the content of an `Ok`.
678     /// If the value is an `Err` then it calls `op` with its value.
679     ///
680     /// # Examples
681     ///
682     /// Basic usage:
683     ///
684     /// ```
685     /// fn count(x: &str) -> usize { x.len() }
686     ///
687     /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
688     /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
689     /// ```
690     #[inline]
691     #[stable(feature = "rust1", since = "1.0.0")]
692     pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
693         match self {
694             Ok(t) => t,
695             Err(e) => op(e)
696         }
697     }
698 }
699
700 impl<T, E: fmt::Debug> Result<T, E> {
701     /// Unwraps a result, yielding the content of an `Ok`.
702     ///
703     /// # Panics
704     ///
705     /// Panics if the value is an `Err`, with a panic message provided by the
706     /// `Err`'s value.
707     ///
708     /// # Examples
709     ///
710     /// Basic usage:
711     ///
712     /// ```
713     /// let x: Result<u32, &str> = Ok(2);
714     /// assert_eq!(x.unwrap(), 2);
715     /// ```
716     ///
717     /// ```{.should_panic}
718     /// let x: Result<u32, &str> = Err("emergency failure");
719     /// x.unwrap(); // panics with `emergency failure`
720     /// ```
721     #[inline]
722     #[stable(feature = "rust1", since = "1.0.0")]
723     pub fn unwrap(self) -> T {
724         match self {
725             Ok(t) => t,
726             Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", e),
727         }
728     }
729
730     /// Unwraps a result, yielding the content of an `Ok`.
731     ///
732     /// # Panics
733     ///
734     /// Panics if the value is an `Err`, with a panic message including the
735     /// passed message, and the content of the `Err`.
736     ///
737     /// # Examples
738     ///
739     /// Basic usage:
740     ///
741     /// ```{.should_panic}
742     /// let x: Result<u32, &str> = Err("emergency failure");
743     /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
744     /// ```
745     #[inline]
746     #[stable(feature = "result_expect", since = "1.4.0")]
747     pub fn expect(self, msg: &str) -> T {
748         match self {
749             Ok(t) => t,
750             Err(e) => unwrap_failed(msg, e),
751         }
752     }
753 }
754
755 impl<T: fmt::Debug, E> Result<T, E> {
756     /// Unwraps a result, yielding the content of an `Err`.
757     ///
758     /// # Panics
759     ///
760     /// Panics if the value is an `Ok`, with a custom panic message provided
761     /// by the `Ok`'s value.
762     ///
763     /// # Examples
764     ///
765     /// ```{.should_panic}
766     /// let x: Result<u32, &str> = Ok(2);
767     /// x.unwrap_err(); // panics with `2`
768     /// ```
769     ///
770     /// ```
771     /// let x: Result<u32, &str> = Err("emergency failure");
772     /// assert_eq!(x.unwrap_err(), "emergency failure");
773     /// ```
774     #[inline]
775     #[stable(feature = "rust1", since = "1.0.0")]
776     pub fn unwrap_err(self) -> E {
777         match self {
778             Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", t),
779             Err(e) => e,
780         }
781     }
782 }
783
784 // This is a separate function to reduce the code size of the methods
785 #[inline(never)]
786 #[cold]
787 fn unwrap_failed<E: fmt::Debug>(msg: &str, error: E) -> ! {
788     panic!("{}: {:?}", msg, error)
789 }
790
791 /////////////////////////////////////////////////////////////////////////////
792 // Trait implementations
793 /////////////////////////////////////////////////////////////////////////////
794
795 #[stable(feature = "rust1", since = "1.0.0")]
796 impl<T, E> IntoIterator for Result<T, E> {
797     type Item = T;
798     type IntoIter = IntoIter<T>;
799
800     /// Returns a consuming iterator over the possibly contained value.
801     ///
802     /// # Examples
803     ///
804     /// Basic usage:
805     ///
806     /// ```
807     /// let x: Result<u32, &str> = Ok(5);
808     /// let v: Vec<u32> = x.into_iter().collect();
809     /// assert_eq!(v, [5]);
810     ///
811     /// let x: Result<u32, &str> = Err("nothing!");
812     /// let v: Vec<u32> = x.into_iter().collect();
813     /// assert_eq!(v, []);
814     /// ```
815     #[inline]
816     fn into_iter(self) -> IntoIter<T> {
817         IntoIter { inner: self.ok() }
818     }
819 }
820
821 #[stable(since = "1.4.0", feature = "result_iter")]
822 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
823     type Item = &'a T;
824     type IntoIter = Iter<'a, T>;
825
826     fn into_iter(self) -> Iter<'a, T> {
827         self.iter()
828     }
829 }
830
831 #[stable(since = "1.4.0", feature = "result_iter")]
832 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
833     type Item = &'a mut T;
834     type IntoIter = IterMut<'a, T>;
835
836     fn into_iter(mut self) -> IterMut<'a, T> {
837         self.iter_mut()
838     }
839 }
840
841 /////////////////////////////////////////////////////////////////////////////
842 // The Result Iterators
843 /////////////////////////////////////////////////////////////////////////////
844
845 /// An iterator over a reference to the `Ok` variant of a `Result`.
846 #[derive(Debug)]
847 #[stable(feature = "rust1", since = "1.0.0")]
848 pub struct Iter<'a, T: 'a> { inner: Option<&'a T> }
849
850 #[stable(feature = "rust1", since = "1.0.0")]
851 impl<'a, T> Iterator for Iter<'a, T> {
852     type Item = &'a T;
853
854     #[inline]
855     fn next(&mut self) -> Option<&'a T> { self.inner.take() }
856     #[inline]
857     fn size_hint(&self) -> (usize, Option<usize>) {
858         let n = if self.inner.is_some() {1} else {0};
859         (n, Some(n))
860     }
861 }
862
863 #[stable(feature = "rust1", since = "1.0.0")]
864 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
865     #[inline]
866     fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
867 }
868
869 #[stable(feature = "rust1", since = "1.0.0")]
870 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
871
872 #[stable(feature = "rust1", since = "1.0.0")]
873 impl<'a, T> Clone for Iter<'a, T> {
874     fn clone(&self) -> Iter<'a, T> { Iter { inner: self.inner } }
875 }
876
877 /// An iterator over a mutable reference to the `Ok` variant of a `Result`.
878 #[derive(Debug)]
879 #[stable(feature = "rust1", since = "1.0.0")]
880 pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
881
882 #[stable(feature = "rust1", since = "1.0.0")]
883 impl<'a, T> Iterator for IterMut<'a, T> {
884     type Item = &'a mut T;
885
886     #[inline]
887     fn next(&mut self) -> Option<&'a mut T> { self.inner.take() }
888     #[inline]
889     fn size_hint(&self) -> (usize, Option<usize>) {
890         let n = if self.inner.is_some() {1} else {0};
891         (n, Some(n))
892     }
893 }
894
895 #[stable(feature = "rust1", since = "1.0.0")]
896 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
897     #[inline]
898     fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
899 }
900
901 #[stable(feature = "rust1", since = "1.0.0")]
902 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
903
904 /// An iterator over the value in a `Ok` variant of a `Result`.
905 #[derive(Debug)]
906 #[stable(feature = "rust1", since = "1.0.0")]
907 pub struct IntoIter<T> { inner: Option<T> }
908
909 #[stable(feature = "rust1", since = "1.0.0")]
910 impl<T> Iterator for IntoIter<T> {
911     type Item = T;
912
913     #[inline]
914     fn next(&mut self) -> Option<T> { self.inner.take() }
915     #[inline]
916     fn size_hint(&self) -> (usize, Option<usize>) {
917         let n = if self.inner.is_some() {1} else {0};
918         (n, Some(n))
919     }
920 }
921
922 #[stable(feature = "rust1", since = "1.0.0")]
923 impl<T> DoubleEndedIterator for IntoIter<T> {
924     #[inline]
925     fn next_back(&mut self) -> Option<T> { self.inner.take() }
926 }
927
928 #[stable(feature = "rust1", since = "1.0.0")]
929 impl<T> ExactSizeIterator for IntoIter<T> {}
930
931 /////////////////////////////////////////////////////////////////////////////
932 // FromIterator
933 /////////////////////////////////////////////////////////////////////////////
934
935 #[stable(feature = "rust1", since = "1.0.0")]
936 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
937     /// Takes each element in the `Iterator`: if it is an `Err`, no further
938     /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
939     /// container with the values of each `Result` is returned.
940     ///
941     /// Here is an example which increments every integer in a vector,
942     /// checking for overflow:
943     ///
944     /// ```
945     /// use std::u32;
946     ///
947     /// let v = vec!(1, 2);
948     /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|&x: &u32|
949     ///     if x == u32::MAX { Err("Overflow!") }
950     ///     else { Ok(x + 1) }
951     /// ).collect();
952     /// assert!(res == Ok(vec!(2, 3)));
953     /// ```
954     #[inline]
955     fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
956         // FIXME(#11084): This could be replaced with Iterator::scan when this
957         // performance bug is closed.
958
959         struct Adapter<Iter, E> {
960             iter: Iter,
961             err: Option<E>,
962         }
963
964         impl<T, E, Iter: Iterator<Item=Result<T, E>>> Iterator for Adapter<Iter, E> {
965             type Item = T;
966
967             #[inline]
968             fn next(&mut self) -> Option<T> {
969                 match self.iter.next() {
970                     Some(Ok(value)) => Some(value),
971                     Some(Err(err)) => {
972                         self.err = Some(err);
973                         None
974                     }
975                     None => None,
976                 }
977             }
978         }
979
980         let mut adapter = Adapter { iter: iter.into_iter(), err: None };
981         let v: V = FromIterator::from_iter(adapter.by_ref());
982
983         match adapter.err {
984             Some(err) => Err(err),
985             None => Ok(v),
986         }
987     }
988 }