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

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

243
use fmt;
244
use iter::{FromIterator, FusedIterator, TrustedLen};
245
use ops;
246

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

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

266 267 268 269
/////////////////////////////////////////////////////////////////////////////
// Type implementation
/////////////////////////////////////////////////////////////////////////////

M
Marvin Löbel 已提交
270
impl<T, E> Result<T, E> {
271 272 273
    /////////////////////////////////////////////////////////////////////////
    // Querying the contained values
    /////////////////////////////////////////////////////////////////////////
274

275 276 277
    /// Returns `true` if the result is [`Ok`].
    ///
    /// [`Ok`]: enum.Result.html#variant.Ok
278
    ///
S
Steve Klabnik 已提交
279
    /// # Examples
280
    ///
281 282
    /// Basic usage:
    ///
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 300 301
    /// Returns `true` if the result is [`Err`].
    ///
    /// [`Err`]: enum.Result.html#variant.Err
302
    ///
S
Steve Klabnik 已提交
303
    /// # Examples
304
    ///
305 306
    /// Basic usage:
    ///
J
Jonas Hietala 已提交
307
    /// ```
308
    /// let x: Result<i32, &str> = Ok(-3);
J
Jonas Hietala 已提交
309
    /// assert_eq!(x.is_err(), false);
310
    ///
311
    /// let x: Result<i32, &str> = Err("Some error message");
J
Jonas Hietala 已提交
312 313
    /// assert_eq!(x.is_err(), true);
    /// ```
314
    #[inline]
B
Brian Anderson 已提交
315
    #[stable(feature = "rust1", since = "1.0.0")]
E
Erick Tryzelaar 已提交
316 317 318
    pub fn is_err(&self) -> bool {
        !self.is_ok()
    }
319

320
    /////////////////////////////////////////////////////////////////////////
M
Marvin Löbel 已提交
321
    // Adapter for each variant
322 323
    /////////////////////////////////////////////////////////////////////////

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

G
ggomez 已提交
351
    /// Converts from `Result<T, E>` to [`Option<E>`].
352
    ///
G
ggomez 已提交
353
    /// Converts `self` into an [`Option<E>`], consuming `self`,
354
    /// and discarding the success value, if any.
J
Jonas Hietala 已提交
355
    ///
G
ggomez 已提交
356 357
    /// [`Option<E>`]: ../../std/option/enum.Option.html
    ///
S
Steve Klabnik 已提交
358
    /// # Examples
J
Jonas Hietala 已提交
359
    ///
360 361
    /// Basic usage:
    ///
J
Jonas Hietala 已提交
362
    /// ```
N
Niko Matsakis 已提交
363
    /// let x: Result<u32, &str> = Ok(2);
J
Jonas Hietala 已提交
364 365
    /// assert_eq!(x.err(), None);
    ///
N
Niko Matsakis 已提交
366
    /// let x: Result<u32, &str> = Err("Nothing here");
J
Jonas Hietala 已提交
367 368
    /// assert_eq!(x.err(), Some("Nothing here"));
    /// ```
369
    #[inline]
B
Brian Anderson 已提交
370
    #[stable(feature = "rust1", since = "1.0.0")]
M
Marvin Löbel 已提交
371
    pub fn err(self) -> Option<E> {
372
        match self {
M
Marvin Löbel 已提交
373 374
            Ok(_)  => None,
            Err(x) => Some(x),
375
        }
376 377
    }

M
Marvin Löbel 已提交
378 379 380 381
    /////////////////////////////////////////////////////////////////////////
    // Adapter for working with references
    /////////////////////////////////////////////////////////////////////////

G
ggomez 已提交
382
    /// Converts from `Result<T, E>` to `Result<&T, &E>`.
383 384 385
    ///
    /// Produces a new `Result`, containing a reference
    /// into the original, leaving the original in place.
J
Jonas Hietala 已提交
386
    ///
387 388 389 390
    /// # Examples
    ///
    /// Basic usage:
    ///
J
Jonas Hietala 已提交
391
    /// ```
N
Niko Matsakis 已提交
392
    /// let x: Result<u32, &str> = Ok(2);
J
Jonas Hietala 已提交
393 394
    /// assert_eq!(x.as_ref(), Ok(&2));
    ///
N
Niko Matsakis 已提交
395
    /// let x: Result<u32, &str> = Err("Error");
J
Jonas Hietala 已提交
396 397
    /// assert_eq!(x.as_ref(), Err(&"Error"));
    /// ```
398
    #[inline]
B
Brian Anderson 已提交
399
    #[stable(feature = "rust1", since = "1.0.0")]
400
    pub fn as_ref(&self) -> Result<&T, &E> {
M
Marvin Löbel 已提交
401 402 403
        match *self {
            Ok(ref x) => Ok(x),
            Err(ref x) => Err(x),
404 405 406
        }
    }

G
ggomez 已提交
407
    /// Converts from `Result<T, E>` to `Result<&mut T, &mut E>`.
J
Jonas Hietala 已提交
408
    ///
409 410 411 412
    /// # Examples
    ///
    /// Basic usage:
    ///
J
Jonas Hietala 已提交
413
    /// ```
414
    /// fn mutate(r: &mut Result<i32, i32>) {
J
Jonas Hietala 已提交
415
    ///     match r.as_mut() {
416 417
    ///         Ok(v) => *v = 42,
    ///         Err(e) => *e = 0,
J
Jonas Hietala 已提交
418 419 420
    ///     }
    /// }
    ///
421
    /// let mut x: Result<i32, i32> = Ok(2);
J
Jonas Hietala 已提交
422 423 424
    /// mutate(&mut x);
    /// assert_eq!(x.unwrap(), 42);
    ///
425
    /// let mut x: Result<i32, i32> = Err(13);
J
Jonas Hietala 已提交
426 427 428
    /// mutate(&mut x);
    /// assert_eq!(x.unwrap_err(), 0);
    /// ```
429
    #[inline]
B
Brian Anderson 已提交
430
    #[stable(feature = "rust1", since = "1.0.0")]
431
    pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
M
Marvin Löbel 已提交
432 433 434
        match *self {
            Ok(ref mut x) => Ok(x),
            Err(ref mut x) => Err(x),
435 436
        }
    }
437

438 439 440 441
    /////////////////////////////////////////////////////////////////////////
    // Transforming contained values
    /////////////////////////////////////////////////////////////////////////

442
    /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
443
    /// contained [`Ok`] value, leaving an [`Err`] value untouched.
444
    ///
445
    /// This function can be used to compose the results of two functions.
446
    ///
447 448 449
    /// [`Ok`]: enum.Result.html#variant.Ok
    /// [`Err`]: enum.Result.html#variant.Err
    ///
S
Steve Klabnik 已提交
450
    /// # Examples
451
    ///
A
Alex Crichton 已提交
452
    /// Print the numbers on each line of a string multiplied by two.
453
    ///
J
Jonas Hietala 已提交
454
    /// ```
A
Alex Crichton 已提交
455
    /// let line = "1\n2\n3\n4\n";
456
    ///
A
Alex Crichton 已提交
457 458 459 460 461
    /// for num in line.lines() {
    ///     match num.parse::<i32>().map(|i| i * 2) {
    ///         Ok(n) => println!("{}", n),
    ///         Err(..) => {}
    ///     }
462
    /// }
J
Jonas Hietala 已提交
463
    /// ```
464
    #[inline]
B
Brian Anderson 已提交
465
    #[stable(feature = "rust1", since = "1.0.0")]
466
    pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
467
        match self {
468 469
            Ok(t) => Ok(op(t)),
            Err(e) => Err(e)
470 471 472
        }
    }

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

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

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

    /// Returns a mutable iterator over the possibly contained value.
J
Jonas Hietala 已提交
532
    ///
533 534
    /// The iterator yields one value if the result is [`Ok`], otherwise none.
    ///
S
Steve Klabnik 已提交
535
    /// # Examples
J
Jonas Hietala 已提交
536
    ///
537 538
    /// Basic usage:
    ///
J
Jonas Hietala 已提交
539
    /// ```
N
Niko Matsakis 已提交
540
    /// let mut x: Result<u32, &str> = Ok(7);
J
Jonas Hietala 已提交
541
    /// match x.iter_mut().next() {
542
    ///     Some(v) => *v = 40,
J
Jonas Hietala 已提交
543 544 545 546
    ///     None => {},
    /// }
    /// assert_eq!(x, Ok(40));
    ///
N
Niko Matsakis 已提交
547
    /// let mut x: Result<u32, &str> = Err("nothing!");
J
Jonas Hietala 已提交
548 549
    /// assert_eq!(x.iter_mut().next(), None);
    /// ```
550 551
    ///
    /// [`Ok`]: enum.Result.html#variant.Ok
A
Aaron Turon 已提交
552
    #[inline]
B
Brian Anderson 已提交
553
    #[stable(feature = "rust1", since = "1.0.0")]
554 555
    pub fn iter_mut(&mut self) -> IterMut<T> {
        IterMut { inner: self.as_mut().ok() }
A
Aaron Turon 已提交
556 557
    }

558 559 560 561
    ////////////////////////////////////////////////////////////////////////
    // Boolean operations on the values, eager and lazy
    /////////////////////////////////////////////////////////////////////////

562 563 564 565
    /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
    ///
    /// [`Ok`]: enum.Result.html#variant.Ok
    /// [`Err`]: enum.Result.html#variant.Err
J
Jonas Hietala 已提交
566
    ///
S
Steve Klabnik 已提交
567
    /// # Examples
J
Jonas Hietala 已提交
568
    ///
569 570
    /// Basic usage:
    ///
J
Jonas Hietala 已提交
571
    /// ```
N
Niko Matsakis 已提交
572
    /// let x: Result<u32, &str> = Ok(2);
J
Jonas Hietala 已提交
573 574 575
    /// let y: Result<&str, &str> = Err("late error");
    /// assert_eq!(x.and(y), Err("late error"));
    ///
N
Niko Matsakis 已提交
576
    /// let x: Result<u32, &str> = Err("early error");
J
Jonas Hietala 已提交
577 578 579
    /// let y: Result<&str, &str> = Ok("foo");
    /// assert_eq!(x.and(y), Err("early error"));
    ///
N
Niko Matsakis 已提交
580
    /// let x: Result<u32, &str> = Err("not a 2");
J
Jonas Hietala 已提交
581 582 583
    /// let y: Result<&str, &str> = Err("late error");
    /// assert_eq!(x.and(y), Err("not a 2"));
    ///
N
Niko Matsakis 已提交
584
    /// let x: Result<u32, &str> = Ok(2);
J
Jonas Hietala 已提交
585 586 587
    /// let y: Result<&str, &str> = Ok("different result type");
    /// assert_eq!(x.and(y), Ok("different result type"));
    /// ```
588
    #[inline]
B
Brian Anderson 已提交
589
    #[stable(feature = "rust1", since = "1.0.0")]
590
    pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
591 592
        match self {
            Ok(_) => res,
593
            Err(e) => Err(e),
594 595 596
        }
    }

597 598 599 600
    /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
    ///
    /// [`Ok`]: enum.Result.html#variant.Ok
    /// [`Err`]: enum.Result.html#variant.Err
601
    ///
G
ggomez 已提交
602
    /// This function can be used for control flow based on `Result` values.
J
Jonas Hietala 已提交
603
    ///
S
Steve Klabnik 已提交
604
    /// # Examples
J
Jonas Hietala 已提交
605
    ///
606 607
    /// Basic usage:
    ///
J
Jonas Hietala 已提交
608
    /// ```
N
Niko Matsakis 已提交
609 610
    /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
    /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
J
Jonas Hietala 已提交
611 612 613 614 615 616
    ///
    /// 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));
    /// ```
617
    #[inline]
B
Brian Anderson 已提交
618
    #[stable(feature = "rust1", since = "1.0.0")]
619
    pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
620 621
        match self {
            Ok(t) => op(t),
622
            Err(e) => Err(e),
623
        }
624 625
    }

626 627
    /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
    ///
628 629 630 631
    /// Arguments passed to `or` are eagerly evaluated; if you are passing the
    /// result of a function call, it is recommended to use `or_else`, which is
    /// lazily evaluated.
    ///
632 633
    /// [`Ok`]: enum.Result.html#variant.Ok
    /// [`Err`]: enum.Result.html#variant.Err
J
Jonas Hietala 已提交
634
    ///
S
Steve Klabnik 已提交
635
    /// # Examples
J
Jonas Hietala 已提交
636
    ///
637 638
    /// Basic usage:
    ///
J
Jonas Hietala 已提交
639
    /// ```
N
Niko Matsakis 已提交
640 641
    /// let x: Result<u32, &str> = Ok(2);
    /// let y: Result<u32, &str> = Err("late error");
J
Jonas Hietala 已提交
642 643
    /// assert_eq!(x.or(y), Ok(2));
    ///
N
Niko Matsakis 已提交
644 645
    /// let x: Result<u32, &str> = Err("early error");
    /// let y: Result<u32, &str> = Ok(2);
J
Jonas Hietala 已提交
646 647
    /// assert_eq!(x.or(y), Ok(2));
    ///
N
Niko Matsakis 已提交
648 649
    /// let x: Result<u32, &str> = Err("not a 2");
    /// let y: Result<u32, &str> = Err("late error");
J
Jonas Hietala 已提交
650 651
    /// assert_eq!(x.or(y), Err("late error"));
    ///
N
Niko Matsakis 已提交
652 653
    /// let x: Result<u32, &str> = Ok(2);
    /// let y: Result<u32, &str> = Ok(100);
J
Jonas Hietala 已提交
654 655
    /// assert_eq!(x.or(y), Ok(2));
    /// ```
656
    #[inline]
B
Brian Anderson 已提交
657
    #[stable(feature = "rust1", since = "1.0.0")]
658
    pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
659
        match self {
660
            Ok(v) => Ok(v),
661 662 663 664
            Err(_) => res,
        }
    }

665
    /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
666
    ///
J
Jonas Hietala 已提交
667 668
    /// This function can be used for control flow based on result values.
    ///
669 670 671
    /// [`Ok`]: enum.Result.html#variant.Ok
    /// [`Err`]: enum.Result.html#variant.Err
    ///
S
Steve Klabnik 已提交
672
    /// # Examples
J
Jonas Hietala 已提交
673
    ///
674 675
    /// Basic usage:
    ///
J
Jonas Hietala 已提交
676
    /// ```
N
Niko Matsakis 已提交
677 678
    /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
    /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
J
Jonas Hietala 已提交
679 680 681 682 683 684
    ///
    /// 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));
    /// ```
685
    #[inline]
B
Brian Anderson 已提交
686
    #[stable(feature = "rust1", since = "1.0.0")]
687
    pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
688 689
        match self {
            Ok(t) => Ok(t),
690
            Err(e) => op(e),
691
        }
692
    }
693

694
    /// Unwraps a result, yielding the content of an [`Ok`].
G
ggomez 已提交
695
    /// Else, it returns `optb`.
J
Jonas Hietala 已提交
696
    ///
697 698 699 700
    /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing 
    /// the result of a function call, it is recommended to use `unwrap_or_else`, 
    /// which is lazily evaluated. 
    ///
701 702 703
    /// [`Ok`]: enum.Result.html#variant.Ok
    /// [`Err`]: enum.Result.html#variant.Err
    ///
S
Steve Klabnik 已提交
704
    /// # Examples
J
Jonas Hietala 已提交
705
    ///
706 707
    /// Basic usage:
    ///
J
Jonas Hietala 已提交
708
    /// ```
709
    /// let optb = 2;
N
Niko Matsakis 已提交
710
    /// let x: Result<u32, &str> = Ok(9);
711
    /// assert_eq!(x.unwrap_or(optb), 9);
J
Jonas Hietala 已提交
712
    ///
N
Niko Matsakis 已提交
713
    /// let x: Result<u32, &str> = Err("error");
J
Jonas Hietala 已提交
714 715
    /// assert_eq!(x.unwrap_or(optb), optb);
    /// ```
716
    #[inline]
B
Brian Anderson 已提交
717
    #[stable(feature = "rust1", since = "1.0.0")]
718
    pub fn unwrap_or(self, optb: T) -> T {
M
Marvin Löbel 已提交
719 720
        match self {
            Ok(t) => t,
721
            Err(_) => optb
M
Marvin Löbel 已提交
722 723 724
        }
    }

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

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

784
    /// Unwraps a result, yielding the content of an [`Ok`].
785
    ///
786 787
    /// # Panics
    ///
788 789 790 791 792
    /// Panics if the value is an [`Err`], with a panic message including the
    /// passed message, and the content of the [`Err`].
    ///
    /// [`Ok`]: enum.Result.html#variant.Ok
    /// [`Err`]: enum.Result.html#variant.Err
793 794
    ///
    /// # Examples
795 796 797
    ///
    /// Basic usage:
    ///
798 799 800 801 802
    /// ```{.should_panic}
    /// let x: Result<u32, &str> = Err("emergency failure");
    /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
    /// ```
    #[inline]
803
    #[stable(feature = "result_expect", since = "1.4.0")]
804 805 806
    pub fn expect(self, msg: &str) -> T {
        match self {
            Ok(t) => t,
807
            Err(e) => unwrap_failed(msg, e),
808 809
        }
    }
810 811
}

812
impl<T: fmt::Debug, E> Result<T, E> {
813
    /// Unwraps a result, yielding the content of an [`Err`].
814
    ///
S
Steve Klabnik 已提交
815
    /// # Panics
816
    ///
817 818 819 820 821 822
    /// Panics if the value is an [`Ok`], with a custom panic message provided
    /// by the [`Ok`]'s value.
    ///
    /// [`Ok`]: enum.Result.html#variant.Ok
    /// [`Err`]: enum.Result.html#variant.Err
    ///
J
Jonas Hietala 已提交
823
    ///
S
Steve Klabnik 已提交
824
    /// # Examples
J
Jonas Hietala 已提交
825
    ///
826
    /// ```{.should_panic}
N
Niko Matsakis 已提交
827
    /// let x: Result<u32, &str> = Ok(2);
S
Steve Klabnik 已提交
828
    /// x.unwrap_err(); // panics with `2`
J
Jonas Hietala 已提交
829 830 831
    /// ```
    ///
    /// ```
N
Niko Matsakis 已提交
832
    /// let x: Result<u32, &str> = Err("emergency failure");
J
Jonas Hietala 已提交
833 834
    /// assert_eq!(x.unwrap_err(), "emergency failure");
    /// ```
835
    #[inline]
B
Brian Anderson 已提交
836
    #[stable(feature = "rust1", since = "1.0.0")]
837 838
    pub fn unwrap_err(self) -> E {
        match self {
839
            Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", t),
840
            Err(e) => e,
841 842
        }
    }
C
Clar Charr 已提交
843

844
    /// Unwraps a result, yielding the content of an [`Err`].
C
Clar Charr 已提交
845 846 847
    ///
    /// # Panics
    ///
848 849 850 851 852
    /// Panics if the value is an [`Ok`], with a panic message including the
    /// passed message, and the content of the [`Ok`].
    ///
    /// [`Ok`]: enum.Result.html#variant.Ok
    /// [`Err`]: enum.Result.html#variant.Err
C
Clar Charr 已提交
853 854 855 856 857 858 859 860 861 862
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```{.should_panic}
    /// let x: Result<u32, &str> = Ok(10);
    /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
    /// ```
    #[inline]
863
    #[stable(feature = "result_expect_err", since = "1.17.0")]
C
Clar Charr 已提交
864 865 866 867 868 869
    pub fn expect_err(self, msg: &str) -> E {
        match self {
            Ok(t) => unwrap_failed(msg, t),
            Err(e) => e,
        }
    }
870
}
871

872 873 874
impl<T: Default, E> Result<T, E> {
    /// Returns the contained value or a default
    ///
875 876
    /// Consumes the `self` argument then, if [`Ok`], returns the contained
    /// value, otherwise if [`Err`], returns the default value for that
877 878 879 880 881
    /// type.
    ///
    /// # Examples
    ///
    /// Convert a string to an integer, turning poorly-formed strings
882 883
    /// into 0 (the default value for integers). [`parse`] converts
    /// a string to any other type that implements [`FromStr`], returning an
884
    /// [`Err`] on error.
885 886 887 888 889 890 891 892 893
    ///
    /// ```
    /// let good_year_from_input = "1909";
    /// let bad_year_from_input = "190blarg";
    /// let good_year = good_year_from_input.parse().unwrap_or_default();
    /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
    ///
    /// assert_eq!(1909, good_year);
    /// assert_eq!(0, bad_year);
G
Guillaume Gomez 已提交
894
    /// ```
895 896 897
    ///
    /// [`parse`]: ../../std/primitive.str.html#method.parse
    /// [`FromStr`]: ../../std/str/trait.FromStr.html
898 899
    /// [`Ok`]: enum.Result.html#variant.Ok
    /// [`Err`]: enum.Result.html#variant.Err
900
    #[inline]
901
    #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
902 903 904 905 906 907 908 909
    pub fn unwrap_or_default(self) -> T {
        match self {
            Ok(x) => x,
            Err(_) => Default::default(),
        }
    }
}

910 911 912 913 914
// This is a separate function to reduce the code size of the methods
#[inline(never)]
#[cold]
fn unwrap_failed<E: fmt::Debug>(msg: &str, error: E) -> ! {
    panic!("{}: {:?}", msg, error)
915 916
}

917 918 919 920
/////////////////////////////////////////////////////////////////////////////
// Trait implementations
/////////////////////////////////////////////////////////////////////////////

921 922 923 924 925 926 927
#[stable(feature = "rust1", since = "1.0.0")]
impl<T, E> IntoIterator for Result<T, E> {
    type Item = T;
    type IntoIter = IntoIter<T>;

    /// Returns a consuming iterator over the possibly contained value.
    ///
928 929
    /// The iterator yields one value if the result is [`Ok`], otherwise none.
    ///
930 931
    /// # Examples
    ///
932 933
    /// Basic usage:
    ///
934 935 936 937 938 939 940 941 942
    /// ```
    /// let x: Result<u32, &str> = Ok(5);
    /// let v: Vec<u32> = x.into_iter().collect();
    /// assert_eq!(v, [5]);
    ///
    /// let x: Result<u32, &str> = Err("nothing!");
    /// let v: Vec<u32> = x.into_iter().collect();
    /// assert_eq!(v, []);
    /// ```
943 944
    ///
    /// [`Ok`]: enum.Result.html#variant.Ok
945 946 947 948 949 950
    #[inline]
    fn into_iter(self) -> IntoIter<T> {
        IntoIter { inner: self.ok() }
    }
}

951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
#[stable(since = "1.4.0", feature = "result_iter")]
impl<'a, T, E> IntoIterator for &'a Result<T, E> {
    type Item = &'a T;
    type IntoIter = Iter<'a, T>;

    fn into_iter(self) -> Iter<'a, T> {
        self.iter()
    }
}

#[stable(since = "1.4.0", feature = "result_iter")]
impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
    type Item = &'a mut T;
    type IntoIter = IterMut<'a, T>;

966
    fn into_iter(self) -> IterMut<'a, T> {
967 968 969 970
        self.iter_mut()
    }
}

A
Aaron Turon 已提交
971
/////////////////////////////////////////////////////////////////////////////
972
// The Result Iterators
A
Aaron Turon 已提交
973 974
/////////////////////////////////////////////////////////////////////////////

G
ggomez 已提交
975 976
/// An iterator over a reference to the [`Ok`] variant of a [`Result`].
///
977 978 979 980
/// The iterator yields one value if the result is [`Ok`], otherwise none.
///
/// Created by [`Result::iter`].
///
G
ggomez 已提交
981 982
/// [`Ok`]: enum.Result.html#variant.Ok
/// [`Result`]: enum.Result.html
983
/// [`Result::iter`]: enum.Result.html#method.iter
984
#[derive(Debug)]
B
Brian Anderson 已提交
985
#[stable(feature = "rust1", since = "1.0.0")]
986
pub struct Iter<'a, T: 'a> { inner: Option<&'a T> }
A
Aaron Turon 已提交
987

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

A
Aaron Turon 已提交
992
    #[inline]
993 994
    fn next(&mut self) -> Option<&'a T> { self.inner.take() }
    #[inline]
N
Niko Matsakis 已提交
995
    fn size_hint(&self) -> (usize, Option<usize>) {
996 997
        let n = if self.inner.is_some() {1} else {0};
        (n, Some(n))
A
Aaron Turon 已提交
998
    }
999 1000
}

B
Brian Anderson 已提交
1001
#[stable(feature = "rust1", since = "1.0.0")]
1002
impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1003 1004 1005 1006
    #[inline]
    fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
}

B
Brian Anderson 已提交
1007
#[stable(feature = "rust1", since = "1.0.0")]
1008
impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
1009

S
Steven Allen 已提交
1010 1011 1012
#[unstable(feature = "fused", issue = "35602")]
impl<'a, T> FusedIterator for Iter<'a, T> {}

1013
#[unstable(feature = "trusted_len", issue = "37572")]
1014 1015
unsafe impl<'a, A> TrustedLen for Iter<'a, A> {}

1016
#[stable(feature = "rust1", since = "1.0.0")]
1017 1018 1019 1020
impl<'a, T> Clone for Iter<'a, T> {
    fn clone(&self) -> Iter<'a, T> { Iter { inner: self.inner } }
}

G
ggomez 已提交
1021 1022
/// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
///
1023 1024
/// Created by [`Result::iter_mut`].
///
G
ggomez 已提交
1025 1026
/// [`Ok`]: enum.Result.html#variant.Ok
/// [`Result`]: enum.Result.html
1027
/// [`Result::iter_mut`]: enum.Result.html#method.iter_mut
1028
#[derive(Debug)]
B
Brian Anderson 已提交
1029
#[stable(feature = "rust1", since = "1.0.0")]
1030
pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
A
Aaron Turon 已提交
1031

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

1036 1037
    #[inline]
    fn next(&mut self) -> Option<&'a mut T> { self.inner.take() }
A
Aaron Turon 已提交
1038
    #[inline]
N
Niko Matsakis 已提交
1039
    fn size_hint(&self) -> (usize, Option<usize>) {
1040 1041
        let n = if self.inner.is_some() {1} else {0};
        (n, Some(n))
A
Aaron Turon 已提交
1042 1043
    }
}
1044

B
Brian Anderson 已提交
1045
#[stable(feature = "rust1", since = "1.0.0")]
1046
impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
A
Aaron Turon 已提交
1047
    #[inline]
1048 1049 1050
    fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
}

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

S
Steven Allen 已提交
1054 1055 1056
#[unstable(feature = "fused", issue = "35602")]
impl<'a, T> FusedIterator for IterMut<'a, T> {}

1057
#[unstable(feature = "trusted_len", issue = "37572")]
1058 1059
unsafe impl<'a, A> TrustedLen for IterMut<'a, A> {}

1060 1061 1062 1063 1064 1065
/// An iterator over the value in a [`Ok`] variant of a [`Result`].
///
/// The iterator yields one value if the result is [`Ok`], otherwise none.
///
/// This struct is created by the [`into_iter`] method on
/// [`Result`][`Result`] (provided by the [`IntoIterator`] trait).
1066
///
G
ggomez 已提交
1067
/// [`Ok`]: enum.Result.html#variant.Ok
1068 1069 1070
/// [`Result`]: enum.Result.html
/// [`into_iter`]: ../iter/trait.IntoIterator.html#tymethod.into_iter
/// [`IntoIterator`]: ../iter/trait.IntoIterator.html
1071
#[derive(Clone, Debug)]
B
Brian Anderson 已提交
1072
#[stable(feature = "rust1", since = "1.0.0")]
1073 1074
pub struct IntoIter<T> { inner: Option<T> }

B
Brian Anderson 已提交
1075
#[stable(feature = "rust1", since = "1.0.0")]
1076 1077 1078
impl<T> Iterator for IntoIter<T> {
    type Item = T;

1079 1080 1081
    #[inline]
    fn next(&mut self) -> Option<T> { self.inner.take() }
    #[inline]
N
Niko Matsakis 已提交
1082
    fn size_hint(&self) -> (usize, Option<usize>) {
1083 1084
        let n = if self.inner.is_some() {1} else {0};
        (n, Some(n))
1085
    }
A
Aaron Turon 已提交
1086 1087
}

B
Brian Anderson 已提交
1088
#[stable(feature = "rust1", since = "1.0.0")]
1089
impl<T> DoubleEndedIterator for IntoIter<T> {
1090 1091 1092 1093
    #[inline]
    fn next_back(&mut self) -> Option<T> { self.inner.take() }
}

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

S
Steven Allen 已提交
1097 1098 1099
#[unstable(feature = "fused", issue = "35602")]
impl<T> FusedIterator for IntoIter<T> {}

1100
#[unstable(feature = "trusted_len", issue = "37572")]
1101 1102
unsafe impl<A> TrustedLen for IntoIter<A> {}

A
Aaron Turon 已提交
1103
/////////////////////////////////////////////////////////////////////////////
1104
// FromIterator
A
Aaron Turon 已提交
1105 1106
/////////////////////////////////////////////////////////////////////////////

B
Brian Anderson 已提交
1107
#[stable(feature = "rust1", since = "1.0.0")]
A
Aaron Turon 已提交
1108 1109 1110 1111 1112 1113 1114 1115
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:
    ///
1116
    /// ```
1117
    /// let v = vec![1, 2];
1118 1119
    /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
    ///     x.checked_add(1).ok_or("Overflow!")
A
Aaron Turon 已提交
1120
    /// ).collect();
1121
    /// assert!(res == Ok(vec![2, 3]));
A
Aaron Turon 已提交
1122 1123
    /// ```
    #[inline]
A
Alexis 已提交
1124
    fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
A
Aaron Turon 已提交
1125 1126 1127 1128 1129 1130 1131 1132
        // FIXME(#11084): This could be replaced with Iterator::scan when this
        // performance bug is closed.

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

1133 1134 1135
        impl<T, E, Iter: Iterator<Item=Result<T, E>>> Iterator for Adapter<Iter, E> {
            type Item = T;

A
Aaron Turon 已提交
1136 1137 1138 1139 1140 1141 1142 1143 1144
            #[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,
1145
                }
1146
            }
1147 1148 1149 1150 1151

            fn size_hint(&self) -> (usize, Option<usize>) {
                let (_min, max) = self.iter.size_hint();
                (0, max)
            }
1152
        }
1153

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

A
Aaron Turon 已提交
1157 1158 1159 1160
        match adapter.err {
            Some(err) => Err(err),
            None => Ok(v),
        }
1161 1162
    }
}
1163

1164
#[unstable(feature = "try_trait", issue = "42327")]
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
impl<T,E> ops::Try for Result<T, E> {
    type Ok = T;
    type Error = E;

    fn into_result(self) -> Self {
        self
    }

    fn from_ok(v: T) -> Self {
        Ok(v)
    }

    fn from_error(v: E) -> Self {
        Err(v)
    }
1180
}