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