result.rs 30.3 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
//! let good_result: Result<i32, i32> = Ok(10);
//! let bad_result: Result<i32, i32> = Err(10);
65 66 67 68 69 70
//!
//! // 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.
71 72
//! let good_result: Result<i32, i32> = good_result.map(|i| i + 1);
//! let bad_result: Result<i32, i32> = bad_result.map(|i| i - 1);
73 74
//!
//! // Use `and_then` to continue the computation.
75
//! let good_result: Result<bool, i32> = good_result.and_then(|i| Ok(i == 11));
76 77
//!
//! // Use `or_else` to handle the error.
78
//! let bad_result: Result<i32, i32> = bad_result.or_else(|i| Ok(11));
79
//!
B
Brian Anderson 已提交
80
//! // Consume the result and return the contents with `unwrap`.
81
//! let final_awesome_result = good_result.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
//!
//! Consider the `write_line` method defined for I/O types
G
Gary M. Josack 已提交
95
//! by the [`Writer`](../old_io/trait.Writer.html) trait:
96
//!
J
Jonas Hietala 已提交
97
//! ```
98
//! # #![feature(old_io)]
A
Alex Crichton 已提交
99
//! use std::old_io::IoError;
100 101 102 103
//!
//! trait Writer {
//!     fn write_line(&mut self, s: &str) -> Result<(), IoError>;
//! }
J
Jonas Hietala 已提交
104
//! ```
105 106
//!
//! *Note: The actual definition of `Writer` uses `IoResult`, which
J
Joseph Crail 已提交
107
//! is just a synonym for `Result<T, IoError>`.*
108
//!
109
//! This method doesn't produce a value, but the write may
110 111 112
//! fail. It's crucial to handle the error case, and *not* write
//! something like this:
//!
J
Jonas Hietala 已提交
113
//! ```{.ignore}
114
//! # #![feature(old_io)]
115 116
//! use std::old_io::*;
//! use std::old_path::Path;
117 118 119 120 121 122
//!
//! 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 已提交
123
//! ```
124
//!
125
//! If you *do* write that in Rust, the compiler will give you a
126 127 128
//! 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 已提交
129 130
//! panic, by converting to an `Option` with `ok`, then asserting
//! success with `expect`. This will panic if the write fails, proving
131 132
//! a marginally useful message indicating why:
//!
J
Jonas Hietala 已提交
133
//! ```{.no_run}
134
//! # #![feature(old_io, old_path)]
135 136
//! use std::old_io::*;
//! use std::old_path::Path;
137 138 139 140
//!
//! 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 已提交
141
//! ```
142 143 144
//!
//! You might also simply assert success:
//!
J
Jonas Hietala 已提交
145
//! ```{.no_run}
146
//! # #![feature(old_io, old_path)]
147 148
//! # use std::old_io::*;
//! # use std::old_path::Path;
149 150 151 152
//!
//! # 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 已提交
153
//! ```
154 155 156
//!
//! Or propagate the error up the call stack with `try!`:
//!
J
Jonas Hietala 已提交
157
//! ```
158
//! # #![feature(old_io, old_path)]
159 160
//! # use std::old_io::*;
//! # use std::old_path::Path;
161 162 163 164 165 166
//! 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 已提交
167
//! ```
168 169 170 171 172 173 174 175 176 177
//!
//! # 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 已提交
178
//! ```
179
//! # #![feature(old_io, old_path)]
180 181
//! use std::old_io::*;
//! use std::old_path::Path;
182
//!
183
//! struct Info {
184
//!     name: String,
185 186
//!     age: i32,
//!     rating: i32,
187
//! }
188 189 190 191
//!
//! 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
192
//!     if let Err(e) = file.write_line(&format!("name: {}", info.name)) {
193
//!         return Err(e)
194
//!     }
195
//!     if let Err(e) = file.write_line(&format!("age: {}", info.age)) {
196
//!         return Err(e)
197
//!     }
198
//!     return file.write_line(&format!("rating: {}", info.rating));
199
//! }
J
Jonas Hietala 已提交
200
//! ```
201 202 203
//!
//! With this:
//!
J
Jonas Hietala 已提交
204
//! ```
205
//! # #![feature(old_io, old_path)]
206 207
//! use std::old_io::*;
//! use std::old_path::Path;
208
//!
209
//! struct Info {
210
//!     name: String,
211 212
//!     age: i32,
//!     rating: i32,
213
//! }
214 215 216 217
//!
//! 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
218 219 220
//!     try!(file.write_line(&format!("name: {}", info.name)));
//!     try!(file.write_line(&format!("age: {}", info.age)));
//!     try!(file.write_line(&format!("rating: {}", info.rating)));
221 222
//!     return Ok(());
//! }
J
Jonas Hietala 已提交
223
//! ```
224 225 226 227 228 229 230 231
//!
//! *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 已提交
232
//! ```
233
//! macro_rules! try {
234
//!     ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
235
//! }
J
Jonas Hietala 已提交
236
//! ```
237 238
//!
//! `try!` is imported by the prelude, and is available everywhere.
239

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

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

244
use clone::Clone;
245
use fmt;
S
Steven Fackler 已提交
246
use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSizeIterator, IntoIterator};
247
use ops::{FnMut, FnOnce};
248
use option::Option::{self, None, Some};
A
Aaron Turon 已提交
249
#[allow(deprecated)]
250 251
use slice::AsSlice;
use slice;
252 253

/// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
254 255
///
/// See the [`std::result`](index.html) module documentation for details.
J
Jorge Aparicio 已提交
256
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
257
#[must_use]
B
Brian Anderson 已提交
258
#[stable(feature = "rust1", since = "1.0.0")]
259
pub enum Result<T, E> {
M
Marvin Löbel 已提交
260
    /// Contains the success value
B
Brian Anderson 已提交
261
    #[stable(feature = "rust1", since = "1.0.0")]
262
    Ok(T),
M
Marvin Löbel 已提交
263

264
    /// Contains the error value
B
Brian Anderson 已提交
265
    #[stable(feature = "rust1", since = "1.0.0")]
266
    Err(E)
267 268
}

269 270 271 272
/////////////////////////////////////////////////////////////////////////////
// Type implementation
/////////////////////////////////////////////////////////////////////////////

B
Brian Anderson 已提交
273
#[stable(feature = "rust1", since = "1.0.0")]
M
Marvin Löbel 已提交
274
impl<T, E> Result<T, E> {
275 276 277
    /////////////////////////////////////////////////////////////////////////
    // Querying the contained values
    /////////////////////////////////////////////////////////////////////////
278

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

299
    /// Returns true if the result is `Err`
300
    ///
S
Steve Klabnik 已提交
301
    /// # Examples
302
    ///
J
Jonas Hietala 已提交
303
    /// ```
304
    /// let x: Result<i32, &str> = Ok(-3);
J
Jonas Hietala 已提交
305
    /// assert_eq!(x.is_err(), false);
306
    ///
307
    /// let x: Result<i32, &str> = Err("Some error message");
J
Jonas Hietala 已提交
308 309
    /// assert_eq!(x.is_err(), true);
    /// ```
310
    #[inline]
B
Brian Anderson 已提交
311
    #[stable(feature = "rust1", since = "1.0.0")]
E
Erick Tryzelaar 已提交
312 313 314
    pub fn is_err(&self) -> bool {
        !self.is_ok()
    }
315

316
    /////////////////////////////////////////////////////////////////////////
M
Marvin Löbel 已提交
317
    // Adapter for each variant
318 319
    /////////////////////////////////////////////////////////////////////////

M
Marvin Löbel 已提交
320
    /// Convert from `Result<T, E>` to `Option<T>`
321 322 323 324
    ///
    /// Converts `self` into an `Option<T>`, consuming `self`,
    /// and discarding the error, if any.
    ///
S
Steve Klabnik 已提交
325
    /// # Examples
326
    ///
J
Jonas Hietala 已提交
327
    /// ```
N
Niko Matsakis 已提交
328
    /// let x: Result<u32, &str> = Ok(2);
J
Jonas Hietala 已提交
329
    /// assert_eq!(x.ok(), Some(2));
330
    ///
N
Niko Matsakis 已提交
331
    /// let x: Result<u32, &str> = Err("Nothing here");
J
Jonas Hietala 已提交
332 333
    /// assert_eq!(x.ok(), None);
    /// ```
334
    #[inline]
B
Brian Anderson 已提交
335
    #[stable(feature = "rust1", since = "1.0.0")]
M
Marvin Löbel 已提交
336
    pub fn ok(self) -> Option<T> {
337
        match self {
M
Marvin Löbel 已提交
338 339
            Ok(x)  => Some(x),
            Err(_) => None,
340 341
        }
    }
342

M
Marvin Löbel 已提交
343
    /// Convert from `Result<T, E>` to `Option<E>`
344
    ///
345
    /// Converts `self` into an `Option<E>`, consuming `self`,
346
    /// and discarding the success value, if any.
J
Jonas Hietala 已提交
347
    ///
S
Steve Klabnik 已提交
348
    /// # Examples
J
Jonas Hietala 已提交
349 350
    ///
    /// ```
N
Niko Matsakis 已提交
351
    /// let x: Result<u32, &str> = Ok(2);
J
Jonas Hietala 已提交
352 353
    /// assert_eq!(x.err(), None);
    ///
N
Niko Matsakis 已提交
354
    /// let x: Result<u32, &str> = Err("Nothing here");
J
Jonas Hietala 已提交
355 356
    /// assert_eq!(x.err(), Some("Nothing here"));
    /// ```
357
    #[inline]
B
Brian Anderson 已提交
358
    #[stable(feature = "rust1", since = "1.0.0")]
M
Marvin Löbel 已提交
359
    pub fn err(self) -> Option<E> {
360
        match self {
M
Marvin Löbel 已提交
361 362
            Ok(_)  => None,
            Err(x) => Some(x),
363
        }
364 365
    }

M
Marvin Löbel 已提交
366 367 368 369 370
    /////////////////////////////////////////////////////////////////////////
    // Adapter for working with references
    /////////////////////////////////////////////////////////////////////////

    /// Convert from `Result<T, E>` to `Result<&T, &E>`
371 372 373
    ///
    /// Produces a new `Result`, containing a reference
    /// into the original, leaving the original in place.
J
Jonas Hietala 已提交
374 375
    ///
    /// ```
N
Niko Matsakis 已提交
376
    /// let x: Result<u32, &str> = Ok(2);
J
Jonas Hietala 已提交
377 378
    /// assert_eq!(x.as_ref(), Ok(&2));
    ///
N
Niko Matsakis 已提交
379
    /// let x: Result<u32, &str> = Err("Error");
J
Jonas Hietala 已提交
380 381
    /// assert_eq!(x.as_ref(), Err(&"Error"));
    /// ```
382
    #[inline]
B
Brian Anderson 已提交
383
    #[stable(feature = "rust1", since = "1.0.0")]
384
    pub fn as_ref(&self) -> Result<&T, &E> {
M
Marvin Löbel 已提交
385 386 387
        match *self {
            Ok(ref x) => Ok(x),
            Err(ref x) => Err(x),
388 389 390
        }
    }

M
Marvin Löbel 已提交
391
    /// Convert from `Result<T, E>` to `Result<&mut T, &mut E>`
J
Jonas Hietala 已提交
392 393
    ///
    /// ```
394
    /// fn mutate(r: &mut Result<i32, i32>) {
J
Jonas Hietala 已提交
395
    ///     match r.as_mut() {
J
Jorge Aparicio 已提交
396 397
    ///         Ok(&mut ref mut v) => *v = 42,
    ///         Err(&mut ref mut e) => *e = 0,
J
Jonas Hietala 已提交
398 399 400
    ///     }
    /// }
    ///
401
    /// let mut x: Result<i32, i32> = Ok(2);
J
Jonas Hietala 已提交
402 403 404
    /// mutate(&mut x);
    /// assert_eq!(x.unwrap(), 42);
    ///
405
    /// let mut x: Result<i32, i32> = Err(13);
J
Jonas Hietala 已提交
406 407 408
    /// mutate(&mut x);
    /// assert_eq!(x.unwrap_err(), 0);
    /// ```
409
    #[inline]
B
Brian Anderson 已提交
410
    #[stable(feature = "rust1", since = "1.0.0")]
411
    pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
M
Marvin Löbel 已提交
412 413 414
        match *self {
            Ok(ref mut x) => Ok(x),
            Err(ref mut x) => Err(x),
415 416
        }
    }
417

A
Aaron Turon 已提交
418 419 420 421 422 423 424 425 426 427 428 429 430 431
    /// Convert from `Result<T, E>` to `&[T]` (without copying)
    #[inline]
    #[unstable(feature = "as_slice", since = "unsure of the utility here")]
    pub fn as_slice(&self) -> &[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 已提交
432
    /// Convert from `Result<T, E>` to `&mut [T]` (without copying)
J
Jonas Hietala 已提交
433 434
    ///
    /// ```
435
    /// # #![feature(core)]
N
Niko Matsakis 已提交
436
    /// let mut x: Result<&str, u32> = Ok("Gold");
J
Jonas Hietala 已提交
437 438
    /// {
    ///     let v = x.as_mut_slice();
J
Jorge Aparicio 已提交
439
    ///     assert!(v == ["Gold"]);
J
Jonas Hietala 已提交
440
    ///     v[0] = "Silver";
J
Jorge Aparicio 已提交
441
    ///     assert!(v == ["Silver"]);
J
Jonas Hietala 已提交
442 443 444
    /// }
    /// assert_eq!(x, Ok("Silver"));
    ///
N
Niko Matsakis 已提交
445
    /// let mut x: Result<&str, u32> = Err(45);
J
Jorge Aparicio 已提交
446
    /// assert!(x.as_mut_slice().is_empty());
J
Jonas Hietala 已提交
447
    /// ```
A
Aaron Turon 已提交
448
    #[inline]
449
    #[unstable(feature = "core",
450
               reason = "waiting for mut conventions")]
451
    pub fn as_mut_slice(&mut self) -> &mut [T] {
A
Aaron Turon 已提交
452 453 454 455 456 457 458 459 460 461
        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
            }
        }
    }

462 463 464 465
    /////////////////////////////////////////////////////////////////////////
    // Transforming contained values
    /////////////////////////////////////////////////////////////////////////

V
Virgile Andreani 已提交
466
    /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to an
467
    /// contained `Ok` value, leaving an `Err` value untouched.
468
    ///
469
    /// This function can be used to compose the results of two functions.
470
    ///
S
Steve Klabnik 已提交
471
    /// # Examples
472 473 474 475
    ///
    /// Sum the lines of a buffer by mapping strings to numbers,
    /// ignoring I/O and parse errors:
    ///
J
Jonas Hietala 已提交
476
    /// ```
477
    /// # #![feature(old_io)]
478
    /// use std::old_io::*;
479
    ///
V
Vadim Petrochenkov 已提交
480 481
    /// let mut buffer: &[u8] = b"1\n2\n3\n4\n";
    /// let mut buffer = &mut buffer;
482 483
    ///
    /// let mut sum = 0;
484
    ///
E
Erick Tryzelaar 已提交
485 486
    /// while !buffer.is_empty() {
    ///     let line: IoResult<String> = buffer.read_line();
487
    ///     // Convert the string line to a number using `map` and `from_str`
488 489
    ///     let val: IoResult<i32> = line.map(|line| {
    ///         line.trim_right().parse::<i32>().unwrap_or(0)
490 491
    ///     });
    ///     // Add the value if there were no errors, otherwise add 0
492
    ///     sum += val.unwrap_or(0);
493
    /// }
494 495
    ///
    /// assert!(sum == 10);
J
Jonas Hietala 已提交
496
    /// ```
497
    #[inline]
B
Brian Anderson 已提交
498
    #[stable(feature = "rust1", since = "1.0.0")]
499
    pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
500
        match self {
501 502
            Ok(t) => Ok(op(t)),
            Err(e) => Err(e)
503 504 505
        }
    }

V
Virgile Andreani 已提交
506
    /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to an
507
    /// contained `Err` value, leaving an `Ok` value untouched.
508
    ///
509 510
    /// This function can be used to pass through a successful result while handling
    /// an error.
J
Jonas Hietala 已提交
511
    ///
S
Steve Klabnik 已提交
512
    /// # Examples
J
Jonas Hietala 已提交
513 514
    ///
    /// ```
N
Niko Matsakis 已提交
515
    /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
J
Jonas Hietala 已提交
516
    ///
N
Niko Matsakis 已提交
517
    /// let x: Result<u32, u32> = Ok(2);
518
    /// assert_eq!(x.map_err(stringify), Ok(2));
J
Jonas Hietala 已提交
519
    ///
N
Niko Matsakis 已提交
520
    /// let x: Result<u32, u32> = Err(13);
J
Jonas Hietala 已提交
521 522
    /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
    /// ```
523
    #[inline]
B
Brian Anderson 已提交
524
    #[stable(feature = "rust1", since = "1.0.0")]
525
    pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> {
526
        match self {
527 528
            Ok(t) => Ok(t),
            Err(e) => Err(op(e))
529 530 531
        }
    }

A
Aaron Turon 已提交
532 533 534 535 536
    /////////////////////////////////////////////////////////////////////////
    // Iterator constructors
    /////////////////////////////////////////////////////////////////////////

    /// Returns an iterator over the possibly contained value.
J
Jonas Hietala 已提交
537
    ///
S
Steve Klabnik 已提交
538
    /// # Examples
J
Jonas Hietala 已提交
539 540
    ///
    /// ```
N
Niko Matsakis 已提交
541
    /// let x: Result<u32, &str> = Ok(7);
J
Jonas Hietala 已提交
542 543
    /// assert_eq!(x.iter().next(), Some(&7));
    ///
N
Niko Matsakis 已提交
544
    /// let x: Result<u32, &str> = Err("nothing!");
J
Jonas Hietala 已提交
545 546
    /// assert_eq!(x.iter().next(), None);
    /// ```
A
Aaron Turon 已提交
547
    #[inline]
B
Brian Anderson 已提交
548
    #[stable(feature = "rust1", since = "1.0.0")]
549 550
    pub fn iter(&self) -> Iter<T> {
        Iter { inner: self.as_ref().ok() }
A
Aaron Turon 已提交
551 552 553
    }

    /// Returns a mutable iterator over the possibly contained value.
J
Jonas Hietala 已提交
554
    ///
S
Steve Klabnik 已提交
555
    /// # Examples
J
Jonas Hietala 已提交
556 557
    ///
    /// ```
N
Niko Matsakis 已提交
558
    /// let mut x: Result<u32, &str> = Ok(7);
J
Jonas Hietala 已提交
559
    /// match x.iter_mut().next() {
J
Jorge Aparicio 已提交
560
    ///     Some(&mut ref mut x) => *x = 40,
J
Jonas Hietala 已提交
561 562 563 564
    ///     None => {},
    /// }
    /// assert_eq!(x, Ok(40));
    ///
N
Niko Matsakis 已提交
565
    /// let mut x: Result<u32, &str> = Err("nothing!");
J
Jonas Hietala 已提交
566 567
    /// assert_eq!(x.iter_mut().next(), None);
    /// ```
A
Aaron Turon 已提交
568
    #[inline]
B
Brian Anderson 已提交
569
    #[stable(feature = "rust1", since = "1.0.0")]
570 571
    pub fn iter_mut(&mut self) -> IterMut<T> {
        IterMut { inner: self.as_mut().ok() }
A
Aaron Turon 已提交
572 573 574
    }

    /// Returns a consuming iterator over the possibly contained value.
J
Jonas Hietala 已提交
575
    ///
S
Steve Klabnik 已提交
576
    /// # Examples
J
Jonas Hietala 已提交
577 578
    ///
    /// ```
N
Niko Matsakis 已提交
579 580
    /// let x: Result<u32, &str> = Ok(5);
    /// let v: Vec<u32> = x.into_iter().collect();
581
    /// assert_eq!(v, [5]);
J
Jonas Hietala 已提交
582
    ///
N
Niko Matsakis 已提交
583 584
    /// let x: Result<u32, &str> = Err("nothing!");
    /// let v: Vec<u32> = x.into_iter().collect();
585
    /// assert_eq!(v, []);
J
Jonas Hietala 已提交
586
    /// ```
A
Aaron Turon 已提交
587
    #[inline]
B
Brian Anderson 已提交
588
    #[stable(feature = "rust1", since = "1.0.0")]
589 590
    pub fn into_iter(self) -> IntoIter<T> {
        IntoIter { inner: self.ok() }
A
Aaron Turon 已提交
591 592
    }

593 594 595 596 597
    ////////////////////////////////////////////////////////////////////////
    // 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 已提交
598
    ///
S
Steve Klabnik 已提交
599
    /// # Examples
J
Jonas Hietala 已提交
600 601
    ///
    /// ```
N
Niko Matsakis 已提交
602
    /// let x: Result<u32, &str> = Ok(2);
J
Jonas Hietala 已提交
603 604 605
    /// let y: Result<&str, &str> = Err("late error");
    /// assert_eq!(x.and(y), Err("late error"));
    ///
N
Niko Matsakis 已提交
606
    /// let x: Result<u32, &str> = Err("early error");
J
Jonas Hietala 已提交
607 608 609
    /// let y: Result<&str, &str> = Ok("foo");
    /// assert_eq!(x.and(y), Err("early error"));
    ///
N
Niko Matsakis 已提交
610
    /// let x: Result<u32, &str> = Err("not a 2");
J
Jonas Hietala 已提交
611 612 613
    /// let y: Result<&str, &str> = Err("late error");
    /// assert_eq!(x.and(y), Err("not a 2"));
    ///
N
Niko Matsakis 已提交
614
    /// let x: Result<u32, &str> = Ok(2);
J
Jonas Hietala 已提交
615 616 617
    /// let y: Result<&str, &str> = Ok("different result type");
    /// assert_eq!(x.and(y), Ok("different result type"));
    /// ```
618
    #[inline]
B
Brian Anderson 已提交
619
    #[stable(feature = "rust1", since = "1.0.0")]
620
    pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
621 622
        match self {
            Ok(_) => res,
623
            Err(e) => Err(e),
624 625 626
        }
    }

627
    /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
628
    ///
J
Jonas Hietala 已提交
629 630
    /// This function can be used for control flow based on result values.
    ///
S
Steve Klabnik 已提交
631
    /// # Examples
J
Jonas Hietala 已提交
632 633
    ///
    /// ```
N
Niko Matsakis 已提交
634 635
    /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
    /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
J
Jonas Hietala 已提交
636 637 638 639 640 641
    ///
    /// 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));
    /// ```
642
    #[inline]
B
Brian Anderson 已提交
643
    #[stable(feature = "rust1", since = "1.0.0")]
644
    pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
645 646
        match self {
            Ok(t) => op(t),
647
            Err(e) => Err(e),
648
        }
649 650
    }

651
    /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
J
Jonas Hietala 已提交
652
    ///
S
Steve Klabnik 已提交
653
    /// # Examples
J
Jonas Hietala 已提交
654 655
    ///
    /// ```
N
Niko Matsakis 已提交
656 657
    /// let x: Result<u32, &str> = Ok(2);
    /// let y: Result<u32, &str> = Err("late error");
J
Jonas Hietala 已提交
658 659
    /// assert_eq!(x.or(y), Ok(2));
    ///
N
Niko Matsakis 已提交
660 661
    /// let x: Result<u32, &str> = Err("early error");
    /// let y: Result<u32, &str> = Ok(2);
J
Jonas Hietala 已提交
662 663
    /// assert_eq!(x.or(y), Ok(2));
    ///
N
Niko Matsakis 已提交
664 665
    /// let x: Result<u32, &str> = Err("not a 2");
    /// let y: Result<u32, &str> = Err("late error");
J
Jonas Hietala 已提交
666 667
    /// assert_eq!(x.or(y), Err("late error"));
    ///
N
Niko Matsakis 已提交
668 669
    /// let x: Result<u32, &str> = Ok(2);
    /// let y: Result<u32, &str> = Ok(100);
J
Jonas Hietala 已提交
670 671
    /// assert_eq!(x.or(y), Ok(2));
    /// ```
672
    #[inline]
B
Brian Anderson 已提交
673
    #[stable(feature = "rust1", since = "1.0.0")]
674
    pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
675
        match self {
676
            Ok(v) => Ok(v),
677 678 679 680
            Err(_) => res,
        }
    }

681
    /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
682
    ///
J
Jonas Hietala 已提交
683 684
    /// This function can be used for control flow based on result values.
    ///
S
Steve Klabnik 已提交
685
    /// # Examples
J
Jonas Hietala 已提交
686 687
    ///
    /// ```
N
Niko Matsakis 已提交
688 689
    /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
    /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
J
Jonas Hietala 已提交
690 691 692 693 694 695
    ///
    /// 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));
    /// ```
696
    #[inline]
B
Brian Anderson 已提交
697
    #[stable(feature = "rust1", since = "1.0.0")]
698
    pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
699 700
        match self {
            Ok(t) => Ok(t),
701
            Err(e) => op(e),
702
        }
703
    }
704

M
Marvin Löbel 已提交
705
    /// Unwraps a result, yielding the content of an `Ok`.
706
    /// Else it returns `optb`.
J
Jonas Hietala 已提交
707
    ///
S
Steve Klabnik 已提交
708
    /// # Examples
J
Jonas Hietala 已提交
709 710
    ///
    /// ```
711
    /// let optb = 2;
N
Niko Matsakis 已提交
712
    /// let x: Result<u32, &str> = Ok(9);
713
    /// assert_eq!(x.unwrap_or(optb), 9);
J
Jonas Hietala 已提交
714
    ///
N
Niko Matsakis 已提交
715
    /// let x: Result<u32, &str> = Err("error");
J
Jonas Hietala 已提交
716 717
    /// assert_eq!(x.unwrap_or(optb), optb);
    /// ```
718
    #[inline]
B
Brian Anderson 已提交
719
    #[stable(feature = "rust1", since = "1.0.0")]
720
    pub fn unwrap_or(self, optb: T) -> T {
M
Marvin Löbel 已提交
721 722
        match self {
            Ok(t) => t,
723
            Err(_) => optb
M
Marvin Löbel 已提交
724 725 726
        }
    }

727
    /// Unwraps a result, yielding the content of an `Ok`.
728
    /// If the value is an `Err` then it calls `op` with its value.
J
Jonas Hietala 已提交
729
    ///
S
Steve Klabnik 已提交
730
    /// # Examples
J
Jonas Hietala 已提交
731 732
    ///
    /// ```
N
Niko Matsakis 已提交
733
    /// fn count(x: &str) -> usize { x.len() }
J
Jonas Hietala 已提交
734
    ///
735 736
    /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
    /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
J
Jonas Hietala 已提交
737
    /// ```
738
    #[inline]
B
Brian Anderson 已提交
739
    #[stable(feature = "rust1", since = "1.0.0")]
740
    pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
741 742
        match self {
            Ok(t) => t,
743
            Err(e) => op(e)
744 745
        }
    }
746
}
747

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

B
Brian Anderson 已提交
779
#[stable(feature = "rust1", since = "1.0.0")]
780
impl<T: fmt::Debug, E> Result<T, E> {
781 782
    /// Unwraps a result, yielding the content of an `Err`.
    ///
S
Steve Klabnik 已提交
783
    /// # Panics
784
    ///
S
Steve Klabnik 已提交
785
    /// Panics if the value is an `Ok`, with a custom panic message provided
786
    /// by the `Ok`'s value.
J
Jonas Hietala 已提交
787
    ///
S
Steve Klabnik 已提交
788
    /// # Examples
J
Jonas Hietala 已提交
789
    ///
790
    /// ```{.should_panic}
N
Niko Matsakis 已提交
791
    /// let x: Result<u32, &str> = Ok(2);
S
Steve Klabnik 已提交
792
    /// x.unwrap_err(); // panics with `2`
J
Jonas Hietala 已提交
793 794 795
    /// ```
    ///
    /// ```
N
Niko Matsakis 已提交
796
    /// let x: Result<u32, &str> = Err("emergency failure");
J
Jonas Hietala 已提交
797 798
    /// assert_eq!(x.unwrap_err(), "emergency failure");
    /// ```
799
    #[inline]
B
Brian Anderson 已提交
800
    #[stable(feature = "rust1", since = "1.0.0")]
801 802 803
    pub fn unwrap_err(self) -> E {
        match self {
            Ok(t) =>
804
                panic!("called `Result::unwrap_err()` on an `Ok` value: {:?}", t),
805 806 807 808 809
            Err(e) => e
        }
    }
}

810 811 812 813
/////////////////////////////////////////////////////////////////////////////
// Trait implementations
/////////////////////////////////////////////////////////////////////////////

A
Aaron Turon 已提交
814 815 816 817 818
#[unstable(feature = "core",
           reason = "waiting on the stability of the trait itself")]
#[deprecated(since = "1.0.0",
             reason = "use inherent method instead")]
#[allow(deprecated)]
819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
impl<T, E> AsSlice<T> for Result<T, E> {
    /// Convert from `Result<T, E>` to `&[T]` (without copying)
    #[inline]
    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 已提交
834
/////////////////////////////////////////////////////////////////////////////
835
// The Result Iterators
A
Aaron Turon 已提交
836 837
/////////////////////////////////////////////////////////////////////////////

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

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

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

B
Brian Anderson 已提交
855
#[stable(feature = "rust1", since = "1.0.0")]
856
impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
857 858 859 860
    #[inline]
    fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
}

B
Brian Anderson 已提交
861
#[stable(feature = "rust1", since = "1.0.0")]
862
impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
863 864 865 866 867 868

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 已提交
869
#[stable(feature = "rust1", since = "1.0.0")]
870
pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
A
Aaron Turon 已提交
871

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

876 877
    #[inline]
    fn next(&mut self) -> Option<&'a mut T> { self.inner.take() }
A
Aaron Turon 已提交
878
    #[inline]
N
Niko Matsakis 已提交
879
    fn size_hint(&self) -> (usize, Option<usize>) {
880 881
        let n = if self.inner.is_some() {1} else {0};
        (n, Some(n))
A
Aaron Turon 已提交
882 883
    }
}
884

B
Brian Anderson 已提交
885
#[stable(feature = "rust1", since = "1.0.0")]
886
impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
A
Aaron Turon 已提交
887
    #[inline]
888 889 890
    fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
}

B
Brian Anderson 已提交
891
#[stable(feature = "rust1", since = "1.0.0")]
892
impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
893 894

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

B
Brian Anderson 已提交
898
#[stable(feature = "rust1", since = "1.0.0")]
899 900 901
impl<T> Iterator for IntoIter<T> {
    type Item = T;

902 903 904
    #[inline]
    fn next(&mut self) -> Option<T> { self.inner.take() }
    #[inline]
N
Niko Matsakis 已提交
905
    fn size_hint(&self) -> (usize, Option<usize>) {
906 907
        let n = if self.inner.is_some() {1} else {0};
        (n, Some(n))
908
    }
A
Aaron Turon 已提交
909 910
}

B
Brian Anderson 已提交
911
#[stable(feature = "rust1", since = "1.0.0")]
912
impl<T> DoubleEndedIterator for IntoIter<T> {
913 914 915 916
    #[inline]
    fn next_back(&mut self) -> Option<T> { self.inner.take() }
}

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

A
Aaron Turon 已提交
920
/////////////////////////////////////////////////////////////////////////////
921
// FromIterator
A
Aaron Turon 已提交
922 923
/////////////////////////////////////////////////////////////////////////////

B
Brian Anderson 已提交
924
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
925 926 927 928 929 930 931 932
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:
    ///
933
    /// ```
N
Niko Matsakis 已提交
934
    /// use std::u32;
A
Aaron Turon 已提交
935
    ///
936
    /// let v = vec!(1, 2);
N
Niko Matsakis 已提交
937 938
    /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|&x: &u32|
    ///     if x == u32::MAX { Err("Overflow!") }
A
Aaron Turon 已提交
939 940
    ///     else { Ok(x + 1) }
    /// ).collect();
941
    /// assert!(res == Ok(vec!(2, 3)));
A
Aaron Turon 已提交
942 943
    /// ```
    #[inline]
A
Alexis 已提交
944
    fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
A
Aaron Turon 已提交
945 946 947 948 949 950 951 952
        // FIXME(#11084): This could be replaced with Iterator::scan when this
        // performance bug is closed.

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

953 954 955
        impl<T, E, Iter: Iterator<Item=Result<T, E>>> Iterator for Adapter<Iter, E> {
            type Item = T;

A
Aaron Turon 已提交
956 957 958 959 960 961 962 963 964
            #[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,
965
                }
966
            }
967
        }
968

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

A
Aaron Turon 已提交
972 973 974 975
        match adapter.err {
            Some(err) => Err(err),
            None => Ok(v),
        }
976 977 978
    }
}

979 980 981 982
/////////////////////////////////////////////////////////////////////////////
// FromIterator
/////////////////////////////////////////////////////////////////////////////

983
/// Perform a fold operation over the result values from an iterator.
984
///
985 986
/// If an `Err` is encountered, it is immediately returned.
/// Otherwise, the folded value is returned.
987
#[inline]
988
#[unstable(feature = "core")]
989 990 991
pub fn fold<T,
            V,
            E,
992
            F: FnMut(V, T) -> V,
993
            Iter: Iterator<Item=Result<T, E>>>(
J
Jorge Aparicio 已提交
994
            iterator: Iter,
995
            mut init: V,
996
            mut f: F)
997
            -> Result<V, E> {
998 999 1000 1001
    for t in iterator {
        match t {
            Ok(v) => init = f(init, v),
            Err(u) => return Err(u)
1002 1003
        }
    }
1004
    Ok(init)
1005
}