result.rs 29.4 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
//! ```
J
Jorge Aparicio 已提交
33
//! #[derive(Debug)]
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
//! ```
A
Alex Crichton 已提交
98
//! use std::old_io::IoError;
99 100 101 102
//!
//! 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}
A
Alex Crichton 已提交
113
//! use std::old_io::{File, Open, Write};
114 115 116 117 118 119
//!
//! 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}
A
Alex Crichton 已提交
131
//! use std::old_io::{File, Open, Write};
132 133 134 135
//!
//! 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}
A
Alex Crichton 已提交
141
//! # use std::old_io::{File, Open, Write};
142 143 144 145
//!
//! # 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
//! ```
A
Alex Crichton 已提交
151
//! # use std::old_io::{File, Open, Write, IoError};
152 153 154 155 156 157
//! 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
//! ```
A
Alex Crichton 已提交
170
//! use std::old_io::{File, Open, Write, IoError};
171
//!
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
//!     if let Err(e) = file.write_line(&format!("name: {}", info.name)) {
182
//!         return Err(e)
183
//!     }
184
//!     if let Err(e) = file.write_line(&format!("age: {}", info.age)) {
185
//!         return Err(e)
186
//!     }
187
//!     return file.write_line(&format!("rating: {}", info.rating));
188
//! }
J
Jonas Hietala 已提交
189
//! ```
190 191 192
//!
//! With this:
//!
J
Jonas Hietala 已提交
193
//! ```
A
Alex Crichton 已提交
194
//! use std::old_io::{File, Open, Write, IoError};
195
//!
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)));
//!     try!(file.write_line(&format!("age: {}", info.age)));
//!     try!(file.write_line(&format!("rating: {}", info.rating)));
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

B
Brian Anderson 已提交
227
#![stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
228

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

231
use clone::Clone;
232
use fmt;
A
Alexis 已提交
233 234
use iter::{Iterator, IteratorExt, DoubleEndedIterator,
           FromIterator, ExactSizeIterator, IntoIterator};
235
use ops::{FnMut, FnOnce};
236
use option::Option::{self, None, Some};
237 238
use slice::AsSlice;
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.
J
Jorge Aparicio 已提交
243
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
244
#[must_use]
B
Brian Anderson 已提交
245
#[stable(feature = "rust1", since = "1.0.0")]
246
pub enum Result<T, E> {
M
Marvin Löbel 已提交
247
    /// Contains the success value
B
Brian Anderson 已提交
248
    #[stable(feature = "rust1", since = "1.0.0")]
249
    Ok(T),
M
Marvin Löbel 已提交
250

251
    /// Contains the error value
B
Brian Anderson 已提交
252
    #[stable(feature = "rust1", since = "1.0.0")]
253
    Err(E)
254 255
}

256 257 258 259
/////////////////////////////////////////////////////////////////////////////
// Type implementation
/////////////////////////////////////////////////////////////////////////////

B
Brian Anderson 已提交
260
#[stable(feature = "rust1", since = "1.0.0")]
M
Marvin Löbel 已提交
261
impl<T, E> Result<T, E> {
262 263 264
    /////////////////////////////////////////////////////////////////////////
    // Querying the contained values
    /////////////////////////////////////////////////////////////////////////
265

266
    /// Returns true if the result is `Ok`
267
    ///
S
Steve Klabnik 已提交
268
    /// # Examples
269
    ///
J
Jonas Hietala 已提交
270 271 272 273 274 275 276
    /// ```
    /// 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);
    /// ```
277
    #[inline]
B
Brian Anderson 已提交
278
    #[stable(feature = "rust1", since = "1.0.0")]
E
Erick Tryzelaar 已提交
279 280 281 282 283 284
    pub fn is_ok(&self) -> bool {
        match *self {
            Ok(_) => true,
            Err(_) => false
        }
    }
285

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

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

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

M
Marvin Löbel 已提交
330
    /// Convert from `Result<T, E>` to `Option<E>`
331
    ///
332
    /// Converts `self` into an `Option<E>`, consuming `self`,
333
    /// and discarding the success value, if any.
J
Jonas Hietala 已提交
334
    ///
S
Steve Klabnik 已提交
335
    /// # Examples
J
Jonas Hietala 已提交
336 337
    ///
    /// ```
N
Niko Matsakis 已提交
338
    /// let x: Result<u32, &str> = Ok(2);
J
Jonas Hietala 已提交
339 340
    /// assert_eq!(x.err(), None);
    ///
N
Niko Matsakis 已提交
341
    /// let x: Result<u32, &str> = Err("Nothing here");
J
Jonas Hietala 已提交
342 343
    /// assert_eq!(x.err(), Some("Nothing here"));
    /// ```
344
    #[inline]
B
Brian Anderson 已提交
345
    #[stable(feature = "rust1", since = "1.0.0")]
M
Marvin Löbel 已提交
346
    pub fn err(self) -> Option<E> {
347
        match self {
M
Marvin Löbel 已提交
348 349
            Ok(_)  => None,
            Err(x) => Some(x),
350
        }
351 352
    }

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

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

M
Marvin Löbel 已提交
378
    /// Convert from `Result<T, E>` to `Result<&mut T, &mut E>`
J
Jonas Hietala 已提交
379 380 381 382
    ///
    /// ```
    /// fn mutate(r: &mut Result<int, int>) {
    ///     match r.as_mut() {
J
Jorge Aparicio 已提交
383 384
    ///         Ok(&mut ref mut v) => *v = 42,
    ///         Err(&mut ref mut e) => *e = 0,
J
Jonas Hietala 已提交
385 386 387 388 389 390 391 392 393 394 395
    ///     }
    /// }
    ///
    /// 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);
    /// ```
396
    #[inline]
B
Brian Anderson 已提交
397
    #[stable(feature = "rust1", since = "1.0.0")]
398
    pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
M
Marvin Löbel 已提交
399 400 401
        match *self {
            Ok(ref mut x) => Ok(x),
            Err(ref mut x) => Err(x),
402 403
        }
    }
404

A
Aaron Turon 已提交
405
    /// Convert from `Result<T, E>` to `&mut [T]` (without copying)
J
Jonas Hietala 已提交
406 407
    ///
    /// ```
N
Niko Matsakis 已提交
408
    /// let mut x: Result<&str, u32> = Ok("Gold");
J
Jonas Hietala 已提交
409 410
    /// {
    ///     let v = x.as_mut_slice();
J
Jorge Aparicio 已提交
411
    ///     assert!(v == ["Gold"]);
J
Jonas Hietala 已提交
412
    ///     v[0] = "Silver";
J
Jorge Aparicio 已提交
413
    ///     assert!(v == ["Silver"]);
J
Jonas Hietala 已提交
414 415 416
    /// }
    /// assert_eq!(x, Ok("Silver"));
    ///
N
Niko Matsakis 已提交
417
    /// let mut x: Result<&str, u32> = Err(45);
J
Jorge Aparicio 已提交
418
    /// assert!(x.as_mut_slice().is_empty());
J
Jonas Hietala 已提交
419
    /// ```
A
Aaron Turon 已提交
420
    #[inline]
421
    #[unstable(feature = "core",
422
               reason = "waiting for mut conventions")]
423
    pub fn as_mut_slice(&mut self) -> &mut [T] {
A
Aaron Turon 已提交
424 425 426 427 428 429 430 431 432 433
        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
            }
        }
    }

434 435 436 437
    /////////////////////////////////////////////////////////////////////////
    // Transforming contained values
    /////////////////////////////////////////////////////////////////////////

V
Virgile Andreani 已提交
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
    ///
S
Steve Klabnik 已提交
443
    /// # Examples
444 445 446 447
    ///
    /// Sum the lines of a buffer by mapping strings to numbers,
    /// ignoring I/O and parse errors:
    ///
J
Jonas Hietala 已提交
448
    /// ```
A
Alex Crichton 已提交
449
    /// use std::old_io::IoResult;
450
    ///
V
Vadim Petrochenkov 已提交
451 452
    /// let mut buffer: &[u8] = b"1\n2\n3\n4\n";
    /// let mut buffer = &mut buffer;
453 454
    ///
    /// let mut sum = 0;
455
    ///
E
Erick Tryzelaar 已提交
456 457
    /// while !buffer.is_empty() {
    ///     let line: IoResult<String> = buffer.read_line();
458 459
    ///     // Convert the string line to a number using `map` and `from_str`
    ///     let val: IoResult<int> = line.map(|line| {
460
    ///         line.trim_right().parse::<int>().unwrap_or(0)
461 462 463 464
    ///     });
    ///     // Add the value if there were no errors, otherwise add 0
    ///     sum += val.ok().unwrap_or(0);
    /// }
465 466
    ///
    /// assert!(sum == 10);
J
Jonas Hietala 已提交
467
    /// ```
468
    #[inline]
B
Brian Anderson 已提交
469
    #[stable(feature = "rust1", since = "1.0.0")]
470
    pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
471
        match self {
472 473
            Ok(t) => Ok(op(t)),
            Err(e) => Err(e)
474 475 476
        }
    }

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

A
Aaron Turon 已提交
503 504 505 506 507
    /////////////////////////////////////////////////////////////////////////
    // Iterator constructors
    /////////////////////////////////////////////////////////////////////////

    /// Returns an iterator over the possibly contained value.
J
Jonas Hietala 已提交
508
    ///
S
Steve Klabnik 已提交
509
    /// # Examples
J
Jonas Hietala 已提交
510 511
    ///
    /// ```
N
Niko Matsakis 已提交
512
    /// let x: Result<u32, &str> = Ok(7);
J
Jonas Hietala 已提交
513 514
    /// assert_eq!(x.iter().next(), Some(&7));
    ///
N
Niko Matsakis 已提交
515
    /// let x: Result<u32, &str> = Err("nothing!");
J
Jonas Hietala 已提交
516 517
    /// assert_eq!(x.iter().next(), None);
    /// ```
A
Aaron Turon 已提交
518
    #[inline]
B
Brian Anderson 已提交
519
    #[stable(feature = "rust1", since = "1.0.0")]
520 521
    pub fn iter(&self) -> Iter<T> {
        Iter { inner: self.as_ref().ok() }
A
Aaron Turon 已提交
522 523 524
    }

    /// Returns a mutable iterator over the possibly contained value.
J
Jonas Hietala 已提交
525
    ///
S
Steve Klabnik 已提交
526
    /// # Examples
J
Jonas Hietala 已提交
527 528
    ///
    /// ```
N
Niko Matsakis 已提交
529
    /// let mut x: Result<u32, &str> = Ok(7);
J
Jonas Hietala 已提交
530
    /// match x.iter_mut().next() {
J
Jorge Aparicio 已提交
531
    ///     Some(&mut ref mut x) => *x = 40,
J
Jonas Hietala 已提交
532 533 534 535
    ///     None => {},
    /// }
    /// assert_eq!(x, Ok(40));
    ///
N
Niko Matsakis 已提交
536
    /// let mut x: Result<u32, &str> = Err("nothing!");
J
Jonas Hietala 已提交
537 538
    /// assert_eq!(x.iter_mut().next(), None);
    /// ```
A
Aaron Turon 已提交
539
    #[inline]
B
Brian Anderson 已提交
540
    #[stable(feature = "rust1", since = "1.0.0")]
541 542
    pub fn iter_mut(&mut self) -> IterMut<T> {
        IterMut { inner: self.as_mut().ok() }
A
Aaron Turon 已提交
543 544 545
    }

    /// Returns a consuming iterator over the possibly contained value.
J
Jonas Hietala 已提交
546
    ///
S
Steve Klabnik 已提交
547
    /// # Examples
J
Jonas Hietala 已提交
548 549
    ///
    /// ```
N
Niko Matsakis 已提交
550 551
    /// let x: Result<u32, &str> = Ok(5);
    /// let v: Vec<u32> = x.into_iter().collect();
552
    /// assert_eq!(v, [5]);
J
Jonas Hietala 已提交
553
    ///
N
Niko Matsakis 已提交
554 555
    /// let x: Result<u32, &str> = Err("nothing!");
    /// let v: Vec<u32> = x.into_iter().collect();
556
    /// assert_eq!(v, []);
J
Jonas Hietala 已提交
557
    /// ```
A
Aaron Turon 已提交
558
    #[inline]
B
Brian Anderson 已提交
559
    #[stable(feature = "rust1", since = "1.0.0")]
560 561
    pub fn into_iter(self) -> IntoIter<T> {
        IntoIter { inner: self.ok() }
A
Aaron Turon 已提交
562 563
    }

564 565 566 567 568
    ////////////////////////////////////////////////////////////////////////
    // 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 已提交
569
    ///
S
Steve Klabnik 已提交
570
    /// # Examples
J
Jonas Hietala 已提交
571 572
    ///
    /// ```
N
Niko Matsakis 已提交
573
    /// let x: Result<u32, &str> = Ok(2);
J
Jonas Hietala 已提交
574 575 576
    /// let y: Result<&str, &str> = Err("late error");
    /// assert_eq!(x.and(y), Err("late error"));
    ///
N
Niko Matsakis 已提交
577
    /// let x: Result<u32, &str> = Err("early error");
J
Jonas Hietala 已提交
578 579 580
    /// let y: Result<&str, &str> = Ok("foo");
    /// assert_eq!(x.and(y), Err("early error"));
    ///
N
Niko Matsakis 已提交
581
    /// let x: Result<u32, &str> = Err("not a 2");
J
Jonas Hietala 已提交
582 583 584
    /// let y: Result<&str, &str> = Err("late error");
    /// assert_eq!(x.and(y), Err("not a 2"));
    ///
N
Niko Matsakis 已提交
585
    /// let x: Result<u32, &str> = Ok(2);
J
Jonas Hietala 已提交
586 587 588
    /// let y: Result<&str, &str> = Ok("different result type");
    /// assert_eq!(x.and(y), Ok("different result type"));
    /// ```
589
    #[inline]
B
Brian Anderson 已提交
590
    #[stable(feature = "rust1", since = "1.0.0")]
591
    pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
592 593
        match self {
            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
    ///
J
Jonas Hietala 已提交
600 601
    /// This function can be used for control flow based on result values.
    ///
S
Steve Klabnik 已提交
602
    /// # Examples
J
Jonas Hietala 已提交
603 604
    ///
    /// ```
N
Niko Matsakis 已提交
605 606
    /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
    /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
J
Jonas Hietala 已提交
607 608 609 610 611 612
    ///
    /// 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));
    /// ```
613
    #[inline]
B
Brian Anderson 已提交
614
    #[stable(feature = "rust1", since = "1.0.0")]
615
    pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
616 617
        match self {
            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`.
J
Jonas Hietala 已提交
623
    ///
S
Steve Klabnik 已提交
624
    /// # Examples
J
Jonas Hietala 已提交
625 626
    ///
    /// ```
N
Niko Matsakis 已提交
627 628
    /// let x: Result<u32, &str> = Ok(2);
    /// let y: Result<u32, &str> = Err("late error");
J
Jonas Hietala 已提交
629 630
    /// assert_eq!(x.or(y), Ok(2));
    ///
N
Niko Matsakis 已提交
631 632
    /// let x: Result<u32, &str> = Err("early error");
    /// let y: Result<u32, &str> = Ok(2);
J
Jonas Hietala 已提交
633 634
    /// assert_eq!(x.or(y), Ok(2));
    ///
N
Niko Matsakis 已提交
635 636
    /// let x: Result<u32, &str> = Err("not a 2");
    /// let y: Result<u32, &str> = Err("late error");
J
Jonas Hietala 已提交
637 638
    /// assert_eq!(x.or(y), Err("late error"));
    ///
N
Niko Matsakis 已提交
639 640
    /// let x: Result<u32, &str> = Ok(2);
    /// let y: Result<u32, &str> = Ok(100);
J
Jonas Hietala 已提交
641 642
    /// assert_eq!(x.or(y), Ok(2));
    /// ```
643
    #[inline]
B
Brian Anderson 已提交
644
    #[stable(feature = "rust1", since = "1.0.0")]
645
    pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
646
        match self {
647
            Ok(v) => Ok(v),
648 649 650 651
            Err(_) => res,
        }
    }

652
    /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
653
    ///
J
Jonas Hietala 已提交
654 655
    /// This function can be used for control flow based on result values.
    ///
S
Steve Klabnik 已提交
656
    /// # Examples
J
Jonas Hietala 已提交
657 658
    ///
    /// ```
N
Niko Matsakis 已提交
659 660
    /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
    /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
J
Jonas Hietala 已提交
661 662 663 664 665 666
    ///
    /// 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));
    /// ```
667
    #[inline]
B
Brian Anderson 已提交
668
    #[stable(feature = "rust1", since = "1.0.0")]
669
    pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
670 671
        match self {
            Ok(t) => Ok(t),
672
            Err(e) => op(e),
673
        }
674
    }
675

M
Marvin Löbel 已提交
676
    /// Unwraps a result, yielding the content of an `Ok`.
677
    /// Else it returns `optb`.
J
Jonas Hietala 已提交
678
    ///
S
Steve Klabnik 已提交
679
    /// # Examples
J
Jonas Hietala 已提交
680 681
    ///
    /// ```
682
    /// let optb = 2;
N
Niko Matsakis 已提交
683
    /// let x: Result<u32, &str> = Ok(9);
684
    /// assert_eq!(x.unwrap_or(optb), 9);
J
Jonas Hietala 已提交
685
    ///
N
Niko Matsakis 已提交
686
    /// let x: Result<u32, &str> = Err("error");
J
Jonas Hietala 已提交
687 688
    /// assert_eq!(x.unwrap_or(optb), optb);
    /// ```
689
    #[inline]
B
Brian Anderson 已提交
690
    #[stable(feature = "rust1", since = "1.0.0")]
691
    pub fn unwrap_or(self, optb: T) -> T {
M
Marvin Löbel 已提交
692 693
        match self {
            Ok(t) => t,
694
            Err(_) => optb
M
Marvin Löbel 已提交
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.
J
Jonas Hietala 已提交
700
    ///
S
Steve Klabnik 已提交
701
    /// # Examples
J
Jonas Hietala 已提交
702 703
    ///
    /// ```
N
Niko Matsakis 已提交
704
    /// fn count(x: &str) -> usize { x.len() }
J
Jonas Hietala 已提交
705
    ///
706 707
    /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
    /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
J
Jonas Hietala 已提交
708
    /// ```
709
    #[inline]
B
Brian Anderson 已提交
710
    #[stable(feature = "rust1", since = "1.0.0")]
711
    pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
712 713
        match self {
            Ok(t) => t,
714
            Err(e) => op(e)
715 716
        }
    }
717
}
718

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

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

781 782 783 784 785 786 787
/////////////////////////////////////////////////////////////////////////////
// Trait implementations
/////////////////////////////////////////////////////////////////////////////

impl<T, E> AsSlice<T> for Result<T, E> {
    /// Convert from `Result<T, E>` to `&[T]` (without copying)
    #[inline]
B
Brian Anderson 已提交
788
    #[stable(feature = "rust1", since = "1.0.0")]
789 790 791 792 793 794 795 796 797 798 799 800
    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 已提交
801
/////////////////////////////////////////////////////////////////////////////
802
// The Result Iterators
A
Aaron Turon 已提交
803 804
/////////////////////////////////////////////////////////////////////////////

805
/// An iterator over a reference to the `Ok` variant of a `Result`.
B
Brian Anderson 已提交
806
#[stable(feature = "rust1", since = "1.0.0")]
807
pub struct Iter<'a, T: 'a> { inner: Option<&'a T> }
A
Aaron Turon 已提交
808

B
Brian Anderson 已提交
809
#[stable(feature = "rust1", since = "1.0.0")]
810 811 812
impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;

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

B
Brian Anderson 已提交
822
#[stable(feature = "rust1", since = "1.0.0")]
823
impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
824 825 826 827
    #[inline]
    fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
}

B
Brian Anderson 已提交
828
#[stable(feature = "rust1", since = "1.0.0")]
829
impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
830 831 832 833 834 835

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`.
B
Brian Anderson 已提交
836
#[stable(feature = "rust1", since = "1.0.0")]
837
pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
A
Aaron Turon 已提交
838

B
Brian Anderson 已提交
839
#[stable(feature = "rust1", since = "1.0.0")]
840 841 842
impl<'a, T> Iterator for IterMut<'a, T> {
    type Item = &'a mut T;

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

B
Brian Anderson 已提交
852
#[stable(feature = "rust1", since = "1.0.0")]
853
impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
A
Aaron Turon 已提交
854
    #[inline]
855 856 857
    fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
}

B
Brian Anderson 已提交
858
#[stable(feature = "rust1", since = "1.0.0")]
859
impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
860 861

/// An iterator over the value in a `Ok` variant of a `Result`.
B
Brian Anderson 已提交
862
#[stable(feature = "rust1", since = "1.0.0")]
863 864
pub struct IntoIter<T> { inner: Option<T> }

B
Brian Anderson 已提交
865
#[stable(feature = "rust1", since = "1.0.0")]
866 867 868
impl<T> Iterator for IntoIter<T> {
    type Item = T;

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

B
Brian Anderson 已提交
878
#[stable(feature = "rust1", since = "1.0.0")]
879
impl<T> DoubleEndedIterator for IntoIter<T> {
880 881 882 883
    #[inline]
    fn next_back(&mut self) -> Option<T> { self.inner.take() }
}

B
Brian Anderson 已提交
884
#[stable(feature = "rust1", since = "1.0.0")]
885
impl<T> ExactSizeIterator for IntoIter<T> {}
886

A
Aaron Turon 已提交
887
/////////////////////////////////////////////////////////////////////////////
888
// FromIterator
A
Aaron Turon 已提交
889 890
/////////////////////////////////////////////////////////////////////////////

B
Brian Anderson 已提交
891
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
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:
    ///
900
    /// ```
N
Niko Matsakis 已提交
901
    /// use std::u32;
A
Aaron Turon 已提交
902
    ///
903
    /// let v = vec!(1, 2);
N
Niko Matsakis 已提交
904 905
    /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|&x: &u32|
    ///     if x == u32::MAX { Err("Overflow!") }
A
Aaron Turon 已提交
906 907
    ///     else { Ok(x + 1) }
    /// ).collect();
908
    /// assert!(res == Ok(vec!(2, 3)));
A
Aaron Turon 已提交
909 910
    /// ```
    #[inline]
A
Alexis 已提交
911
    fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
A
Aaron Turon 已提交
912 913 914 915 916 917 918 919
        // FIXME(#11084): This could be replaced with Iterator::scan when this
        // performance bug is closed.

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

920 921 922
        impl<T, E, Iter: Iterator<Item=Result<T, E>>> Iterator for Adapter<Iter, E> {
            type Item = T;

A
Aaron Turon 已提交
923 924 925 926 927 928 929 930 931
            #[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,
932
                }
933
            }
934
        }
935

A
Alexis 已提交
936
        let mut adapter = Adapter { iter: iter.into_iter(), err: None };
A
Aaron Turon 已提交
937
        let v: V = FromIterator::from_iter(adapter.by_ref());
938

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

946 947 948 949
/////////////////////////////////////////////////////////////////////////////
// FromIterator
/////////////////////////////////////////////////////////////////////////////

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