]> git.lizzy.rs Git - rust.git/blob - src/libcore/result.rs
Auto merge of #31479 - kamalmarhubi:fmt-pointer-unsized, 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 //!     let mut file = try!(File::create("my_best_friends.txt"));
179 //!     // Early return on error
180 //!     if let Err(e) = file.write_all(format!("name: {}\n", info.name).as_bytes()) {
181 //!         return Err(e)
182 //!     }
183 //!     if let Err(e) = file.write_all(format!("age: {}\n", info.age).as_bytes()) {
184 //!         return Err(e)
185 //!     }
186 //!     if let Err(e) = file.write_all(format!("rating: {}\n", info.rating).as_bytes()) {
187 //!         return Err(e)
188 //!     }
189 //!     Ok(())
190 //! }
191 //! ```
192 //!
193 //! With this:
194 //!
195 //! ```
196 //! # #![allow(dead_code)]
197 //! use std::fs::File;
198 //! use std::io::prelude::*;
199 //! use std::io;
200 //!
201 //! struct Info {
202 //!     name: String,
203 //!     age: i32,
204 //!     rating: i32,
205 //! }
206 //!
207 //! fn write_info(info: &Info) -> io::Result<()> {
208 //!     let mut file = try!(File::create("my_best_friends.txt"));
209 //!     // Early return on error
210 //!     try!(file.write_all(format!("name: {}\n", info.name).as_bytes()));
211 //!     try!(file.write_all(format!("age: {}\n", info.age).as_bytes()));
212 //!     try!(file.write_all(format!("rating: {}\n", info.rating).as_bytes()));
213 //!     Ok(())
214 //! }
215 //! ```
216 //!
217 //! *It's much nicer!*
218 //!
219 //! Wrapping an expression in `try!` will result in the unwrapped
220 //! success (`Ok`) value, unless the result is `Err`, in which case
221 //! `Err` is returned early from the enclosing function. Its simple definition
222 //! makes it clear:
223 //!
224 //! ```
225 //! macro_rules! try {
226 //!     ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
227 //! }
228 //! ```
229 //!
230 //! `try!` is imported by the prelude and is available everywhere, but it can only
231 //! be used in functions that return `Result` because of the early return of
232 //! `Err` that it provides.
233
234 #![stable(feature = "rust1", since = "1.0.0")]
235
236 use self::Result::{Ok, Err};
237
238 use clone::Clone;
239 use fmt;
240 use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSizeIterator, IntoIterator};
241 use ops::FnOnce;
242 use option::Option::{self, None, Some};
243
244 /// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
245 ///
246 /// See the [`std::result`](index.html) module documentation for details.
247 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
248 #[must_use]
249 #[stable(feature = "rust1", since = "1.0.0")]
250 pub enum Result<T, E> {
251     /// Contains the success value
252     #[stable(feature = "rust1", since = "1.0.0")]
253     Ok(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] T),
254
255     /// Contains the error value
256     #[stable(feature = "rust1", since = "1.0.0")]
257     Err(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] E)
258 }
259
260 /////////////////////////////////////////////////////////////////////////////
261 // Type implementation
262 /////////////////////////////////////////////////////////////////////////////
263
264 impl<T, E> Result<T, E> {
265     /////////////////////////////////////////////////////////////////////////
266     // Querying the contained values
267     /////////////////////////////////////////////////////////////////////////
268
269     /// Returns true if the result is `Ok`
270     ///
271     /// # Examples
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     /// # Examples
292     ///
293     /// ```
294     /// let x: Result<i32, &str> = Ok(-3);
295     /// assert_eq!(x.is_err(), false);
296     ///
297     /// let x: Result<i32, &str> = Err("Some error message");
298     /// assert_eq!(x.is_err(), true);
299     /// ```
300     #[inline]
301     #[stable(feature = "rust1", since = "1.0.0")]
302     pub fn is_err(&self) -> bool {
303         !self.is_ok()
304     }
305
306     /////////////////////////////////////////////////////////////////////////
307     // Adapter for each variant
308     /////////////////////////////////////////////////////////////////////////
309
310     /// Converts from `Result<T, E>` to `Option<T>`
311     ///
312     /// Converts `self` into an `Option<T>`, consuming `self`,
313     /// and discarding the error, if any.
314     ///
315     /// # Examples
316     ///
317     /// ```
318     /// let x: Result<u32, &str> = Ok(2);
319     /// assert_eq!(x.ok(), Some(2));
320     ///
321     /// let x: Result<u32, &str> = Err("Nothing here");
322     /// assert_eq!(x.ok(), None);
323     /// ```
324     #[inline]
325     #[stable(feature = "rust1", since = "1.0.0")]
326     pub fn ok(self) -> Option<T> {
327         match self {
328             Ok(x)  => Some(x),
329             Err(_) => None,
330         }
331     }
332
333     /// Converts from `Result<T, E>` to `Option<E>`
334     ///
335     /// Converts `self` into an `Option<E>`, consuming `self`,
336     /// and discarding the success value, if any.
337     ///
338     /// # Examples
339     ///
340     /// ```
341     /// let x: Result<u32, &str> = Ok(2);
342     /// assert_eq!(x.err(), None);
343     ///
344     /// let x: Result<u32, &str> = Err("Nothing here");
345     /// assert_eq!(x.err(), Some("Nothing here"));
346     /// ```
347     #[inline]
348     #[stable(feature = "rust1", since = "1.0.0")]
349     pub fn err(self) -> Option<E> {
350         match self {
351             Ok(_)  => None,
352             Err(x) => Some(x),
353         }
354     }
355
356     /////////////////////////////////////////////////////////////////////////
357     // Adapter for working with references
358     /////////////////////////////////////////////////////////////////////////
359
360     /// Converts from `Result<T, E>` to `Result<&T, &E>`
361     ///
362     /// Produces a new `Result`, containing a reference
363     /// into the original, leaving the original in place.
364     ///
365     /// ```
366     /// let x: Result<u32, &str> = Ok(2);
367     /// assert_eq!(x.as_ref(), Ok(&2));
368     ///
369     /// let x: Result<u32, &str> = Err("Error");
370     /// assert_eq!(x.as_ref(), Err(&"Error"));
371     /// ```
372     #[inline]
373     #[stable(feature = "rust1", since = "1.0.0")]
374     pub fn as_ref(&self) -> Result<&T, &E> {
375         match *self {
376             Ok(ref x) => Ok(x),
377             Err(ref x) => Err(x),
378         }
379     }
380
381     /// Converts from `Result<T, E>` to `Result<&mut T, &mut E>`
382     ///
383     /// ```
384     /// fn mutate(r: &mut Result<i32, i32>) {
385     ///     match r.as_mut() {
386     ///         Ok(&mut ref mut v) => *v = 42,
387     ///         Err(&mut ref mut e) => *e = 0,
388     ///     }
389     /// }
390     ///
391     /// let mut x: Result<i32, i32> = Ok(2);
392     /// mutate(&mut x);
393     /// assert_eq!(x.unwrap(), 42);
394     ///
395     /// let mut x: Result<i32, i32> = Err(13);
396     /// mutate(&mut x);
397     /// assert_eq!(x.unwrap_err(), 0);
398     /// ```
399     #[inline]
400     #[stable(feature = "rust1", since = "1.0.0")]
401     pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
402         match *self {
403             Ok(ref mut x) => Ok(x),
404             Err(ref mut x) => Err(x),
405         }
406     }
407
408     /////////////////////////////////////////////////////////////////////////
409     // Transforming contained values
410     /////////////////////////////////////////////////////////////////////////
411
412     /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
413     /// contained `Ok` value, leaving an `Err` value untouched.
414     ///
415     /// This function can be used to compose the results of two functions.
416     ///
417     /// # Examples
418     ///
419     /// Print the numbers on each line of a string multiplied by two.
420     ///
421     /// ```
422     /// let line = "1\n2\n3\n4\n";
423     ///
424     /// for num in line.lines() {
425     ///     match num.parse::<i32>().map(|i| i * 2) {
426     ///         Ok(n) => println!("{}", n),
427     ///         Err(..) => {}
428     ///     }
429     /// }
430     /// ```
431     #[inline]
432     #[stable(feature = "rust1", since = "1.0.0")]
433     pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
434         match self {
435             Ok(t) => Ok(op(t)),
436             Err(e) => Err(e)
437         }
438     }
439
440     /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
441     /// contained `Err` value, leaving an `Ok` value untouched.
442     ///
443     /// This function can be used to pass through a successful result while handling
444     /// an error.
445     ///
446     /// # Examples
447     ///
448     /// ```
449     /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
450     ///
451     /// let x: Result<u32, u32> = Ok(2);
452     /// assert_eq!(x.map_err(stringify), Ok(2));
453     ///
454     /// let x: Result<u32, u32> = Err(13);
455     /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
456     /// ```
457     #[inline]
458     #[stable(feature = "rust1", since = "1.0.0")]
459     pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> {
460         match self {
461             Ok(t) => Ok(t),
462             Err(e) => Err(op(e))
463         }
464     }
465
466     /////////////////////////////////////////////////////////////////////////
467     // Iterator constructors
468     /////////////////////////////////////////////////////////////////////////
469
470     /// Returns an iterator over the possibly contained value.
471     ///
472     /// # Examples
473     ///
474     /// ```
475     /// let x: Result<u32, &str> = Ok(7);
476     /// assert_eq!(x.iter().next(), Some(&7));
477     ///
478     /// let x: Result<u32, &str> = Err("nothing!");
479     /// assert_eq!(x.iter().next(), None);
480     /// ```
481     #[inline]
482     #[stable(feature = "rust1", since = "1.0.0")]
483     pub fn iter(&self) -> Iter<T> {
484         Iter { inner: self.as_ref().ok() }
485     }
486
487     /// Returns a mutable iterator over the possibly contained value.
488     ///
489     /// # Examples
490     ///
491     /// ```
492     /// let mut x: Result<u32, &str> = Ok(7);
493     /// match x.iter_mut().next() {
494     ///     Some(v) => *v = 40,
495     ///     None => {},
496     /// }
497     /// assert_eq!(x, Ok(40));
498     ///
499     /// let mut x: Result<u32, &str> = Err("nothing!");
500     /// assert_eq!(x.iter_mut().next(), None);
501     /// ```
502     #[inline]
503     #[stable(feature = "rust1", since = "1.0.0")]
504     pub fn iter_mut(&mut self) -> IterMut<T> {
505         IterMut { inner: self.as_mut().ok() }
506     }
507
508     ////////////////////////////////////////////////////////////////////////
509     // Boolean operations on the values, eager and lazy
510     /////////////////////////////////////////////////////////////////////////
511
512     /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
513     ///
514     /// # Examples
515     ///
516     /// ```
517     /// let x: Result<u32, &str> = Ok(2);
518     /// let y: Result<&str, &str> = Err("late error");
519     /// assert_eq!(x.and(y), Err("late error"));
520     ///
521     /// let x: Result<u32, &str> = Err("early error");
522     /// let y: Result<&str, &str> = Ok("foo");
523     /// assert_eq!(x.and(y), Err("early error"));
524     ///
525     /// let x: Result<u32, &str> = Err("not a 2");
526     /// let y: Result<&str, &str> = Err("late error");
527     /// assert_eq!(x.and(y), Err("not a 2"));
528     ///
529     /// let x: Result<u32, &str> = Ok(2);
530     /// let y: Result<&str, &str> = Ok("different result type");
531     /// assert_eq!(x.and(y), Ok("different result type"));
532     /// ```
533     #[inline]
534     #[stable(feature = "rust1", since = "1.0.0")]
535     pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
536         match self {
537             Ok(_) => res,
538             Err(e) => Err(e),
539         }
540     }
541
542     /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
543     ///
544     /// This function can be used for control flow based on result values.
545     ///
546     /// # Examples
547     ///
548     /// ```
549     /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
550     /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
551     ///
552     /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
553     /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
554     /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
555     /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
556     /// ```
557     #[inline]
558     #[stable(feature = "rust1", since = "1.0.0")]
559     pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
560         match self {
561             Ok(t) => op(t),
562             Err(e) => Err(e),
563         }
564     }
565
566     /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
567     ///
568     /// # Examples
569     ///
570     /// ```
571     /// let x: Result<u32, &str> = Ok(2);
572     /// let y: Result<u32, &str> = Err("late error");
573     /// assert_eq!(x.or(y), Ok(2));
574     ///
575     /// let x: Result<u32, &str> = Err("early error");
576     /// let y: Result<u32, &str> = Ok(2);
577     /// assert_eq!(x.or(y), Ok(2));
578     ///
579     /// let x: Result<u32, &str> = Err("not a 2");
580     /// let y: Result<u32, &str> = Err("late error");
581     /// assert_eq!(x.or(y), Err("late error"));
582     ///
583     /// let x: Result<u32, &str> = Ok(2);
584     /// let y: Result<u32, &str> = Ok(100);
585     /// assert_eq!(x.or(y), Ok(2));
586     /// ```
587     #[inline]
588     #[stable(feature = "rust1", since = "1.0.0")]
589     pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
590         match self {
591             Ok(v) => Ok(v),
592             Err(_) => res,
593         }
594     }
595
596     /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
597     ///
598     /// This function can be used for control flow based on result values.
599     ///
600     /// # Examples
601     ///
602     /// ```
603     /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
604     /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
605     ///
606     /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
607     /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
608     /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
609     /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
610     /// ```
611     #[inline]
612     #[stable(feature = "rust1", since = "1.0.0")]
613     pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
614         match self {
615             Ok(t) => Ok(t),
616             Err(e) => op(e),
617         }
618     }
619
620     /// Unwraps a result, yielding the content of an `Ok`.
621     /// Else it returns `optb`.
622     ///
623     /// # Examples
624     ///
625     /// ```
626     /// let optb = 2;
627     /// let x: Result<u32, &str> = Ok(9);
628     /// assert_eq!(x.unwrap_or(optb), 9);
629     ///
630     /// let x: Result<u32, &str> = Err("error");
631     /// assert_eq!(x.unwrap_or(optb), optb);
632     /// ```
633     #[inline]
634     #[stable(feature = "rust1", since = "1.0.0")]
635     pub fn unwrap_or(self, optb: T) -> T {
636         match self {
637             Ok(t) => t,
638             Err(_) => optb
639         }
640     }
641
642     /// Unwraps a result, yielding the content of an `Ok`.
643     /// If the value is an `Err` then it calls `op` with its value.
644     ///
645     /// # Examples
646     ///
647     /// ```
648     /// fn count(x: &str) -> usize { x.len() }
649     ///
650     /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
651     /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
652     /// ```
653     #[inline]
654     #[stable(feature = "rust1", since = "1.0.0")]
655     pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
656         match self {
657             Ok(t) => t,
658             Err(e) => op(e)
659         }
660     }
661 }
662
663 impl<T, E: fmt::Debug> Result<T, E> {
664     /// Unwraps a result, yielding the content of an `Ok`.
665     ///
666     /// # Panics
667     ///
668     /// Panics if the value is an `Err`, with a panic message provided by the
669     /// `Err`'s value.
670     ///
671     /// # Examples
672     ///
673     /// ```
674     /// let x: Result<u32, &str> = Ok(2);
675     /// assert_eq!(x.unwrap(), 2);
676     /// ```
677     ///
678     /// ```{.should_panic}
679     /// let x: Result<u32, &str> = Err("emergency failure");
680     /// x.unwrap(); // panics with `emergency failure`
681     /// ```
682     #[inline]
683     #[stable(feature = "rust1", since = "1.0.0")]
684     pub fn unwrap(self) -> T {
685         match self {
686             Ok(t) => t,
687             Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", e),
688         }
689     }
690
691     /// Unwraps a result, yielding the content of an `Ok`.
692     ///
693     /// # Panics
694     ///
695     /// Panics if the value is an `Err`, with a panic message including the
696     /// passed message, and the content of the `Err`.
697     ///
698     /// # Examples
699     /// ```{.should_panic}
700     /// let x: Result<u32, &str> = Err("emergency failure");
701     /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
702     /// ```
703     #[inline]
704     #[stable(feature = "result_expect", since = "1.4.0")]
705     pub fn expect(self, msg: &str) -> T {
706         match self {
707             Ok(t) => t,
708             Err(e) => unwrap_failed(msg, e),
709         }
710     }
711 }
712
713 impl<T: fmt::Debug, E> Result<T, E> {
714     /// Unwraps a result, yielding the content of an `Err`.
715     ///
716     /// # Panics
717     ///
718     /// Panics if the value is an `Ok`, with a custom panic message provided
719     /// by the `Ok`'s value.
720     ///
721     /// # Examples
722     ///
723     /// ```{.should_panic}
724     /// let x: Result<u32, &str> = Ok(2);
725     /// x.unwrap_err(); // panics with `2`
726     /// ```
727     ///
728     /// ```
729     /// let x: Result<u32, &str> = Err("emergency failure");
730     /// assert_eq!(x.unwrap_err(), "emergency failure");
731     /// ```
732     #[inline]
733     #[stable(feature = "rust1", since = "1.0.0")]
734     pub fn unwrap_err(self) -> E {
735         match self {
736             Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", t),
737             Err(e) => e,
738         }
739     }
740 }
741
742 // This is a separate function to reduce the code size of the methods
743 #[inline(never)]
744 #[cold]
745 fn unwrap_failed<E: fmt::Debug>(msg: &str, error: E) -> ! {
746     panic!("{}: {:?}", msg, error)
747 }
748
749 /////////////////////////////////////////////////////////////////////////////
750 // Trait implementations
751 /////////////////////////////////////////////////////////////////////////////
752
753 #[stable(feature = "rust1", since = "1.0.0")]
754 impl<T, E> IntoIterator for Result<T, E> {
755     type Item = T;
756     type IntoIter = IntoIter<T>;
757
758     /// Returns a consuming iterator over the possibly contained value.
759     ///
760     /// # Examples
761     ///
762     /// ```
763     /// let x: Result<u32, &str> = Ok(5);
764     /// let v: Vec<u32> = x.into_iter().collect();
765     /// assert_eq!(v, [5]);
766     ///
767     /// let x: Result<u32, &str> = Err("nothing!");
768     /// let v: Vec<u32> = x.into_iter().collect();
769     /// assert_eq!(v, []);
770     /// ```
771     #[inline]
772     fn into_iter(self) -> IntoIter<T> {
773         IntoIter { inner: self.ok() }
774     }
775 }
776
777 #[stable(since = "1.4.0", feature = "result_iter")]
778 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
779     type Item = &'a T;
780     type IntoIter = Iter<'a, T>;
781
782     fn into_iter(self) -> Iter<'a, T> {
783         self.iter()
784     }
785 }
786
787 #[stable(since = "1.4.0", feature = "result_iter")]
788 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
789     type Item = &'a mut T;
790     type IntoIter = IterMut<'a, T>;
791
792     fn into_iter(mut self) -> IterMut<'a, T> {
793         self.iter_mut()
794     }
795 }
796
797 /////////////////////////////////////////////////////////////////////////////
798 // The Result Iterators
799 /////////////////////////////////////////////////////////////////////////////
800
801 /// An iterator over a reference to the `Ok` variant of a `Result`.
802 #[stable(feature = "rust1", since = "1.0.0")]
803 pub struct Iter<'a, T: 'a> { inner: Option<&'a T> }
804
805 #[stable(feature = "rust1", since = "1.0.0")]
806 impl<'a, T> Iterator for Iter<'a, T> {
807     type Item = &'a T;
808
809     #[inline]
810     fn next(&mut self) -> Option<&'a T> { self.inner.take() }
811     #[inline]
812     fn size_hint(&self) -> (usize, Option<usize>) {
813         let n = if self.inner.is_some() {1} else {0};
814         (n, Some(n))
815     }
816 }
817
818 #[stable(feature = "rust1", since = "1.0.0")]
819 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
820     #[inline]
821     fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
822 }
823
824 #[stable(feature = "rust1", since = "1.0.0")]
825 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
826
827 #[stable(feature = "rust1", since = "1.0.0")]
828 impl<'a, T> Clone for Iter<'a, T> {
829     fn clone(&self) -> Iter<'a, T> { Iter { inner: self.inner } }
830 }
831
832 /// An iterator over a mutable reference to the `Ok` variant of a `Result`.
833 #[stable(feature = "rust1", since = "1.0.0")]
834 pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
835
836 #[stable(feature = "rust1", since = "1.0.0")]
837 impl<'a, T> Iterator for IterMut<'a, T> {
838     type Item = &'a mut T;
839
840     #[inline]
841     fn next(&mut self) -> Option<&'a mut T> { self.inner.take() }
842     #[inline]
843     fn size_hint(&self) -> (usize, Option<usize>) {
844         let n = if self.inner.is_some() {1} else {0};
845         (n, Some(n))
846     }
847 }
848
849 #[stable(feature = "rust1", since = "1.0.0")]
850 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
851     #[inline]
852     fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
853 }
854
855 #[stable(feature = "rust1", since = "1.0.0")]
856 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
857
858 /// An iterator over the value in a `Ok` variant of a `Result`.
859 #[stable(feature = "rust1", since = "1.0.0")]
860 pub struct IntoIter<T> { inner: Option<T> }
861
862 #[stable(feature = "rust1", since = "1.0.0")]
863 impl<T> Iterator for IntoIter<T> {
864     type Item = T;
865
866     #[inline]
867     fn next(&mut self) -> Option<T> { self.inner.take() }
868     #[inline]
869     fn size_hint(&self) -> (usize, Option<usize>) {
870         let n = if self.inner.is_some() {1} else {0};
871         (n, Some(n))
872     }
873 }
874
875 #[stable(feature = "rust1", since = "1.0.0")]
876 impl<T> DoubleEndedIterator for IntoIter<T> {
877     #[inline]
878     fn next_back(&mut self) -> Option<T> { self.inner.take() }
879 }
880
881 #[stable(feature = "rust1", since = "1.0.0")]
882 impl<T> ExactSizeIterator for IntoIter<T> {}
883
884 /////////////////////////////////////////////////////////////////////////////
885 // FromIterator
886 /////////////////////////////////////////////////////////////////////////////
887
888 #[stable(feature = "rust1", since = "1.0.0")]
889 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
890     /// Takes each element in the `Iterator`: if it is an `Err`, no further
891     /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
892     /// container with the values of each `Result` is returned.
893     ///
894     /// Here is an example which increments every integer in a vector,
895     /// checking for overflow:
896     ///
897     /// ```
898     /// use std::u32;
899     ///
900     /// let v = vec!(1, 2);
901     /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|&x: &u32|
902     ///     if x == u32::MAX { Err("Overflow!") }
903     ///     else { Ok(x + 1) }
904     /// ).collect();
905     /// assert!(res == Ok(vec!(2, 3)));
906     /// ```
907     #[inline]
908     fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
909         // FIXME(#11084): This could be replaced with Iterator::scan when this
910         // performance bug is closed.
911
912         struct Adapter<Iter, E> {
913             iter: Iter,
914             err: Option<E>,
915         }
916
917         impl<T, E, Iter: Iterator<Item=Result<T, E>>> Iterator for Adapter<Iter, E> {
918             type Item = T;
919
920             #[inline]
921             fn next(&mut self) -> Option<T> {
922                 match self.iter.next() {
923                     Some(Ok(value)) => Some(value),
924                     Some(Err(err)) => {
925                         self.err = Some(err);
926                         None
927                     }
928                     None => None,
929                 }
930             }
931         }
932
933         let mut adapter = Adapter { iter: iter.into_iter(), err: None };
934         let v: V = FromIterator::from_iter(adapter.by_ref());
935
936         match adapter.err {
937             Some(err) => Err(err),
938             None => Ok(v),
939         }
940     }
941 }