result.rs 28.0 KB
Newer Older
C
Chris Wong 已提交
1
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 3 4 5 6 7 8 9 10
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

11 12
//! Error handling with the `Result` type
//!
13
//! `Result<T, E>` is the type used for returning and propagating
14 15 16 17
//! errors. It is an enum with the variants, `Ok(T)`, representing
//! success and containing a value, and `Err(E)`, representing error
//! and containing an error value.
//!
J
Jonas Hietala 已提交
18
//! ```
19 20 21 22
//! enum Result<T, E> {
//!    Ok(T),
//!    Err(E)
//! }
J
Jonas Hietala 已提交
23
//! ```
24 25 26
//!
//! Functions return `Result` whenever errors are expected and
//! recoverable. In the `std` crate `Result` is most prominently used
A
Alex Crichton 已提交
27
//! for [I/O](../../std/io/index.html).
28 29 30 31
//!
//! A simple function returning `Result` might be
//! defined and used like so:
//!
J
Jonas Hietala 已提交
32
//! ```
33
//! #[derive(Show)]
34 35 36 37
//! enum Version { Version1, Version2 }
//!
//! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
//!     if header.len() < 1 {
B
Brian Anderson 已提交
38
//!         return Err("invalid header length");
39 40
//!     }
//!     match header[0] {
S
Steven Fackler 已提交
41 42
//!         1 => Ok(Version::Version1),
//!         2 => Ok(Version::Version2),
43 44 45 46 47 48 49
//!         _ => Err("invalid version")
//!     }
//! }
//!
//! let version = parse_version(&[1, 2, 3, 4]);
//! match version {
//!     Ok(v) => {
50
//!         println!("working with version: {:?}", v);
51 52
//!     }
//!     Err(e) => {
53
//!         println!("error parsing header: {:?}", e);
54 55
//!     }
//! }
J
Jonas Hietala 已提交
56
//! ```
57 58 59
//!
//! Pattern matching on `Result`s is clear and straightforward for
//! simple cases, but `Result` comes with some convenience methods
N
Nicholas Bishop 已提交
60
//! that make working with it more succinct.
61
//!
J
Jonas Hietala 已提交
62
//! ```
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
//! let good_result: Result<int, int> = Ok(10);
//! let bad_result: Result<int, int> = Err(10);
//!
//! // The `is_ok` and `is_err` methods do what they say.
//! assert!(good_result.is_ok() && !good_result.is_err());
//! assert!(bad_result.is_err() && !bad_result.is_ok());
//!
//! // `map` consumes the `Result` and produces another.
//! let good_result: Result<int, int> = good_result.map(|i| i + 1);
//! let bad_result: Result<int, int> = bad_result.map(|i| i - 1);
//!
//! // Use `and_then` to continue the computation.
//! let good_result: Result<bool, int> = good_result.and_then(|i| Ok(i == 11));
//!
//! // Use `or_else` to handle the error.
//! let bad_result: Result<int, int> = bad_result.or_else(|i| Ok(11));
//!
B
Brian Anderson 已提交
80
//! // Consume the result and return the contents with `unwrap`.
81
//! let final_awesome_result = good_result.ok().unwrap();
J
Jonas Hietala 已提交
82
//! ```
83 84 85
//!
//! # Results must be used
//!
B
Brian Anderson 已提交
86 87 88 89 90 91 92
//! A common problem with using return values to indicate errors is
//! that it is easy to ignore the return value, thus failing to handle
//! the error. Result is annotated with the #[must_use] attribute,
//! which will cause the compiler to issue a warning when a Result
//! value is ignored. This makes `Result` especially useful with
//! functions that may encounter errors but don't otherwise return a
//! useful value.
93 94 95 96
//!
//! Consider the `write_line` method defined for I/O types
//! by the [`Writer`](../io/trait.Writer.html) trait:
//!
J
Jonas Hietala 已提交
97
//! ```
98 99 100 101 102
//! use std::io::IoError;
//!
//! trait Writer {
//!     fn write_line(&mut self, s: &str) -> Result<(), IoError>;
//! }
J
Jonas Hietala 已提交
103
//! ```
104 105
//!
//! *Note: The actual definition of `Writer` uses `IoResult`, which
J
Joseph Crail 已提交
106
//! is just a synonym for `Result<T, IoError>`.*
107
//!
108
//! This method doesn't produce a value, but the write may
109 110 111
//! fail. It's crucial to handle the error case, and *not* write
//! something like this:
//!
J
Jonas Hietala 已提交
112
//! ```{.ignore}
113 114 115 116 117 118 119
//! use std::io::{File, Open, Write};
//!
//! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
//! // If `write_line` errors, then we'll never know, because the return
//! // value is ignored.
//! file.write_line("important message");
//! drop(file);
J
Jonas Hietala 已提交
120
//! ```
121
//!
122
//! If you *do* write that in Rust, the compiler will give you a
123 124 125
//! warning (by default, controlled by the `unused_must_use` lint).
//!
//! You might instead, if you don't want to handle the error, simply
S
Steve Klabnik 已提交
126 127
//! panic, by converting to an `Option` with `ok`, then asserting
//! success with `expect`. This will panic if the write fails, proving
128 129
//! a marginally useful message indicating why:
//!
J
Jonas Hietala 已提交
130
//! ```{.no_run}
131 132 133 134 135
//! use std::io::{File, Open, Write};
//!
//! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
//! file.write_line("important message").ok().expect("failed to write message");
//! drop(file);
J
Jonas Hietala 已提交
136
//! ```
137 138 139
//!
//! You might also simply assert success:
//!
J
Jonas Hietala 已提交
140
//! ```{.no_run}
141 142 143 144 145
//! # use std::io::{File, Open, Write};
//!
//! # let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
//! assert!(file.write_line("important message").is_ok());
//! # drop(file);
J
Jonas Hietala 已提交
146
//! ```
147 148 149
//!
//! Or propagate the error up the call stack with `try!`:
//!
J
Jonas Hietala 已提交
150
//! ```
151 152 153 154 155 156 157
//! # use std::io::{File, Open, Write, IoError};
//! fn write_message() -> Result<(), IoError> {
//!     let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
//!     try!(file.write_line("important message"));
//!     drop(file);
//!     return Ok(());
//! }
J
Jonas Hietala 已提交
158
//! ```
159 160 161 162 163 164 165 166 167 168
//!
//! # The `try!` macro
//!
//! When writing code that calls many functions that return the
//! `Result` type, the error handling can be tedious.  The `try!`
//! macro hides some of the boilerplate of propagating errors up the
//! call stack.
//!
//! It replaces this:
//!
J
Jonas Hietala 已提交
169
//! ```
170 171
//! use std::io::{File, Open, Write, IoError};
//!
172
//! struct Info {
173
//!     name: String,
174 175 176
//!     age: int,
//!     rating: int
//! }
177 178 179 180
//!
//! fn write_info(info: &Info) -> Result<(), IoError> {
//!     let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
//!     // Early return on error
181 182
//!     if let Err(e) = file.write_line(format!("name: {}", info.name).as_slice()) {
//!         return Err(e)
183
//!     }
184 185
//!     if let Err(e) = file.write_line(format!("age: {}", info.age).as_slice()) {
//!         return Err(e)
186
//!     }
187
//!     return file.write_line(format!("rating: {}", info.rating).as_slice());
188
//! }
J
Jonas Hietala 已提交
189
//! ```
190 191 192
//!
//! With this:
//!
J
Jonas Hietala 已提交
193
//! ```
194 195
//! use std::io::{File, Open, Write, IoError};
//!
196
//! struct Info {
197
//!     name: String,
198 199 200
//!     age: int,
//!     rating: int
//! }
201 202 203 204
//!
//! fn write_info(info: &Info) -> Result<(), IoError> {
//!     let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
//!     // Early return on error
205 206 207
//!     try!(file.write_line(format!("name: {}", info.name).as_slice()));
//!     try!(file.write_line(format!("age: {}", info.age).as_slice()));
//!     try!(file.write_line(format!("rating: {}", info.rating).as_slice()));
208 209
//!     return Ok(());
//! }
J
Jonas Hietala 已提交
210
//! ```
211 212 213 214 215 216 217 218
//!
//! *It's much nicer!*
//!
//! Wrapping an expression in `try!` will result in the unwrapped
//! success (`Ok`) value, unless the result is `Err`, in which case
//! `Err` is returned early from the enclosing function. Its simple definition
//! makes it clear:
//!
J
Jonas Hietala 已提交
219
//! ```
220
//! macro_rules! try {
221
//!     ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
222
//! }
J
Jonas Hietala 已提交
223
//! ```
224 225
//!
//! `try!` is imported by the prelude, and is available everywhere.
226

A
Aaron Turon 已提交
227 228
#![stable]

229
use self::Result::{Ok, Err};
S
Steven Fackler 已提交
230

231
use clone::Clone;
232
use fmt::Debug;
A
Aaron Turon 已提交
233
use iter::{Iterator, IteratorExt, DoubleEndedIterator, FromIterator, ExactSizeIterator};
234
use ops::{FnMut, FnOnce};
235
use option::Option::{self, None, Some};
236 237
use slice::AsSlice;
use slice;
238 239

/// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
240 241
///
/// See the [`std::result`](index.html) module documentation for details.
242
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Show, Hash)]
243
#[must_use]
A
Aaron Turon 已提交
244
#[stable]
245
pub enum Result<T, E> {
M
Marvin Löbel 已提交
246
    /// Contains the success value
247
    #[stable]
248
    Ok(T),
M
Marvin Löbel 已提交
249

250
    /// Contains the error value
251
    #[stable]
252
    Err(E)
253 254
}

255 256 257 258
/////////////////////////////////////////////////////////////////////////////
// Type implementation
/////////////////////////////////////////////////////////////////////////////

259
#[stable]
M
Marvin Löbel 已提交
260
impl<T, E> Result<T, E> {
261 262 263
    /////////////////////////////////////////////////////////////////////////
    // Querying the contained values
    /////////////////////////////////////////////////////////////////////////
264

265
    /// Returns true if the result is `Ok`
266 267 268
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
269 270 271 272 273 274 275
    /// ```
    /// let x: Result<int, &str> = Ok(-3);
    /// assert_eq!(x.is_ok(), true);
    ///
    /// let x: Result<int, &str> = Err("Some error message");
    /// assert_eq!(x.is_ok(), false);
    /// ```
276
    #[inline]
A
Aaron Turon 已提交
277
    #[stable]
E
Erick Tryzelaar 已提交
278 279 280 281 282 283
    pub fn is_ok(&self) -> bool {
        match *self {
            Ok(_) => true,
            Err(_) => false
        }
    }
284

285
    /// Returns true if the result is `Err`
286 287 288
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
289 290 291
    /// ```
    /// let x: Result<int, &str> = Ok(-3);
    /// assert_eq!(x.is_err(), false);
292
    ///
J
Jonas Hietala 已提交
293 294 295
    /// let x: Result<int, &str> = Err("Some error message");
    /// assert_eq!(x.is_err(), true);
    /// ```
296
    #[inline]
A
Aaron Turon 已提交
297
    #[stable]
E
Erick Tryzelaar 已提交
298 299 300
    pub fn is_err(&self) -> bool {
        !self.is_ok()
    }
301

302
    /////////////////////////////////////////////////////////////////////////
M
Marvin Löbel 已提交
303
    // Adapter for each variant
304 305
    /////////////////////////////////////////////////////////////////////////

M
Marvin Löbel 已提交
306
    /// Convert from `Result<T, E>` to `Option<T>`
307 308 309 310
    ///
    /// Converts `self` into an `Option<T>`, consuming `self`,
    /// and discarding the error, if any.
    ///
J
Jonas Hietala 已提交
311
    /// # Example
312
    ///
J
Jonas Hietala 已提交
313 314 315
    /// ```
    /// let x: Result<uint, &str> = Ok(2);
    /// assert_eq!(x.ok(), Some(2));
316
    ///
J
Jonas Hietala 已提交
317 318 319
    /// let x: Result<uint, &str> = Err("Nothing here");
    /// assert_eq!(x.ok(), None);
    /// ```
320
    #[inline]
A
Aaron Turon 已提交
321
    #[stable]
M
Marvin Löbel 已提交
322
    pub fn ok(self) -> Option<T> {
323
        match self {
M
Marvin Löbel 已提交
324 325
            Ok(x)  => Some(x),
            Err(_) => None,
326 327
        }
    }
328

M
Marvin Löbel 已提交
329
    /// Convert from `Result<T, E>` to `Option<E>`
330
    ///
331
    /// Converts `self` into an `Option<E>`, consuming `self`,
332
    /// and discarding the value, if any.
J
Jonas Hietala 已提交
333 334 335 336 337 338 339 340 341 342
    ///
    /// # Example
    ///
    /// ```
    /// let x: Result<uint, &str> = Ok(2);
    /// assert_eq!(x.err(), None);
    ///
    /// let x: Result<uint, &str> = Err("Nothing here");
    /// assert_eq!(x.err(), Some("Nothing here"));
    /// ```
343
    #[inline]
A
Aaron Turon 已提交
344
    #[stable]
M
Marvin Löbel 已提交
345
    pub fn err(self) -> Option<E> {
346
        match self {
M
Marvin Löbel 已提交
347 348
            Ok(_)  => None,
            Err(x) => Some(x),
349
        }
350 351
    }

M
Marvin Löbel 已提交
352 353 354 355 356
    /////////////////////////////////////////////////////////////////////////
    // Adapter for working with references
    /////////////////////////////////////////////////////////////////////////

    /// Convert from `Result<T, E>` to `Result<&T, &E>`
357 358 359
    ///
    /// Produces a new `Result`, containing a reference
    /// into the original, leaving the original in place.
J
Jonas Hietala 已提交
360 361 362 363 364 365 366 367
    ///
    /// ```
    /// let x: Result<uint, &str> = Ok(2);
    /// assert_eq!(x.as_ref(), Ok(&2));
    ///
    /// let x: Result<uint, &str> = Err("Error");
    /// assert_eq!(x.as_ref(), Err(&"Error"));
    /// ```
368
    #[inline]
A
Aaron Turon 已提交
369
    #[stable]
370
    pub fn as_ref(&self) -> Result<&T, &E> {
M
Marvin Löbel 已提交
371 372 373
        match *self {
            Ok(ref x) => Ok(x),
            Err(ref x) => Err(x),
374 375 376
        }
    }

M
Marvin Löbel 已提交
377
    /// Convert from `Result<T, E>` to `Result<&mut T, &mut E>`
J
Jonas Hietala 已提交
378 379 380 381
    ///
    /// ```
    /// fn mutate(r: &mut Result<int, int>) {
    ///     match r.as_mut() {
J
Jorge Aparicio 已提交
382 383
    ///         Ok(&mut ref mut v) => *v = 42,
    ///         Err(&mut ref mut e) => *e = 0,
J
Jonas Hietala 已提交
384 385 386 387 388 389 390 391 392 393 394
    ///     }
    /// }
    ///
    /// let mut x: Result<int, int> = Ok(2);
    /// mutate(&mut x);
    /// assert_eq!(x.unwrap(), 42);
    ///
    /// let mut x: Result<int, int> = Err(13);
    /// mutate(&mut x);
    /// assert_eq!(x.unwrap_err(), 0);
    /// ```
395
    #[inline]
396 397
    #[stable]
    pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
M
Marvin Löbel 已提交
398 399 400
        match *self {
            Ok(ref mut x) => Ok(x),
            Err(ref mut x) => Err(x),
401 402
        }
    }
403

A
Aaron Turon 已提交
404
    /// Convert from `Result<T, E>` to `&mut [T]` (without copying)
J
Jonas Hietala 已提交
405 406 407 408 409
    ///
    /// ```
    /// let mut x: Result<&str, uint> = Ok("Gold");
    /// {
    ///     let v = x.as_mut_slice();
J
Jorge Aparicio 已提交
410
    ///     assert!(v == ["Gold"]);
J
Jonas Hietala 已提交
411
    ///     v[0] = "Silver";
J
Jorge Aparicio 已提交
412
    ///     assert!(v == ["Silver"]);
J
Jonas Hietala 已提交
413 414 415 416
    /// }
    /// assert_eq!(x, Ok("Silver"));
    ///
    /// let mut x: Result<&str, uint> = Err(45);
J
Jorge Aparicio 已提交
417
    /// assert!(x.as_mut_slice().is_empty());
J
Jonas Hietala 已提交
418
    /// ```
A
Aaron Turon 已提交
419 420
    #[inline]
    #[unstable = "waiting for mut conventions"]
421
    pub fn as_mut_slice(&mut self) -> &mut [T] {
A
Aaron Turon 已提交
422 423 424 425 426 427 428 429 430 431
        match *self {
            Ok(ref mut x) => slice::mut_ref_slice(x),
            Err(_) => {
                // work around lack of implicit coercion from fixed-size array to slice
                let emp: &mut [_] = &mut [];
                emp
            }
        }
    }

432 433 434 435
    /////////////////////////////////////////////////////////////////////////
    // Transforming contained values
    /////////////////////////////////////////////////////////////////////////

V
Virgile Andreani 已提交
436
    /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to an
437
    /// contained `Ok` value, leaving an `Err` value untouched.
438
    ///
439
    /// This function can be used to compose the results of two functions.
440
    ///
J
Jonas Hietala 已提交
441
    /// # Example
442 443 444 445
    ///
    /// Sum the lines of a buffer by mapping strings to numbers,
    /// ignoring I/O and parse errors:
    ///
J
Jonas Hietala 已提交
446
    /// ```
E
Erick Tryzelaar 已提交
447
    /// use std::io::IoResult;
448
    ///
E
Erick Tryzelaar 已提交
449
    /// let mut buffer = &mut b"1\n2\n3\n4\n";
450 451
    ///
    /// let mut sum = 0;
452
    ///
E
Erick Tryzelaar 已提交
453 454
    /// while !buffer.is_empty() {
    ///     let line: IoResult<String> = buffer.read_line();
455 456
    ///     // Convert the string line to a number using `map` and `from_str`
    ///     let val: IoResult<int> = line.map(|line| {
A
Alex Crichton 已提交
457
    ///         line.as_slice().trim_right().parse::<int>().unwrap_or(0)
458 459 460 461
    ///     });
    ///     // Add the value if there were no errors, otherwise add 0
    ///     sum += val.ok().unwrap_or(0);
    /// }
462 463
    ///
    /// assert!(sum == 10);
J
Jonas Hietala 已提交
464
    /// ```
465
    #[inline]
466
    #[stable]
467
    pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
468
        match self {
469 470
            Ok(t) => Ok(op(t)),
            Err(e) => Err(e)
471 472 473
        }
    }

V
Virgile Andreani 已提交
474
    /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to an
475
    /// contained `Err` value, leaving an `Ok` value untouched.
476
    ///
477 478
    /// This function can be used to pass through a successful result while handling
    /// an error.
J
Jonas Hietala 已提交
479 480 481 482 483 484
    ///
    /// # Example
    ///
    /// ```
    /// fn stringify(x: uint) -> String { format!("error code: {}", x) }
    ///
485 486
    /// let x: Result<uint, uint> = Ok(2);
    /// assert_eq!(x.map_err(stringify), Ok(2));
J
Jonas Hietala 已提交
487 488 489 490
    ///
    /// let x: Result<uint, uint> = Err(13);
    /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
    /// ```
491
    #[inline]
492
    #[stable]
493
    pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> {
494
        match self {
495 496
            Ok(t) => Ok(t),
            Err(e) => Err(op(e))
497 498 499
        }
    }

A
Aaron Turon 已提交
500 501 502 503 504
    /////////////////////////////////////////////////////////////////////////
    // Iterator constructors
    /////////////////////////////////////////////////////////////////////////

    /// Returns an iterator over the possibly contained value.
J
Jonas Hietala 已提交
505 506 507 508 509 510 511 512 513 514
    ///
    /// # Example
    ///
    /// ```
    /// let x: Result<uint, &str> = Ok(7);
    /// assert_eq!(x.iter().next(), Some(&7));
    ///
    /// let x: Result<uint, &str> = Err("nothing!");
    /// assert_eq!(x.iter().next(), None);
    /// ```
A
Aaron Turon 已提交
515
    #[inline]
516 517 518
    #[stable]
    pub fn iter(&self) -> Iter<T> {
        Iter { inner: self.as_ref().ok() }
A
Aaron Turon 已提交
519 520 521
    }

    /// Returns a mutable iterator over the possibly contained value.
J
Jonas Hietala 已提交
522 523 524 525 526 527
    ///
    /// # Example
    ///
    /// ```
    /// let mut x: Result<uint, &str> = Ok(7);
    /// match x.iter_mut().next() {
J
Jorge Aparicio 已提交
528
    ///     Some(&mut ref mut x) => *x = 40,
J
Jonas Hietala 已提交
529 530 531 532 533 534 535
    ///     None => {},
    /// }
    /// assert_eq!(x, Ok(40));
    ///
    /// let mut x: Result<uint, &str> = Err("nothing!");
    /// assert_eq!(x.iter_mut().next(), None);
    /// ```
A
Aaron Turon 已提交
536
    #[inline]
537 538 539
    #[stable]
    pub fn iter_mut(&mut self) -> IterMut<T> {
        IterMut { inner: self.as_mut().ok() }
A
Aaron Turon 已提交
540 541 542
    }

    /// Returns a consuming iterator over the possibly contained value.
J
Jonas Hietala 已提交
543 544 545 546 547 548
    ///
    /// # Example
    ///
    /// ```
    /// let x: Result<uint, &str> = Ok(5);
    /// let v: Vec<uint> = x.into_iter().collect();
549
    /// assert_eq!(v, vec![5]);
J
Jonas Hietala 已提交
550 551 552 553 554
    ///
    /// let x: Result<uint, &str> = Err("nothing!");
    /// let v: Vec<uint> = x.into_iter().collect();
    /// assert_eq!(v, vec![]);
    /// ```
A
Aaron Turon 已提交
555
    #[inline]
556 557 558
    #[stable]
    pub fn into_iter(self) -> IntoIter<T> {
        IntoIter { inner: self.ok() }
A
Aaron Turon 已提交
559 560
    }

561 562 563 564 565
    ////////////////////////////////////////////////////////////////////////
    // Boolean operations on the values, eager and lazy
    /////////////////////////////////////////////////////////////////////////

    /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
J
Jonas Hietala 已提交
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
    ///
    /// # Example
    ///
    /// ```
    /// let x: Result<uint, &str> = Ok(2);
    /// let y: Result<&str, &str> = Err("late error");
    /// assert_eq!(x.and(y), Err("late error"));
    ///
    /// let x: Result<uint, &str> = Err("early error");
    /// let y: Result<&str, &str> = Ok("foo");
    /// assert_eq!(x.and(y), Err("early error"));
    ///
    /// let x: Result<uint, &str> = Err("not a 2");
    /// let y: Result<&str, &str> = Err("late error");
    /// assert_eq!(x.and(y), Err("not a 2"));
    ///
    /// let x: Result<uint, &str> = Ok(2);
    /// let y: Result<&str, &str> = Ok("different result type");
    /// assert_eq!(x.and(y), Ok("different result type"));
    /// ```
586
    #[inline]
A
Aaron Turon 已提交
587
    #[stable]
588
    pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
589 590
        match self {
            Ok(_) => res,
591
            Err(e) => Err(e),
592 593 594
        }
    }

595
    /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
596
    ///
J
Jonas Hietala 已提交
597 598 599 600 601 602 603 604 605 606 607 608 609
    /// This function can be used for control flow based on result values.
    ///
    /// # Example
    ///
    /// ```
    /// fn sq(x: uint) -> Result<uint, uint> { Ok(x * x) }
    /// fn err(x: uint) -> Result<uint, uint> { Err(x) }
    ///
    /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
    /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
    /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
    /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
    /// ```
610
    #[inline]
611
    #[stable]
612
    pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
613 614
        match self {
            Ok(t) => op(t),
615
            Err(e) => Err(e),
616
        }
617 618
    }

619
    /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
J
Jonas Hietala 已提交
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
    ///
    /// # Example
    ///
    /// ```
    /// let x: Result<uint, &str> = Ok(2);
    /// let y: Result<uint, &str> = Err("late error");
    /// assert_eq!(x.or(y), Ok(2));
    ///
    /// let x: Result<uint, &str> = Err("early error");
    /// let y: Result<uint, &str> = Ok(2);
    /// assert_eq!(x.or(y), Ok(2));
    ///
    /// let x: Result<uint, &str> = Err("not a 2");
    /// let y: Result<uint, &str> = Err("late error");
    /// assert_eq!(x.or(y), Err("late error"));
    ///
    /// let x: Result<uint, &str> = Ok(2);
    /// let y: Result<uint, &str> = Ok(100);
    /// assert_eq!(x.or(y), Ok(2));
    /// ```
640
    #[inline]
A
Aaron Turon 已提交
641
    #[stable]
642 643 644 645 646 647 648
    pub fn or(self, res: Result<T, E>) -> Result<T, E> {
        match self {
            Ok(_) => self,
            Err(_) => res,
        }
    }

649
    /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
650
    ///
J
Jonas Hietala 已提交
651 652 653 654 655 656 657 658 659 660 661 662 663
    /// This function can be used for control flow based on result values.
    ///
    /// # Example
    ///
    /// ```
    /// fn sq(x: uint) -> Result<uint, uint> { Ok(x * x) }
    /// fn err(x: uint) -> Result<uint, uint> { Err(x) }
    ///
    /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
    /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
    /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
    /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
    /// ```
664
    #[inline]
665
    #[stable]
666
    pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
667 668
        match self {
            Ok(t) => Ok(t),
669
            Err(e) => op(e),
670
        }
671
    }
672

M
Marvin Löbel 已提交
673
    /// Unwraps a result, yielding the content of an `Ok`.
674
    /// Else it returns `optb`.
J
Jonas Hietala 已提交
675 676 677 678
    ///
    /// # Example
    ///
    /// ```
679 680 681
    /// let optb = 2;
    /// let x: Result<uint, &str> = Ok(9);
    /// assert_eq!(x.unwrap_or(optb), 9);
J
Jonas Hietala 已提交
682 683 684 685
    ///
    /// let x: Result<uint, &str> = Err("error");
    /// assert_eq!(x.unwrap_or(optb), optb);
    /// ```
686
    #[inline]
687
    #[stable]
688
    pub fn unwrap_or(self, optb: T) -> T {
M
Marvin Löbel 已提交
689 690
        match self {
            Ok(t) => t,
691
            Err(_) => optb
M
Marvin Löbel 已提交
692 693 694
        }
    }

695
    /// Unwraps a result, yielding the content of an `Ok`.
696
    /// If the value is an `Err` then it calls `op` with its value.
J
Jonas Hietala 已提交
697 698 699 700 701 702
    ///
    /// # Example
    ///
    /// ```
    /// fn count(x: &str) -> uint { x.len() }
    ///
703 704
    /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
    /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
J
Jonas Hietala 已提交
705
    /// ```
706
    #[inline]
707
    #[stable]
708
    pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
709 710
        match self {
            Ok(t) => t,
711
            Err(e) => op(e)
712 713
        }
    }
714
}
715

716
#[stable]
717
impl<T, E: Debug> Result<T, E> {
718 719
    /// Unwraps a result, yielding the content of an `Ok`.
    ///
S
Steve Klabnik 已提交
720
    /// # Panics
721
    ///
S
Steve Klabnik 已提交
722
    /// Panics if the value is an `Err`, with a custom panic message provided
723
    /// by the `Err`'s value.
J
Jonas Hietala 已提交
724 725 726 727
    ///
    /// # Example
    ///
    /// ```
728 729
    /// let x: Result<uint, &str> = Ok(2);
    /// assert_eq!(x.unwrap(), 2);
J
Jonas Hietala 已提交
730 731 732 733
    /// ```
    ///
    /// ```{.should_fail}
    /// let x: Result<uint, &str> = Err("emergency failure");
S
Steve Klabnik 已提交
734
    /// x.unwrap(); // panics with `emergency failure`
J
Jonas Hietala 已提交
735
    /// ```
736
    #[inline]
737
    #[stable]
738 739 740 741
    pub fn unwrap(self) -> T {
        match self {
            Ok(t) => t,
            Err(e) =>
742
                panic!("called `Result::unwrap()` on an `Err` value: {:?}", e)
743 744 745 746
        }
    }
}

747
#[stable]
748
impl<T: Debug, E> Result<T, E> {
749 750
    /// Unwraps a result, yielding the content of an `Err`.
    ///
S
Steve Klabnik 已提交
751
    /// # Panics
752
    ///
S
Steve Klabnik 已提交
753
    /// Panics if the value is an `Ok`, with a custom panic message provided
754
    /// by the `Ok`'s value.
J
Jonas Hietala 已提交
755 756 757 758
    ///
    /// # Example
    ///
    /// ```{.should_fail}
759
    /// let x: Result<uint, &str> = Ok(2);
S
Steve Klabnik 已提交
760
    /// x.unwrap_err(); // panics with `2`
J
Jonas Hietala 已提交
761 762 763 764 765 766
    /// ```
    ///
    /// ```
    /// let x: Result<uint, &str> = Err("emergency failure");
    /// assert_eq!(x.unwrap_err(), "emergency failure");
    /// ```
767
    #[inline]
768
    #[stable]
769 770 771
    pub fn unwrap_err(self) -> E {
        match self {
            Ok(t) =>
772
                panic!("called `Result::unwrap_err()` on an `Ok` value: {:?}", t),
773 774 775 776 777
            Err(e) => e
        }
    }
}

778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
/////////////////////////////////////////////////////////////////////////////
// Trait implementations
/////////////////////////////////////////////////////////////////////////////

impl<T, E> AsSlice<T> for Result<T, E> {
    /// Convert from `Result<T, E>` to `&[T]` (without copying)
    #[inline]
    #[stable]
    fn as_slice<'a>(&'a self) -> &'a [T] {
        match *self {
            Ok(ref x) => slice::ref_slice(x),
            Err(_) => {
                // work around lack of implicit coercion from fixed-size array to slice
                let emp: &[_] = &[];
                emp
            }
        }
    }
}

A
Aaron Turon 已提交
798
/////////////////////////////////////////////////////////////////////////////
799
// The Result Iterators
A
Aaron Turon 已提交
800 801
/////////////////////////////////////////////////////////////////////////////

802 803 804
/// An iterator over a reference to the `Ok` variant of a `Result`.
#[stable]
pub struct Iter<'a, T: 'a> { inner: Option<&'a T> }
A
Aaron Turon 已提交
805

806
#[stable]
807 808 809
impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;

A
Aaron Turon 已提交
810
    #[inline]
811 812 813 814 815
    fn next(&mut self) -> Option<&'a T> { self.inner.take() }
    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        let n = if self.inner.is_some() {1} else {0};
        (n, Some(n))
A
Aaron Turon 已提交
816
    }
817 818
}

819
#[stable]
820
impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
821 822 823 824
    #[inline]
    fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
}

825
#[stable]
826
impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
827 828 829 830 831 832 833 834

impl<'a, T> Clone for Iter<'a, T> {
    fn clone(&self) -> Iter<'a, T> { Iter { inner: self.inner } }
}

/// An iterator over a mutable reference to the `Ok` variant of a `Result`.
#[stable]
pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
A
Aaron Turon 已提交
835

836
#[stable]
837 838 839
impl<'a, T> Iterator for IterMut<'a, T> {
    type Item = &'a mut T;

840 841
    #[inline]
    fn next(&mut self) -> Option<&'a mut T> { self.inner.take() }
A
Aaron Turon 已提交
842 843
    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
844 845
        let n = if self.inner.is_some() {1} else {0};
        (n, Some(n))
A
Aaron Turon 已提交
846 847
    }
}
848

849
#[stable]
850
impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
A
Aaron Turon 已提交
851
    #[inline]
852 853 854
    fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
}

855
#[stable]
856
impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
857 858 859 860 861

/// An iterator over the value in a `Ok` variant of a `Result`.
#[stable]
pub struct IntoIter<T> { inner: Option<T> }

862
#[stable]
863 864 865
impl<T> Iterator for IntoIter<T> {
    type Item = T;

866 867 868 869 870 871
    #[inline]
    fn next(&mut self) -> Option<T> { self.inner.take() }
    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        let n = if self.inner.is_some() {1} else {0};
        (n, Some(n))
872
    }
A
Aaron Turon 已提交
873 874
}

875
#[stable]
876
impl<T> DoubleEndedIterator for IntoIter<T> {
877 878 879 880
    #[inline]
    fn next_back(&mut self) -> Option<T> { self.inner.take() }
}

881
#[stable]
882
impl<T> ExactSizeIterator for IntoIter<T> {}
883

A
Aaron Turon 已提交
884
/////////////////////////////////////////////////////////////////////////////
885
// FromIterator
A
Aaron Turon 已提交
886 887
/////////////////////////////////////////////////////////////////////////////

888
#[stable]
A
Aaron Turon 已提交
889 890 891 892 893 894 895 896 897 898 899
impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
    /// Takes each element in the `Iterator`: if it is an `Err`, no further
    /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
    /// container with the values of each `Result` is returned.
    ///
    /// Here is an example which increments every integer in a vector,
    /// checking for overflow:
    ///
    /// ```rust
    /// use std::uint;
    ///
900
    /// let v = vec!(1, 2);
901 902
    /// let res: Result<Vec<uint>, &'static str> = v.iter().map(|&x: &uint|
    ///     if x == uint::MAX { Err("Overflow!") }
A
Aaron Turon 已提交
903 904
    ///     else { Ok(x + 1) }
    /// ).collect();
905
    /// assert!(res == Ok(vec!(2, 3)));
A
Aaron Turon 已提交
906 907
    /// ```
    #[inline]
908
    fn from_iter<I: Iterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
A
Aaron Turon 已提交
909 910 911 912 913 914 915 916
        // FIXME(#11084): This could be replaced with Iterator::scan when this
        // performance bug is closed.

        struct Adapter<Iter, E> {
            iter: Iter,
            err: Option<E>,
        }

917 918 919
        impl<T, E, Iter: Iterator<Item=Result<T, E>>> Iterator for Adapter<Iter, E> {
            type Item = T;

A
Aaron Turon 已提交
920 921 922 923 924 925 926 927 928
            #[inline]
            fn next(&mut self) -> Option<T> {
                match self.iter.next() {
                    Some(Ok(value)) => Some(value),
                    Some(Err(err)) => {
                        self.err = Some(err);
                        None
                    }
                    None => None,
929
                }
930
            }
931
        }
932

A
Aaron Turon 已提交
933 934
        let mut adapter = Adapter { iter: iter, err: None };
        let v: V = FromIterator::from_iter(adapter.by_ref());
935

A
Aaron Turon 已提交
936 937 938 939
        match adapter.err {
            Some(err) => Err(err),
            None => Ok(v),
        }
940 941 942
    }
}

943 944 945 946
/////////////////////////////////////////////////////////////////////////////
// FromIterator
/////////////////////////////////////////////////////////////////////////////

947
/// Perform a fold operation over the result values from an iterator.
948
///
949 950
/// If an `Err` is encountered, it is immediately returned.
/// Otherwise, the folded value is returned.
951
#[inline]
B
Brian Anderson 已提交
952
#[unstable]
953 954 955
pub fn fold<T,
            V,
            E,
956
            F: FnMut(V, T) -> V,
957
            Iter: Iterator<Item=Result<T, E>>>(
958 959
            mut iterator: Iter,
            mut init: V,
960
            mut f: F)
961
            -> Result<V, E> {
962 963 964 965
    for t in iterator {
        match t {
            Ok(v) => init = f(init, v),
            Err(u) => return Err(u)
966 967
        }
    }
968
    Ok(init)
969
}