]> git.lizzy.rs Git - rust.git/blob - src/libcore/result.rs
auto merge of #19628 : jbranchaud/rust/add-string-as-string-doctest, r=steveklabnik
[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 //! #[deriving(Show)]
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::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::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 by 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::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::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::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::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 //!     match file.write_line(format!("name: {}", info.name).as_slice()) {
182 //!         Ok(_) => (),
183 //!         Err(e) => return Err(e)
184 //!     }
185 //!     match file.write_line(format!("age: {}", info.age).as_slice()) {
186 //!         Ok(_) => (),
187 //!         Err(e) => return Err(e)
188 //!     }
189 //!     return file.write_line(format!("rating: {}", info.rating).as_slice());
190 //! }
191 //! ```
192 //!
193 //! With this:
194 //!
195 //! ```
196 //! use std::io::{File, Open, Write, IoError};
197 //!
198 //! struct Info {
199 //!     name: String,
200 //!     age: int,
201 //!     rating: int
202 //! }
203 //!
204 //! fn write_info(info: &Info) -> Result<(), IoError> {
205 //!     let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
206 //!     // Early return on error
207 //!     try!(file.write_line(format!("name: {}", info.name).as_slice()));
208 //!     try!(file.write_line(format!("age: {}", info.age).as_slice()));
209 //!     try!(file.write_line(format!("rating: {}", info.rating).as_slice()));
210 //!     return Ok(());
211 //! }
212 //! ```
213 //!
214 //! *It's much nicer!*
215 //!
216 //! Wrapping an expression in `try!` will result in the unwrapped
217 //! success (`Ok`) value, unless the result is `Err`, in which case
218 //! `Err` is returned early from the enclosing function. Its simple definition
219 //! makes it clear:
220 //!
221 //! ```
222 //! # #![feature(macro_rules)]
223 //! macro_rules! try(
224 //!     ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
225 //! )
226 //! # fn main() { }
227 //! ```
228 //!
229 //! `try!` is imported by the prelude, and is available everywhere.
230
231 #![stable]
232
233 use self::Result::*;
234
235 use kinds::Copy;
236 use std::fmt::Show;
237 use slice;
238 use slice::AsSlice;
239 use iter::{Iterator, IteratorExt, DoubleEndedIterator, FromIterator, ExactSizeIterator};
240 use option::Option;
241 use option::Option::{None, Some};
242
243 /// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
244 ///
245 /// See the [`std::result`](index.html) module documentation for details.
246 #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Show)]
247 #[must_use]
248 #[stable]
249 pub enum Result<T, E> {
250     /// Contains the success value
251     Ok(T),
252
253     /// Contains the error value
254     Err(E)
255 }
256
257 /////////////////////////////////////////////////////////////////////////////
258 // Type implementation
259 /////////////////////////////////////////////////////////////////////////////
260
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]
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]
299     pub fn is_err(&self) -> bool {
300         !self.is_ok()
301     }
302
303
304     /////////////////////////////////////////////////////////////////////////
305     // Adapter for each variant
306     /////////////////////////////////////////////////////////////////////////
307
308     /// Convert from `Result<T, E>` to `Option<T>`
309     ///
310     /// Converts `self` into an `Option<T>`, consuming `self`,
311     /// and discarding the error, if any.
312     ///
313     /// # Example
314     ///
315     /// ```
316     /// let x: Result<uint, &str> = Ok(2);
317     /// assert_eq!(x.ok(), Some(2));
318     ///
319     /// let x: Result<uint, &str> = Err("Nothing here");
320     /// assert_eq!(x.ok(), None);
321     /// ```
322     #[inline]
323     #[stable]
324     pub fn ok(self) -> Option<T> {
325         match self {
326             Ok(x)  => Some(x),
327             Err(_) => None,
328         }
329     }
330
331     /// Convert from `Result<T, E>` to `Option<E>`
332     ///
333     /// Converts `self` into an `Option<T>`, consuming `self`,
334     /// and discarding the value, if any.
335     ///
336     /// # Example
337     ///
338     /// ```
339     /// let x: Result<uint, &str> = Ok(2);
340     /// assert_eq!(x.err(), None);
341     ///
342     /// let x: Result<uint, &str> = Err("Nothing here");
343     /// assert_eq!(x.err(), Some("Nothing here"));
344     /// ```
345     #[inline]
346     #[stable]
347     pub fn err(self) -> Option<E> {
348         match self {
349             Ok(_)  => None,
350             Err(x) => Some(x),
351         }
352     }
353
354     /////////////////////////////////////////////////////////////////////////
355     // Adapter for working with references
356     /////////////////////////////////////////////////////////////////////////
357
358     /// Convert from `Result<T, E>` to `Result<&T, &E>`
359     ///
360     /// Produces a new `Result`, containing a reference
361     /// into the original, leaving the original in place.
362     ///
363     /// ```
364     /// let x: Result<uint, &str> = Ok(2);
365     /// assert_eq!(x.as_ref(), Ok(&2));
366     ///
367     /// let x: Result<uint, &str> = Err("Error");
368     /// assert_eq!(x.as_ref(), Err(&"Error"));
369     /// ```
370     #[inline]
371     #[stable]
372     pub fn as_ref<'r>(&'r self) -> Result<&'r T, &'r E> {
373         match *self {
374             Ok(ref x) => Ok(x),
375             Err(ref x) => Err(x),
376         }
377     }
378
379     /// Convert from `Result<T, E>` to `Result<&mut T, &mut E>`
380     ///
381     /// ```
382     /// fn mutate(r: &mut Result<int, int>) {
383     ///     match r.as_mut() {
384     ///         Ok(&ref mut v) => *v = 42,
385     ///         Err(&ref mut e) => *e = 0,
386     ///     }
387     /// }
388     ///
389     /// let mut x: Result<int, int> = Ok(2);
390     /// mutate(&mut x);
391     /// assert_eq!(x.unwrap(), 42);
392     ///
393     /// let mut x: Result<int, int> = Err(13);
394     /// mutate(&mut x);
395     /// assert_eq!(x.unwrap_err(), 0);
396     /// ```
397     #[inline]
398     #[unstable = "waiting for mut conventions"]
399     pub fn as_mut<'r>(&'r mut self) -> Result<&'r mut T, &'r mut E> {
400         match *self {
401             Ok(ref mut x) => Ok(x),
402             Err(ref mut x) => Err(x),
403         }
404     }
405
406     /// Convert from `Result<T, E>` to `&mut [T]` (without copying)
407     ///
408     /// ```
409     /// let mut x: Result<&str, uint> = Ok("Gold");
410     /// {
411     ///     let v = x.as_mut_slice();
412     ///     assert!(v == ["Gold"]);
413     ///     v[0] = "Silver";
414     ///     assert!(v == ["Silver"]);
415     /// }
416     /// assert_eq!(x, Ok("Silver"));
417     ///
418     /// let mut x: Result<&str, uint> = Err(45);
419     /// assert!(x.as_mut_slice().is_empty());
420     /// ```
421     #[inline]
422     #[unstable = "waiting for mut conventions"]
423     pub fn as_mut_slice<'r>(&'r mut self) -> &'r 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::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     ///         from_str::<int>(line.as_slice().trim_right()).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     #[unstable = "waiting for unboxed closures"]
469     pub fn map<U>(self, op: |T| -> U) -> 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: uint) -> String { format!("error code: {}", x) }
486     ///
487     /// let x: Result<uint, uint> = Ok(2u);
488     /// assert_eq!(x.map_err(stringify), Ok(2u));
489     ///
490     /// let x: Result<uint, uint> = Err(13);
491     /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
492     /// ```
493     #[inline]
494     #[unstable = "waiting for unboxed closures"]
495     pub fn map_err<F>(self, op: |E| -> F) -> Result<T,F> {
496         match self {
497           Ok(t) => Ok(t),
498           Err(e) => Err(op(e))
499         }
500     }
501
502
503     /////////////////////////////////////////////////////////////////////////
504     // Iterator constructors
505     /////////////////////////////////////////////////////////////////////////
506
507     /// Returns an iterator over the possibly contained value.
508     ///
509     /// # Example
510     ///
511     /// ```
512     /// let x: Result<uint, &str> = Ok(7);
513     /// assert_eq!(x.iter().next(), Some(&7));
514     ///
515     /// let x: Result<uint, &str> = Err("nothing!");
516     /// assert_eq!(x.iter().next(), None);
517     /// ```
518     #[inline]
519     #[unstable = "waiting for iterator conventions"]
520     pub fn iter<'r>(&'r self) -> Item<&'r T> {
521         Item{opt: self.as_ref().ok()}
522     }
523
524     /// Returns a mutable iterator over the possibly contained value.
525     ///
526     /// # Example
527     ///
528     /// ```
529     /// let mut x: Result<uint, &str> = Ok(7);
530     /// match x.iter_mut().next() {
531     ///     Some(&ref mut x) => *x = 40,
532     ///     None => {},
533     /// }
534     /// assert_eq!(x, Ok(40));
535     ///
536     /// let mut x: Result<uint, &str> = Err("nothing!");
537     /// assert_eq!(x.iter_mut().next(), None);
538     /// ```
539     #[inline]
540     #[unstable = "waiting for iterator conventions"]
541     pub fn iter_mut<'r>(&'r mut self) -> Item<&'r mut T> {
542         Item{opt: self.as_mut().ok()}
543     }
544
545     /// Returns a consuming iterator over the possibly contained value.
546     ///
547     /// # Example
548     ///
549     /// ```
550     /// let x: Result<uint, &str> = Ok(5);
551     /// let v: Vec<uint> = x.into_iter().collect();
552     /// assert_eq!(v, vec![5u]);
553     ///
554     /// let x: Result<uint, &str> = Err("nothing!");
555     /// let v: Vec<uint> = x.into_iter().collect();
556     /// assert_eq!(v, vec![]);
557     /// ```
558     #[inline]
559     #[unstable = "waiting for iterator conventions"]
560     pub fn into_iter(self) -> Item<T> {
561         Item{opt: self.ok()}
562     }
563
564     ////////////////////////////////////////////////////////////////////////
565     // Boolean operations on the values, eager and lazy
566     /////////////////////////////////////////////////////////////////////////
567
568     /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
569     ///
570     /// # Example
571     ///
572     /// ```
573     /// let x: Result<uint, &str> = Ok(2);
574     /// let y: Result<&str, &str> = Err("late error");
575     /// assert_eq!(x.and(y), Err("late error"));
576     ///
577     /// let x: Result<uint, &str> = Err("early error");
578     /// let y: Result<&str, &str> = Ok("foo");
579     /// assert_eq!(x.and(y), Err("early error"));
580     ///
581     /// let x: Result<uint, &str> = Err("not a 2");
582     /// let y: Result<&str, &str> = Err("late error");
583     /// assert_eq!(x.and(y), Err("not a 2"));
584     ///
585     /// let x: Result<uint, &str> = Ok(2);
586     /// let y: Result<&str, &str> = Ok("different result type");
587     /// assert_eq!(x.and(y), Ok("different result type"));
588     /// ```
589     #[inline]
590     #[stable]
591     pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
592         match self {
593             Ok(_) => res,
594             Err(e) => Err(e),
595         }
596     }
597
598     /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
599     ///
600     /// This function can be used for control flow based on result values.
601     ///
602     /// # Example
603     ///
604     /// ```
605     /// fn sq(x: uint) -> Result<uint, uint> { Ok(x * x) }
606     /// fn err(x: uint) -> Result<uint, uint> { Err(x) }
607     ///
608     /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
609     /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
610     /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
611     /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
612     /// ```
613     #[inline]
614     #[unstable = "waiting for unboxed closures"]
615     pub fn and_then<U>(self, op: |T| -> Result<U, E>) -> Result<U, E> {
616         match self {
617             Ok(t) => op(t),
618             Err(e) => Err(e),
619         }
620     }
621
622     /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
623     ///
624     /// # Example
625     ///
626     /// ```
627     /// let x: Result<uint, &str> = Ok(2);
628     /// let y: Result<uint, &str> = Err("late error");
629     /// assert_eq!(x.or(y), Ok(2));
630     ///
631     /// let x: Result<uint, &str> = Err("early error");
632     /// let y: Result<uint, &str> = Ok(2);
633     /// assert_eq!(x.or(y), Ok(2));
634     ///
635     /// let x: Result<uint, &str> = Err("not a 2");
636     /// let y: Result<uint, &str> = Err("late error");
637     /// assert_eq!(x.or(y), Err("late error"));
638     ///
639     /// let x: Result<uint, &str> = Ok(2);
640     /// let y: Result<uint, &str> = Ok(100);
641     /// assert_eq!(x.or(y), Ok(2));
642     /// ```
643     #[inline]
644     #[stable]
645     pub fn or(self, res: Result<T, E>) -> Result<T, E> {
646         match self {
647             Ok(_) => self,
648             Err(_) => res,
649         }
650     }
651
652     /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
653     ///
654     /// This function can be used for control flow based on result values.
655     ///
656     /// # Example
657     ///
658     /// ```
659     /// fn sq(x: uint) -> Result<uint, uint> { Ok(x * x) }
660     /// fn err(x: uint) -> Result<uint, uint> { Err(x) }
661     ///
662     /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
663     /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
664     /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
665     /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
666     /// ```
667     #[inline]
668     #[unstable = "waiting for unboxed closures"]
669     pub fn or_else<F>(self, op: |E| -> Result<T, F>) -> Result<T, F> {
670         match self {
671             Ok(t) => Ok(t),
672             Err(e) => op(e),
673         }
674     }
675
676     /// Unwraps a result, yielding the content of an `Ok`.
677     /// Else it returns `optb`.
678     ///
679     /// # Example
680     ///
681     /// ```
682     /// let optb = 2u;
683     /// let x: Result<uint, &str> = Ok(9u);
684     /// assert_eq!(x.unwrap_or(optb), 9u);
685     ///
686     /// let x: Result<uint, &str> = Err("error");
687     /// assert_eq!(x.unwrap_or(optb), optb);
688     /// ```
689     #[inline]
690     #[unstable = "waiting for conventions"]
691     pub fn unwrap_or(self, optb: T) -> T {
692         match self {
693             Ok(t) => t,
694             Err(_) => optb
695         }
696     }
697
698     /// Unwraps a result, yielding the content of an `Ok`.
699     /// If the value is an `Err` then it calls `op` with its value.
700     ///
701     /// # Example
702     ///
703     /// ```
704     /// fn count(x: &str) -> uint { x.len() }
705     ///
706     /// assert_eq!(Ok(2u).unwrap_or_else(count), 2u);
707     /// assert_eq!(Err("foo").unwrap_or_else(count), 3u);
708     /// ```
709     #[inline]
710     #[unstable = "waiting for conventions"]
711     pub fn unwrap_or_else(self, op: |E| -> T) -> T {
712         match self {
713             Ok(t) => t,
714             Err(e) => op(e)
715         }
716     }
717 }
718
719 impl<T, E: Show> 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<uint, &str> = Ok(2u);
731     /// assert_eq!(x.unwrap(), 2u);
732     /// ```
733     ///
734     /// ```{.should_fail}
735     /// let x: Result<uint, &str> = Err("emergency failure");
736     /// x.unwrap(); // panics with `emergency failure`
737     /// ```
738     #[inline]
739     #[unstable = "waiting for conventions"]
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 impl<T: Show, E> Result<T, E> {
750     /// Unwraps a result, yielding the content of an `Err`.
751     ///
752     /// # Panics
753     ///
754     /// Panics if the value is an `Ok`, with a custom panic message provided
755     /// by the `Ok`'s value.
756     ///
757     /// # Example
758     ///
759     /// ```{.should_fail}
760     /// let x: Result<uint, &str> = Ok(2u);
761     /// x.unwrap_err(); // panics with `2`
762     /// ```
763     ///
764     /// ```
765     /// let x: Result<uint, &str> = Err("emergency failure");
766     /// assert_eq!(x.unwrap_err(), "emergency failure");
767     /// ```
768     #[inline]
769     #[unstable = "waiting for conventions"]
770     pub fn unwrap_err(self) -> E {
771         match self {
772             Ok(t) =>
773                 panic!("called `Result::unwrap_err()` on an `Ok` value: {}", t),
774             Err(e) => e
775         }
776     }
777 }
778
779 /////////////////////////////////////////////////////////////////////////////
780 // Trait implementations
781 /////////////////////////////////////////////////////////////////////////////
782
783 impl<T, E> AsSlice<T> for Result<T, E> {
784     /// Convert from `Result<T, E>` to `&[T]` (without copying)
785     #[inline]
786     #[stable]
787     fn as_slice<'a>(&'a self) -> &'a [T] {
788         match *self {
789             Ok(ref x) => slice::ref_slice(x),
790             Err(_) => {
791                 // work around lack of implicit coercion from fixed-size array to slice
792                 let emp: &[_] = &[];
793                 emp
794             }
795         }
796     }
797 }
798
799 /////////////////////////////////////////////////////////////////////////////
800 // The Result Iterator
801 /////////////////////////////////////////////////////////////////////////////
802
803 /// A `Result` iterator that yields either one or zero elements
804 ///
805 /// The `Item` iterator is returned by the `iter`, `iter_mut` and `into_iter`
806 /// methods on `Result`.
807 #[deriving(Clone)]
808 #[unstable = "waiting for iterator conventions"]
809 pub struct Item<T> {
810     opt: Option<T>
811 }
812
813 impl<T> Iterator<T> for Item<T> {
814     #[inline]
815     fn next(&mut self) -> Option<T> {
816         self.opt.take()
817     }
818
819     #[inline]
820     fn size_hint(&self) -> (uint, Option<uint>) {
821         match self.opt {
822             Some(_) => (1, Some(1)),
823             None => (0, Some(0)),
824         }
825     }
826 }
827
828 impl<A> DoubleEndedIterator<A> for Item<A> {
829     #[inline]
830     fn next_back(&mut self) -> Option<A> {
831         self.opt.take()
832     }
833 }
834
835 impl<A> ExactSizeIterator<A> for Item<A> {}
836
837 /////////////////////////////////////////////////////////////////////////////
838 // FromIterator
839 /////////////////////////////////////////////////////////////////////////////
840
841 #[stable]
842 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
843     /// Takes each element in the `Iterator`: if it is an `Err`, no further
844     /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
845     /// container with the values of each `Result` is returned.
846     ///
847     /// Here is an example which increments every integer in a vector,
848     /// checking for overflow:
849     ///
850     /// ```rust
851     /// use std::uint;
852     ///
853     /// let v = vec!(1u, 2u);
854     /// let res: Result<Vec<uint>, &'static str> = v.iter().map(|&x: &uint|
855     ///     if x == uint::MAX { Err("Overflow!") }
856     ///     else { Ok(x + 1) }
857     /// ).collect();
858     /// assert!(res == Ok(vec!(2u, 3u)));
859     /// ```
860     #[inline]
861     fn from_iter<I: Iterator<Result<A, E>>>(iter: I) -> Result<V, E> {
862         // FIXME(#11084): This could be replaced with Iterator::scan when this
863         // performance bug is closed.
864
865         struct Adapter<Iter, E> {
866             iter: Iter,
867             err: Option<E>,
868         }
869
870         impl<T, E, Iter: Iterator<Result<T, E>>> Iterator<T> for Adapter<Iter, E> {
871             #[inline]
872             fn next(&mut self) -> Option<T> {
873                 match self.iter.next() {
874                     Some(Ok(value)) => Some(value),
875                     Some(Err(err)) => {
876                         self.err = Some(err);
877                         None
878                     }
879                     None => None,
880                 }
881             }
882         }
883
884         let mut adapter = Adapter { iter: iter, err: None };
885         let v: V = FromIterator::from_iter(adapter.by_ref());
886
887         match adapter.err {
888             Some(err) => Err(err),
889             None => Ok(v),
890         }
891     }
892 }
893
894 /////////////////////////////////////////////////////////////////////////////
895 // FromIterator
896 /////////////////////////////////////////////////////////////////////////////
897
898 /// Perform a fold operation over the result values from an iterator.
899 ///
900 /// If an `Err` is encountered, it is immediately returned.
901 /// Otherwise, the folded value is returned.
902 #[inline]
903 #[experimental]
904 pub fn fold<T,
905             V,
906             E,
907             Iter: Iterator<Result<T, E>>>(
908             mut iterator: Iter,
909             mut init: V,
910             f: |V, T| -> V)
911             -> Result<V, E> {
912     for t in iterator {
913         match t {
914             Ok(v) => init = f(init, v),
915             Err(u) => return Err(u)
916         }
917     }
918     Ok(init)
919 }
920
921 #[cfg(not(stage0))]
922 impl<T:Copy,U:Copy> Copy for Result<T,U> {}
923