]> git.proxmox.com Git - rustc.git/blame - src/libcore/result.rs
New upstream version 1.46.0~beta.2+dfsg1
[rustc.git] / src / libcore / result.rs
CommitLineData
54a0048b 1//! Error handling with the `Result` type.
1a4d82fc 2//!
9e0c209e
SL
3//! [`Result<T, E>`][`Result`] is the type used for returning and propagating
4//! errors. It is an enum with the variants, [`Ok(T)`], representing
5//! success and containing a value, and [`Err(E)`], representing error
1a4d82fc
JJ
6//! and containing an error value.
7//!
8//! ```
92a42be0 9//! # #[allow(dead_code)]
1a4d82fc
JJ
10//! enum Result<T, E> {
11//! Ok(T),
a7813a04 12//! Err(E),
1a4d82fc
JJ
13//! }
14//! ```
15//!
9e0c209e
SL
16//! Functions return [`Result`] whenever errors are expected and
17//! recoverable. In the `std` crate, [`Result`] is most prominently used
1a4d82fc
JJ
18//! for [I/O](../../std/io/index.html).
19//!
9e0c209e 20//! A simple function returning [`Result`] might be
1a4d82fc
JJ
21//! defined and used like so:
22//!
23//! ```
85aaf69f 24//! #[derive(Debug)]
1a4d82fc
JJ
25//! enum Version { Version1, Version2 }
26//!
27//! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
9346a6ac
AL
28//! match header.get(0) {
29//! None => Err("invalid header length"),
30//! Some(&1) => Ok(Version::Version1),
31//! Some(&2) => Ok(Version::Version2),
a7813a04 32//! Some(_) => Err("invalid version"),
1a4d82fc
JJ
33//! }
34//! }
35//!
36//! let version = parse_version(&[1, 2, 3, 4]);
37//! match version {
9346a6ac
AL
38//! Ok(v) => println!("working with version: {:?}", v),
39//! Err(e) => println!("error parsing header: {:?}", e),
1a4d82fc
JJ
40//! }
41//! ```
42//!
9e0c209e
SL
43//! Pattern matching on [`Result`]s is clear and straightforward for
44//! simple cases, but [`Result`] comes with some convenience methods
1a4d82fc
JJ
45//! that make working with it more succinct.
46//!
47//! ```
c34b1796
AL
48//! let good_result: Result<i32, i32> = Ok(10);
49//! let bad_result: Result<i32, i32> = Err(10);
1a4d82fc
JJ
50//!
51//! // The `is_ok` and `is_err` methods do what they say.
52//! assert!(good_result.is_ok() && !good_result.is_err());
53//! assert!(bad_result.is_err() && !bad_result.is_ok());
54//!
55//! // `map` consumes the `Result` and produces another.
c34b1796
AL
56//! let good_result: Result<i32, i32> = good_result.map(|i| i + 1);
57//! let bad_result: Result<i32, i32> = bad_result.map(|i| i - 1);
1a4d82fc
JJ
58//!
59//! // Use `and_then` to continue the computation.
c34b1796 60//! let good_result: Result<bool, i32> = good_result.and_then(|i| Ok(i == 11));
1a4d82fc
JJ
61//!
62//! // Use `or_else` to handle the error.
9346a6ac 63//! let bad_result: Result<i32, i32> = bad_result.or_else(|i| Ok(i + 20));
1a4d82fc
JJ
64//!
65//! // Consume the result and return the contents with `unwrap`.
c34b1796 66//! let final_awesome_result = good_result.unwrap();
1a4d82fc
JJ
67//! ```
68//!
69//! # Results must be used
70//!
71//! A common problem with using return values to indicate errors is
72//! that it is easy to ignore the return value, thus failing to handle
9e0c209e 73//! the error. [`Result`] is annotated with the `#[must_use]` attribute,
1a4d82fc 74//! which will cause the compiler to issue a warning when a Result
9e0c209e 75//! value is ignored. This makes [`Result`] especially useful with
1a4d82fc
JJ
76//! functions that may encounter errors but don't otherwise return a
77//! useful value.
78//!
9e0c209e
SL
79//! Consider the [`write_all`] method defined for I/O types
80//! by the [`Write`] trait:
1a4d82fc
JJ
81//!
82//! ```
9346a6ac 83//! use std::io;
1a4d82fc 84//!
9346a6ac
AL
85//! trait Write {
86//! fn write_all(&mut self, bytes: &[u8]) -> Result<(), io::Error>;
1a4d82fc
JJ
87//! }
88//! ```
89//!
9e0c209e
SL
90//! *Note: The actual definition of [`Write`] uses [`io::Result`], which
91//! is just a synonym for [`Result`]`<T, `[`io::Error`]`>`.*
1a4d82fc
JJ
92//!
93//! This method doesn't produce a value, but the write may
94//! fail. It's crucial to handle the error case, and *not* write
95//! something like this:
96//!
9346a6ac 97//! ```no_run
92a42be0 98//! # #![allow(unused_must_use)] // \o/
9346a6ac
AL
99//! use std::fs::File;
100//! use std::io::prelude::*;
1a4d82fc 101//!
9346a6ac
AL
102//! let mut file = File::create("valuable_data.txt").unwrap();
103//! // If `write_all` errors, then we'll never know, because the return
1a4d82fc 104//! // value is ignored.
9346a6ac 105//! file.write_all(b"important message");
1a4d82fc
JJ
106//! ```
107//!
85aaf69f 108//! If you *do* write that in Rust, the compiler will give you a
1a4d82fc
JJ
109//! warning (by default, controlled by the `unused_must_use` lint).
110//!
111//! You might instead, if you don't want to handle the error, simply
9e0c209e 112//! assert success with [`expect`]. This will panic if the
92a42be0 113//! write fails, providing a marginally useful message indicating why:
1a4d82fc
JJ
114//!
115//! ```{.no_run}
9346a6ac
AL
116//! use std::fs::File;
117//! use std::io::prelude::*;
1a4d82fc 118//!
9346a6ac 119//! let mut file = File::create("valuable_data.txt").unwrap();
92a42be0 120//! file.write_all(b"important message").expect("failed to write message");
1a4d82fc
JJ
121//! ```
122//!
123//! You might also simply assert success:
124//!
125//! ```{.no_run}
9346a6ac
AL
126//! # use std::fs::File;
127//! # use std::io::prelude::*;
128//! # let mut file = File::create("valuable_data.txt").unwrap();
129//! assert!(file.write_all(b"important message").is_ok());
1a4d82fc
JJ
130//! ```
131//!
8bb4bdeb 132//! Or propagate the error up the call stack with [`?`]:
1a4d82fc
JJ
133//!
134//! ```
9346a6ac
AL
135//! # use std::fs::File;
136//! # use std::io::prelude::*;
137//! # use std::io;
92a42be0 138//! # #[allow(dead_code)]
9346a6ac 139//! fn write_message() -> io::Result<()> {
8bb4bdeb
XL
140//! let mut file = File::create("valuable_data.txt")?;
141//! file.write_all(b"important message")?;
9346a6ac 142//! Ok(())
1a4d82fc
JJ
143//! }
144//! ```
145//!
ff7c6d11 146//! # The question mark operator, `?`
1a4d82fc
JJ
147//!
148//! When writing code that calls many functions that return the
ff7c6d11
XL
149//! [`Result`] type, the error handling can be tedious. The question mark
150//! operator, [`?`], hides some of the boilerplate of propagating errors
151//! up the call stack.
1a4d82fc
JJ
152//!
153//! It replaces this:
154//!
155//! ```
92a42be0 156//! # #![allow(dead_code)]
9346a6ac
AL
157//! use std::fs::File;
158//! use std::io::prelude::*;
159//! use std::io;
1a4d82fc
JJ
160//!
161//! struct Info {
162//! name: String,
c34b1796
AL
163//! age: i32,
164//! rating: i32,
1a4d82fc
JJ
165//! }
166//!
9346a6ac 167//! fn write_info(info: &Info) -> io::Result<()> {
1a4d82fc 168//! // Early return on error
3157f602
XL
169//! let mut file = match File::create("my_best_friends.txt") {
170//! Err(e) => return Err(e),
171//! Ok(f) => f,
172//! };
9346a6ac 173//! if let Err(e) = file.write_all(format!("name: {}\n", info.name).as_bytes()) {
85aaf69f 174//! return Err(e)
1a4d82fc 175//! }
9346a6ac 176//! if let Err(e) = file.write_all(format!("age: {}\n", info.age).as_bytes()) {
85aaf69f 177//! return Err(e)
1a4d82fc 178//! }
9346a6ac
AL
179//! if let Err(e) = file.write_all(format!("rating: {}\n", info.rating).as_bytes()) {
180//! return Err(e)
181//! }
182//! Ok(())
1a4d82fc
JJ
183//! }
184//! ```
185//!
186//! With this:
187//!
188//! ```
92a42be0 189//! # #![allow(dead_code)]
9346a6ac
AL
190//! use std::fs::File;
191//! use std::io::prelude::*;
192//! use std::io;
1a4d82fc
JJ
193//!
194//! struct Info {
195//! name: String,
c34b1796
AL
196//! age: i32,
197//! rating: i32,
1a4d82fc
JJ
198//! }
199//!
9346a6ac 200//! fn write_info(info: &Info) -> io::Result<()> {
8bb4bdeb 201//! let mut file = File::create("my_best_friends.txt")?;
1a4d82fc 202//! // Early return on error
8bb4bdeb
XL
203//! file.write_all(format!("name: {}\n", info.name).as_bytes())?;
204//! file.write_all(format!("age: {}\n", info.age).as_bytes())?;
205//! file.write_all(format!("rating: {}\n", info.rating).as_bytes())?;
9346a6ac 206//! Ok(())
1a4d82fc
JJ
207//! }
208//! ```
209//!
210//! *It's much nicer!*
211//!
8bb4bdeb 212//! Ending the expression with [`?`] will result in the unwrapped
9e0c209e 213//! success ([`Ok`]) value, unless the result is [`Err`], in which case
8bb4bdeb 214//! [`Err`] is returned early from the enclosing function.
1a4d82fc 215//!
8bb4bdeb
XL
216//! [`?`] can only be used in functions that return [`Result`] because of the
217//! early return of [`Err`] that it provides.
9e0c209e
SL
218//!
219//! [`expect`]: enum.Result.html#method.expect
220//! [`Write`]: ../../std/io/trait.Write.html
221//! [`write_all`]: ../../std/io/trait.Write.html#method.write_all
222//! [`io::Result`]: ../../std/io/type.Result.html
8bb4bdeb 223//! [`?`]: ../../std/macro.try.html
9e0c209e
SL
224//! [`Result`]: enum.Result.html
225//! [`Ok(T)`]: enum.Result.html#variant.Ok
226//! [`Err(E)`]: enum.Result.html#variant.Err
227//! [`io::Error`]: ../../std/io/struct.Error.html
228//! [`Ok`]: enum.Result.html#variant.Ok
229//! [`Err`]: enum.Result.html#variant.Err
1a4d82fc 230
85aaf69f 231#![stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 232
416331ca
XL
233use crate::iter::{self, FromIterator, FusedIterator, TrustedLen};
234use crate::ops::{self, Deref, DerefMut};
ba9703b0 235use crate::{convert, fmt};
1a4d82fc 236
3b2f2976 237/// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]).
1a4d82fc
JJ
238///
239/// See the [`std::result`](index.html) module documentation for details.
3b2f2976
XL
240///
241/// [`Ok`]: enum.Result.html#variant.Ok
242/// [`Err`]: enum.Result.html#variant.Err
dc9dc135 243#[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
94b46f34 244#[must_use = "this `Result` may be an `Err` variant, which should be handled"]
dfeec247 245#[rustc_diagnostic_item = "result_type"]
85aaf69f 246#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
247pub enum Result<T, E> {
248 /// Contains the success value
85aaf69f 249 #[stable(feature = "rust1", since = "1.0.0")]
7453a54e 250 Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
1a4d82fc
JJ
251
252 /// Contains the error value
85aaf69f 253 #[stable(feature = "rust1", since = "1.0.0")]
a7813a04 254 Err(#[stable(feature = "rust1", since = "1.0.0")] E),
1a4d82fc
JJ
255}
256
257/////////////////////////////////////////////////////////////////////////////
258// Type implementation
259/////////////////////////////////////////////////////////////////////////////
260
1a4d82fc
JJ
261impl<T, E> Result<T, E> {
262 /////////////////////////////////////////////////////////////////////////
263 // Querying the contained values
264 /////////////////////////////////////////////////////////////////////////
265
3b2f2976
XL
266 /// Returns `true` if the result is [`Ok`].
267 ///
268 /// [`Ok`]: enum.Result.html#variant.Ok
1a4d82fc 269 ///
c34b1796 270 /// # Examples
1a4d82fc 271 ///
a7813a04
XL
272 /// Basic usage:
273 ///
1a4d82fc 274 /// ```
c34b1796 275 /// let x: Result<i32, &str> = Ok(-3);
1a4d82fc
JJ
276 /// assert_eq!(x.is_ok(), true);
277 ///
c34b1796 278 /// let x: Result<i32, &str> = Err("Some error message");
1a4d82fc
JJ
279 /// assert_eq!(x.is_ok(), false);
280 /// ```
416331ca 281 #[must_use = "if you intended to assert that this is ok, consider `.unwrap()` instead"]
dfeec247 282 #[rustc_const_unstable(feature = "const_result", issue = "67520")]
1a4d82fc 283 #[inline]
85aaf69f 284 #[stable(feature = "rust1", since = "1.0.0")]
dfeec247
XL
285 pub const fn is_ok(&self) -> bool {
286 matches!(*self, Ok(_))
1a4d82fc
JJ
287 }
288
3b2f2976
XL
289 /// Returns `true` if the result is [`Err`].
290 ///
291 /// [`Err`]: enum.Result.html#variant.Err
1a4d82fc 292 ///
c34b1796 293 /// # Examples
1a4d82fc 294 ///
a7813a04
XL
295 /// Basic usage:
296 ///
1a4d82fc 297 /// ```
c34b1796 298 /// let x: Result<i32, &str> = Ok(-3);
1a4d82fc
JJ
299 /// assert_eq!(x.is_err(), false);
300 ///
c34b1796 301 /// let x: Result<i32, &str> = Err("Some error message");
1a4d82fc
JJ
302 /// assert_eq!(x.is_err(), true);
303 /// ```
416331ca 304 #[must_use = "if you intended to assert that this is err, consider `.unwrap_err()` instead"]
dfeec247 305 #[rustc_const_unstable(feature = "const_result", issue = "67520")]
1a4d82fc 306 #[inline]
85aaf69f 307 #[stable(feature = "rust1", since = "1.0.0")]
dfeec247 308 pub const fn is_err(&self) -> bool {
1a4d82fc
JJ
309 !self.is_ok()
310 }
311
416331ca
XL
312 /// Returns `true` if the result is an [`Ok`] value containing the given value.
313 ///
314 /// # Examples
315 ///
316 /// ```
317 /// #![feature(option_result_contains)]
318 ///
319 /// let x: Result<u32, &str> = Ok(2);
320 /// assert_eq!(x.contains(&2), true);
321 ///
322 /// let x: Result<u32, &str> = Ok(3);
323 /// assert_eq!(x.contains(&2), false);
324 ///
325 /// let x: Result<u32, &str> = Err("Some error message");
326 /// assert_eq!(x.contains(&2), false);
327 /// ```
328 #[must_use]
329 #[inline]
330 #[unstable(feature = "option_result_contains", issue = "62358")]
dfeec247
XL
331 pub fn contains<U>(&self, x: &U) -> bool
332 where
333 U: PartialEq<T>,
334 {
416331ca
XL
335 match self {
336 Ok(y) => x == y,
dfeec247 337 Err(_) => false,
416331ca
XL
338 }
339 }
340
341 /// Returns `true` if the result is an [`Err`] value containing the given value.
342 ///
343 /// # Examples
344 ///
345 /// ```
346 /// #![feature(result_contains_err)]
347 ///
348 /// let x: Result<u32, &str> = Ok(2);
349 /// assert_eq!(x.contains_err(&"Some error message"), false);
350 ///
351 /// let x: Result<u32, &str> = Err("Some error message");
352 /// assert_eq!(x.contains_err(&"Some error message"), true);
353 ///
354 /// let x: Result<u32, &str> = Err("Some other error message");
355 /// assert_eq!(x.contains_err(&"Some error message"), false);
356 /// ```
357 #[must_use]
358 #[inline]
359 #[unstable(feature = "result_contains_err", issue = "62358")]
dfeec247
XL
360 pub fn contains_err<F>(&self, f: &F) -> bool
361 where
362 F: PartialEq<E>,
363 {
416331ca
XL
364 match self {
365 Ok(_) => false,
dfeec247 366 Err(e) => f == e,
416331ca
XL
367 }
368 }
369
1a4d82fc
JJ
370 /////////////////////////////////////////////////////////////////////////
371 // Adapter for each variant
372 /////////////////////////////////////////////////////////////////////////
373
9e0c209e 374 /// Converts from `Result<T, E>` to [`Option<T>`].
1a4d82fc 375 ///
9e0c209e 376 /// Converts `self` into an [`Option<T>`], consuming `self`,
1a4d82fc
JJ
377 /// and discarding the error, if any.
378 ///
9e0c209e
SL
379 /// [`Option<T>`]: ../../std/option/enum.Option.html
380 ///
c34b1796 381 /// # Examples
1a4d82fc 382 ///
a7813a04
XL
383 /// Basic usage:
384 ///
1a4d82fc 385 /// ```
85aaf69f 386 /// let x: Result<u32, &str> = Ok(2);
1a4d82fc
JJ
387 /// assert_eq!(x.ok(), Some(2));
388 ///
85aaf69f 389 /// let x: Result<u32, &str> = Err("Nothing here");
1a4d82fc
JJ
390 /// assert_eq!(x.ok(), None);
391 /// ```
392 #[inline]
85aaf69f 393 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
394 pub fn ok(self) -> Option<T> {
395 match self {
dfeec247 396 Ok(x) => Some(x),
1a4d82fc
JJ
397 Err(_) => None,
398 }
399 }
400
9e0c209e 401 /// Converts from `Result<T, E>` to [`Option<E>`].
1a4d82fc 402 ///
9e0c209e 403 /// Converts `self` into an [`Option<E>`], consuming `self`,
c34b1796 404 /// and discarding the success value, if any.
1a4d82fc 405 ///
9e0c209e
SL
406 /// [`Option<E>`]: ../../std/option/enum.Option.html
407 ///
c34b1796 408 /// # Examples
1a4d82fc 409 ///
a7813a04
XL
410 /// Basic usage:
411 ///
1a4d82fc 412 /// ```
85aaf69f 413 /// let x: Result<u32, &str> = Ok(2);
1a4d82fc
JJ
414 /// assert_eq!(x.err(), None);
415 ///
85aaf69f 416 /// let x: Result<u32, &str> = Err("Nothing here");
1a4d82fc
JJ
417 /// assert_eq!(x.err(), Some("Nothing here"));
418 /// ```
419 #[inline]
85aaf69f 420 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
421 pub fn err(self) -> Option<E> {
422 match self {
dfeec247 423 Ok(_) => None,
1a4d82fc
JJ
424 Err(x) => Some(x),
425 }
426 }
427
428 /////////////////////////////////////////////////////////////////////////
429 // Adapter for working with references
430 /////////////////////////////////////////////////////////////////////////
431
532ac7d7 432 /// Converts from `&Result<T, E>` to `Result<&T, &E>`.
1a4d82fc
JJ
433 ///
434 /// Produces a new `Result`, containing a reference
435 /// into the original, leaving the original in place.
436 ///
a7813a04
XL
437 /// # Examples
438 ///
439 /// Basic usage:
440 ///
1a4d82fc 441 /// ```
85aaf69f 442 /// let x: Result<u32, &str> = Ok(2);
1a4d82fc
JJ
443 /// assert_eq!(x.as_ref(), Ok(&2));
444 ///
85aaf69f 445 /// let x: Result<u32, &str> = Err("Error");
1a4d82fc
JJ
446 /// assert_eq!(x.as_ref(), Err(&"Error"));
447 /// ```
448 #[inline]
dfeec247 449 #[rustc_const_unstable(feature = "const_result", issue = "67520")]
85aaf69f 450 #[stable(feature = "rust1", since = "1.0.0")]
dfeec247 451 pub const fn as_ref(&self) -> Result<&T, &E> {
1a4d82fc
JJ
452 match *self {
453 Ok(ref x) => Ok(x),
454 Err(ref x) => Err(x),
455 }
456 }
457
532ac7d7 458 /// Converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`.
1a4d82fc 459 ///
a7813a04
XL
460 /// # Examples
461 ///
462 /// Basic usage:
463 ///
1a4d82fc 464 /// ```
c34b1796 465 /// fn mutate(r: &mut Result<i32, i32>) {
1a4d82fc 466 /// match r.as_mut() {
5bcae85e
SL
467 /// Ok(v) => *v = 42,
468 /// Err(e) => *e = 0,
1a4d82fc
JJ
469 /// }
470 /// }
471 ///
c34b1796 472 /// let mut x: Result<i32, i32> = Ok(2);
1a4d82fc
JJ
473 /// mutate(&mut x);
474 /// assert_eq!(x.unwrap(), 42);
475 ///
c34b1796 476 /// let mut x: Result<i32, i32> = Err(13);
1a4d82fc
JJ
477 /// mutate(&mut x);
478 /// assert_eq!(x.unwrap_err(), 0);
479 /// ```
480 #[inline]
85aaf69f 481 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
482 pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
483 match *self {
484 Ok(ref mut x) => Ok(x),
485 Err(ref mut x) => Err(x),
486 }
487 }
488
1a4d82fc
JJ
489 /////////////////////////////////////////////////////////////////////////
490 // Transforming contained values
491 /////////////////////////////////////////////////////////////////////////
492
92a42be0 493 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
3b2f2976 494 /// contained [`Ok`] value, leaving an [`Err`] value untouched.
1a4d82fc
JJ
495 ///
496 /// This function can be used to compose the results of two functions.
497 ///
3b2f2976
XL
498 /// [`Ok`]: enum.Result.html#variant.Ok
499 /// [`Err`]: enum.Result.html#variant.Err
500 ///
c34b1796 501 /// # Examples
1a4d82fc 502 ///
9346a6ac 503 /// Print the numbers on each line of a string multiplied by two.
1a4d82fc
JJ
504 ///
505 /// ```
9346a6ac 506 /// let line = "1\n2\n3\n4\n";
1a4d82fc 507 ///
9346a6ac
AL
508 /// for num in line.lines() {
509 /// match num.parse::<i32>().map(|i| i * 2) {
510 /// Ok(n) => println!("{}", n),
511 /// Err(..) => {}
512 /// }
1a4d82fc 513 /// }
1a4d82fc
JJ
514 /// ```
515 #[inline]
85aaf69f 516 #[stable(feature = "rust1", since = "1.0.0")]
dfeec247 517 pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U, E> {
1a4d82fc
JJ
518 match self {
519 Ok(t) => Ok(op(t)),
dfeec247 520 Err(e) => Err(e),
1a4d82fc
JJ
521 }
522 }
523
ba9703b0
XL
524 /// Applies a function to the contained value (if [`Ok`]),
525 /// or returns the provided default (if [`Err`]).
60c5eb7d 526 ///
74b04a01
XL
527 /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
528 /// the result of a function call, it is recommended to use [`map_or_else`],
529 /// which is lazily evaluated.
530 ///
531 /// [`map_or_else`]: #method.map_or_else
ba9703b0
XL
532 /// [`Ok`]: enum.Result.html#variant.Ok
533 /// [`Err`]: enum.Result.html#variant.Err
74b04a01 534 ///
60c5eb7d
XL
535 /// # Examples
536 ///
537 /// ```
538 /// let x: Result<_, &str> = Ok("foo");
539 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
540 ///
541 /// let x: Result<&str, _> = Err("bar");
542 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
543 /// ```
544 #[inline]
545 #[stable(feature = "result_map_or", since = "1.41.0")]
546 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
547 match self {
548 Ok(t) => f(t),
549 Err(_) => default,
550 }
551 }
552
b7449926
XL
553 /// Maps a `Result<T, E>` to `U` by applying a function to a
554 /// contained [`Ok`] value, or a fallback function to a
555 /// contained [`Err`] value.
556 ///
557 /// This function can be used to unpack a successful result
558 /// while handling an error.
559 ///
560 /// [`Ok`]: enum.Result.html#variant.Ok
561 /// [`Err`]: enum.Result.html#variant.Err
562 ///
563 /// # Examples
564 ///
565 /// Basic usage:
566 ///
567 /// ```
b7449926
XL
568 /// let k = 21;
569 ///
570 /// let x : Result<_, &str> = Ok("foo");
571 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);
572 ///
573 /// let x : Result<&str, _> = Err("bar");
574 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
575 /// ```
576 #[inline]
60c5eb7d
XL
577 #[stable(feature = "result_map_or_else", since = "1.41.0")]
578 pub fn map_or_else<U, D: FnOnce(E) -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
579 match self {
580 Ok(t) => f(t),
581 Err(e) => default(e),
582 }
b7449926
XL
583 }
584
92a42be0 585 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
3b2f2976 586 /// contained [`Err`] value, leaving an [`Ok`] value untouched.
1a4d82fc
JJ
587 ///
588 /// This function can be used to pass through a successful result while handling
589 /// an error.
590 ///
3b2f2976
XL
591 /// [`Ok`]: enum.Result.html#variant.Ok
592 /// [`Err`]: enum.Result.html#variant.Err
593 ///
c34b1796 594 /// # Examples
1a4d82fc 595 ///
a7813a04
XL
596 /// Basic usage:
597 ///
1a4d82fc 598 /// ```
85aaf69f 599 /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
1a4d82fc 600 ///
85aaf69f
SL
601 /// let x: Result<u32, u32> = Ok(2);
602 /// assert_eq!(x.map_err(stringify), Ok(2));
1a4d82fc 603 ///
85aaf69f 604 /// let x: Result<u32, u32> = Err(13);
1a4d82fc
JJ
605 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
606 /// ```
607 #[inline]
85aaf69f 608 #[stable(feature = "rust1", since = "1.0.0")]
dfeec247 609 pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T, F> {
1a4d82fc
JJ
610 match self {
611 Ok(t) => Ok(t),
dfeec247 612 Err(e) => Err(op(e)),
1a4d82fc
JJ
613 }
614 }
615
616 /////////////////////////////////////////////////////////////////////////
617 // Iterator constructors
618 /////////////////////////////////////////////////////////////////////////
619
620 /// Returns an iterator over the possibly contained value.
621 ///
b7449926 622 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
32a655c1 623 ///
c34b1796 624 /// # Examples
1a4d82fc 625 ///
a7813a04
XL
626 /// Basic usage:
627 ///
1a4d82fc 628 /// ```
85aaf69f 629 /// let x: Result<u32, &str> = Ok(7);
1a4d82fc
JJ
630 /// assert_eq!(x.iter().next(), Some(&7));
631 ///
85aaf69f 632 /// let x: Result<u32, &str> = Err("nothing!");
1a4d82fc
JJ
633 /// assert_eq!(x.iter().next(), None);
634 /// ```
635 #[inline]
85aaf69f 636 #[stable(feature = "rust1", since = "1.0.0")]
48663c56 637 pub fn iter(&self) -> Iter<'_, T> {
1a4d82fc
JJ
638 Iter { inner: self.as_ref().ok() }
639 }
640
641 /// Returns a mutable iterator over the possibly contained value.
642 ///
b7449926 643 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
32a655c1 644 ///
c34b1796 645 /// # Examples
1a4d82fc 646 ///
a7813a04
XL
647 /// Basic usage:
648 ///
1a4d82fc 649 /// ```
85aaf69f 650 /// let mut x: Result<u32, &str> = Ok(7);
1a4d82fc 651 /// match x.iter_mut().next() {
b039eaaf 652 /// Some(v) => *v = 40,
1a4d82fc
JJ
653 /// None => {},
654 /// }
655 /// assert_eq!(x, Ok(40));
656 ///
85aaf69f 657 /// let mut x: Result<u32, &str> = Err("nothing!");
1a4d82fc
JJ
658 /// assert_eq!(x.iter_mut().next(), None);
659 /// ```
660 #[inline]
85aaf69f 661 #[stable(feature = "rust1", since = "1.0.0")]
48663c56 662 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1a4d82fc
JJ
663 IterMut { inner: self.as_mut().ok() }
664 }
665
1a4d82fc
JJ
666 ////////////////////////////////////////////////////////////////////////
667 // Boolean operations on the values, eager and lazy
668 /////////////////////////////////////////////////////////////////////////
669
3b2f2976
XL
670 /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
671 ///
672 /// [`Ok`]: enum.Result.html#variant.Ok
673 /// [`Err`]: enum.Result.html#variant.Err
1a4d82fc 674 ///
c34b1796 675 /// # Examples
1a4d82fc 676 ///
a7813a04
XL
677 /// Basic usage:
678 ///
1a4d82fc 679 /// ```
85aaf69f 680 /// let x: Result<u32, &str> = Ok(2);
1a4d82fc
JJ
681 /// let y: Result<&str, &str> = Err("late error");
682 /// assert_eq!(x.and(y), Err("late error"));
683 ///
85aaf69f 684 /// let x: Result<u32, &str> = Err("early error");
1a4d82fc
JJ
685 /// let y: Result<&str, &str> = Ok("foo");
686 /// assert_eq!(x.and(y), Err("early error"));
687 ///
85aaf69f 688 /// let x: Result<u32, &str> = Err("not a 2");
1a4d82fc
JJ
689 /// let y: Result<&str, &str> = Err("late error");
690 /// assert_eq!(x.and(y), Err("not a 2"));
691 ///
85aaf69f 692 /// let x: Result<u32, &str> = Ok(2);
1a4d82fc
JJ
693 /// let y: Result<&str, &str> = Ok("different result type");
694 /// assert_eq!(x.and(y), Ok("different result type"));
695 /// ```
696 #[inline]
85aaf69f 697 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
698 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
699 match self {
700 Ok(_) => res,
701 Err(e) => Err(e),
702 }
703 }
704
3b2f2976
XL
705 /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
706 ///
707 /// [`Ok`]: enum.Result.html#variant.Ok
708 /// [`Err`]: enum.Result.html#variant.Err
1a4d82fc 709 ///
9e0c209e 710 /// This function can be used for control flow based on `Result` values.
1a4d82fc 711 ///
c34b1796 712 /// # Examples
1a4d82fc 713 ///
a7813a04
XL
714 /// Basic usage:
715 ///
1a4d82fc 716 /// ```
85aaf69f
SL
717 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
718 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
1a4d82fc
JJ
719 ///
720 /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
721 /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
722 /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
723 /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
724 /// ```
725 #[inline]
85aaf69f 726 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
727 pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
728 match self {
729 Ok(t) => op(t),
730 Err(e) => Err(e),
731 }
732 }
733
3b2f2976
XL
734 /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
735 ///
ff7c6d11
XL
736 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
737 /// result of a function call, it is recommended to use [`or_else`], which is
738 /// lazily evaluated.
739 ///
3b2f2976
XL
740 /// [`Ok`]: enum.Result.html#variant.Ok
741 /// [`Err`]: enum.Result.html#variant.Err
ff7c6d11 742 /// [`or_else`]: #method.or_else
1a4d82fc 743 ///
c34b1796 744 /// # Examples
1a4d82fc 745 ///
a7813a04
XL
746 /// Basic usage:
747 ///
1a4d82fc 748 /// ```
85aaf69f
SL
749 /// let x: Result<u32, &str> = Ok(2);
750 /// let y: Result<u32, &str> = Err("late error");
1a4d82fc
JJ
751 /// assert_eq!(x.or(y), Ok(2));
752 ///
85aaf69f
SL
753 /// let x: Result<u32, &str> = Err("early error");
754 /// let y: Result<u32, &str> = Ok(2);
1a4d82fc
JJ
755 /// assert_eq!(x.or(y), Ok(2));
756 ///
85aaf69f
SL
757 /// let x: Result<u32, &str> = Err("not a 2");
758 /// let y: Result<u32, &str> = Err("late error");
1a4d82fc
JJ
759 /// assert_eq!(x.or(y), Err("late error"));
760 ///
85aaf69f
SL
761 /// let x: Result<u32, &str> = Ok(2);
762 /// let y: Result<u32, &str> = Ok(100);
1a4d82fc
JJ
763 /// assert_eq!(x.or(y), Ok(2));
764 /// ```
765 #[inline]
85aaf69f 766 #[stable(feature = "rust1", since = "1.0.0")]
c34b1796 767 pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
1a4d82fc 768 match self {
c34b1796 769 Ok(v) => Ok(v),
1a4d82fc
JJ
770 Err(_) => res,
771 }
772 }
773
3b2f2976 774 /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
1a4d82fc
JJ
775 ///
776 /// This function can be used for control flow based on result values.
777 ///
3b2f2976
XL
778 /// [`Ok`]: enum.Result.html#variant.Ok
779 /// [`Err`]: enum.Result.html#variant.Err
780 ///
c34b1796 781 /// # Examples
1a4d82fc 782 ///
a7813a04
XL
783 /// Basic usage:
784 ///
1a4d82fc 785 /// ```
85aaf69f
SL
786 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
787 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
1a4d82fc
JJ
788 ///
789 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
790 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
791 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
792 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
793 /// ```
794 #[inline]
85aaf69f 795 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
796 pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
797 match self {
798 Ok(t) => Ok(t),
799 Err(e) => op(e),
800 }
801 }
802
74b04a01 803 /// Returns the contained [`Ok`] value or a provided default.
1a4d82fc 804 ///
ff7c6d11
XL
805 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
806 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
807 /// which is lazily evaluated.
808 ///
3b2f2976
XL
809 /// [`Ok`]: enum.Result.html#variant.Ok
810 /// [`Err`]: enum.Result.html#variant.Err
ff7c6d11 811 /// [`unwrap_or_else`]: #method.unwrap_or_else
3b2f2976 812 ///
c34b1796 813 /// # Examples
1a4d82fc 814 ///
a7813a04
XL
815 /// Basic usage:
816 ///
1a4d82fc 817 /// ```
74b04a01 818 /// let default = 2;
85aaf69f 819 /// let x: Result<u32, &str> = Ok(9);
74b04a01 820 /// assert_eq!(x.unwrap_or(default), 9);
1a4d82fc 821 ///
85aaf69f 822 /// let x: Result<u32, &str> = Err("error");
74b04a01 823 /// assert_eq!(x.unwrap_or(default), default);
1a4d82fc
JJ
824 /// ```
825 #[inline]
85aaf69f 826 #[stable(feature = "rust1", since = "1.0.0")]
74b04a01 827 pub fn unwrap_or(self, default: T) -> T {
1a4d82fc
JJ
828 match self {
829 Ok(t) => t,
74b04a01 830 Err(_) => default,
1a4d82fc
JJ
831 }
832 }
833
74b04a01 834 /// Returns the contained [`Ok`] value or computes it from a closure.
3b2f2976
XL
835 ///
836 /// [`Ok`]: enum.Result.html#variant.Ok
1a4d82fc 837 ///
c34b1796 838 /// # Examples
1a4d82fc 839 ///
a7813a04
XL
840 /// Basic usage:
841 ///
1a4d82fc 842 /// ```
85aaf69f 843 /// fn count(x: &str) -> usize { x.len() }
1a4d82fc 844 ///
85aaf69f
SL
845 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
846 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
1a4d82fc
JJ
847 /// ```
848 #[inline]
85aaf69f 849 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
850 pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
851 match self {
852 Ok(t) => t,
dfeec247 853 Err(e) => op(e),
1a4d82fc
JJ
854 }
855 }
856}
857
e1599b0c
XL
858impl<T: Copy, E> Result<&T, E> {
859 /// Maps a `Result<&T, E>` to a `Result<T, E>` by copying the contents of the
860 /// `Ok` part.
861 ///
862 /// # Examples
863 ///
864 /// ```
865 /// #![feature(result_copied)]
866 /// let val = 12;
867 /// let x: Result<&i32, i32> = Ok(&val);
868 /// assert_eq!(x, Ok(&12));
869 /// let copied = x.copied();
870 /// assert_eq!(copied, Ok(12));
871 /// ```
872 #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
873 pub fn copied(self) -> Result<T, E> {
874 self.map(|&t| t)
875 }
876}
877
878impl<T: Copy, E> Result<&mut T, E> {
879 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by copying the contents of the
880 /// `Ok` part.
881 ///
882 /// # Examples
883 ///
884 /// ```
885 /// #![feature(result_copied)]
886 /// let mut val = 12;
887 /// let x: Result<&mut i32, i32> = Ok(&mut val);
888 /// assert_eq!(x, Ok(&mut 12));
889 /// let copied = x.copied();
890 /// assert_eq!(copied, Ok(12));
891 /// ```
892 #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
893 pub fn copied(self) -> Result<T, E> {
894 self.map(|&mut t| t)
895 }
896}
897
898impl<T: Clone, E> Result<&T, E> {
899 /// Maps a `Result<&T, E>` to a `Result<T, E>` by cloning the contents of the
900 /// `Ok` part.
901 ///
902 /// # Examples
903 ///
904 /// ```
905 /// #![feature(result_cloned)]
906 /// let val = 12;
907 /// let x: Result<&i32, i32> = Ok(&val);
908 /// assert_eq!(x, Ok(&12));
909 /// let cloned = x.cloned();
910 /// assert_eq!(cloned, Ok(12));
911 /// ```
912 #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
913 pub fn cloned(self) -> Result<T, E> {
914 self.map(|t| t.clone())
915 }
916}
917
918impl<T: Clone, E> Result<&mut T, E> {
919 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by cloning the contents of the
920 /// `Ok` part.
921 ///
922 /// # Examples
923 ///
924 /// ```
925 /// #![feature(result_cloned)]
926 /// let mut val = 12;
927 /// let x: Result<&mut i32, i32> = Ok(&mut val);
928 /// assert_eq!(x, Ok(&mut 12));
929 /// let cloned = x.cloned();
930 /// assert_eq!(cloned, Ok(12));
931 /// ```
932 #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
933 pub fn cloned(self) -> Result<T, E> {
934 self.map(|t| t.clone())
935 }
936}
937
85aaf69f 938impl<T, E: fmt::Debug> Result<T, E> {
74b04a01
XL
939 /// Returns the contained [`Ok`] value, consuming the `self` value.
940 ///
941 /// # Panics
942 ///
943 /// Panics if the value is an [`Err`], with a panic message including the
944 /// passed message, and the content of the [`Err`].
945 ///
946 /// [`Ok`]: enum.Result.html#variant.Ok
947 /// [`Err`]: enum.Result.html#variant.Err
948 ///
949 /// # Examples
950 ///
951 /// Basic usage:
952 ///
953 /// ```{.should_panic}
954 /// let x: Result<u32, &str> = Err("emergency failure");
955 /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
956 /// ```
957 #[inline]
958 #[track_caller]
959 #[stable(feature = "result_expect", since = "1.4.0")]
960 pub fn expect(self, msg: &str) -> T {
961 match self {
962 Ok(t) => t,
963 Err(e) => unwrap_failed(msg, &e),
964 }
965 }
966
967 /// Returns the contained [`Ok`] value, consuming the `self` value.
968 ///
969 /// Because this function may panic, its use is generally discouraged.
970 /// Instead, prefer to use pattern matching and handle the [`Err`]
971 /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
972 /// [`unwrap_or_default`].
973 ///
974 /// [`unwrap_or`]: #method.unwrap_or
975 /// [`unwrap_or_else`]: #method.unwrap_or_else
976 /// [`unwrap_or_default`]: #method.unwrap_or_default
1a4d82fc
JJ
977 ///
978 /// # Panics
979 ///
3b2f2976
XL
980 /// Panics if the value is an [`Err`], with a panic message provided by the
981 /// [`Err`]'s value.
982 ///
983 /// [`Ok`]: enum.Result.html#variant.Ok
984 /// [`Err`]: enum.Result.html#variant.Err
1a4d82fc 985 ///
c34b1796 986 /// # Examples
1a4d82fc 987 ///
a7813a04
XL
988 /// Basic usage:
989 ///
1a4d82fc 990 /// ```
85aaf69f
SL
991 /// let x: Result<u32, &str> = Ok(2);
992 /// assert_eq!(x.unwrap(), 2);
1a4d82fc
JJ
993 /// ```
994 ///
c34b1796 995 /// ```{.should_panic}
85aaf69f 996 /// let x: Result<u32, &str> = Err("emergency failure");
1a4d82fc
JJ
997 /// x.unwrap(); // panics with `emergency failure`
998 /// ```
999 #[inline]
dfeec247 1000 #[track_caller]
85aaf69f 1001 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1002 pub fn unwrap(self) -> T {
1003 match self {
1004 Ok(t) => t,
416331ca 1005 Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e),
1a4d82fc
JJ
1006 }
1007 }
74b04a01 1008}
62682a34 1009
74b04a01
XL
1010impl<T: fmt::Debug, E> Result<T, E> {
1011 /// Returns the contained [`Err`] value, consuming the `self` value.
62682a34 1012 ///
9cc50fc6
SL
1013 /// # Panics
1014 ///
74b04a01
XL
1015 /// Panics if the value is an [`Ok`], with a panic message including the
1016 /// passed message, and the content of the [`Ok`].
3b2f2976
XL
1017 ///
1018 /// [`Ok`]: enum.Result.html#variant.Ok
1019 /// [`Err`]: enum.Result.html#variant.Err
62682a34
SL
1020 ///
1021 /// # Examples
a7813a04
XL
1022 ///
1023 /// Basic usage:
1024 ///
62682a34 1025 /// ```{.should_panic}
74b04a01
XL
1026 /// let x: Result<u32, &str> = Ok(10);
1027 /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
62682a34
SL
1028 /// ```
1029 #[inline]
dfeec247 1030 #[track_caller]
74b04a01
XL
1031 #[stable(feature = "result_expect_err", since = "1.17.0")]
1032 pub fn expect_err(self, msg: &str) -> E {
62682a34 1033 match self {
74b04a01
XL
1034 Ok(t) => unwrap_failed(msg, &t),
1035 Err(e) => e,
62682a34
SL
1036 }
1037 }
1a4d82fc 1038
74b04a01 1039 /// Returns the contained [`Err`] value, consuming the `self` value.
1a4d82fc
JJ
1040 ///
1041 /// # Panics
1042 ///
3b2f2976
XL
1043 /// Panics if the value is an [`Ok`], with a custom panic message provided
1044 /// by the [`Ok`]'s value.
1045 ///
1046 /// [`Ok`]: enum.Result.html#variant.Ok
1047 /// [`Err`]: enum.Result.html#variant.Err
1048 ///
1a4d82fc 1049 ///
c34b1796 1050 /// # Examples
1a4d82fc 1051 ///
c34b1796 1052 /// ```{.should_panic}
85aaf69f 1053 /// let x: Result<u32, &str> = Ok(2);
1a4d82fc
JJ
1054 /// x.unwrap_err(); // panics with `2`
1055 /// ```
1056 ///
1057 /// ```
85aaf69f 1058 /// let x: Result<u32, &str> = Err("emergency failure");
1a4d82fc
JJ
1059 /// assert_eq!(x.unwrap_err(), "emergency failure");
1060 /// ```
1061 #[inline]
dfeec247 1062 #[track_caller]
85aaf69f 1063 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1064 pub fn unwrap_err(self) -> E {
1065 match self {
416331ca 1066 Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t),
7453a54e 1067 Err(e) => e,
1a4d82fc
JJ
1068 }
1069 }
1070}
1071
c30ab7b3 1072impl<T: Default, E> Result<T, E> {
74b04a01 1073 /// Returns the contained [`Ok`] value or a default
c30ab7b3 1074 ///
3b2f2976
XL
1075 /// Consumes the `self` argument then, if [`Ok`], returns the contained
1076 /// value, otherwise if [`Err`], returns the default value for that
c30ab7b3
SL
1077 /// type.
1078 ///
1079 /// # Examples
1080 ///
9fa01778 1081 /// Converts a string to an integer, turning poorly-formed strings
c30ab7b3
SL
1082 /// into 0 (the default value for integers). [`parse`] converts
1083 /// a string to any other type that implements [`FromStr`], returning an
3b2f2976 1084 /// [`Err`] on error.
c30ab7b3
SL
1085 ///
1086 /// ```
c30ab7b3
SL
1087 /// let good_year_from_input = "1909";
1088 /// let bad_year_from_input = "190blarg";
1089 /// let good_year = good_year_from_input.parse().unwrap_or_default();
1090 /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
1091 ///
1092 /// assert_eq!(1909, good_year);
1093 /// assert_eq!(0, bad_year);
cc61c64b 1094 /// ```
c30ab7b3
SL
1095 ///
1096 /// [`parse`]: ../../std/primitive.str.html#method.parse
1097 /// [`FromStr`]: ../../std/str/trait.FromStr.html
3b2f2976
XL
1098 /// [`Ok`]: enum.Result.html#variant.Ok
1099 /// [`Err`]: enum.Result.html#variant.Err
c30ab7b3 1100 #[inline]
32a655c1 1101 #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
c30ab7b3
SL
1102 pub fn unwrap_or_default(self) -> T {
1103 match self {
1104 Ok(x) => x,
1105 Err(_) => Default::default(),
2c00a5a8
XL
1106 }
1107 }
1108}
1109
dfeec247
XL
1110#[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
1111impl<T, E: Into<!>> Result<T, E> {
74b04a01 1112 /// Returns the contained [`Ok`] value, but never panics.
dfeec247
XL
1113 ///
1114 /// Unlike [`unwrap`], this method is known to never panic on the
1115 /// result types it is implemented for. Therefore, it can be used
1116 /// instead of `unwrap` as a maintainability safeguard that will fail
1117 /// to compile if the error type of the `Result` is later changed
1118 /// to an error that can actually occur.
1119 ///
1120 /// [`Ok`]: enum.Result.html#variant.Ok
1121 /// [`Err`]: enum.Result.html#variant.Err
1122 /// [`unwrap`]: enum.Result.html#method.unwrap
1123 ///
1124 /// # Examples
1125 ///
1126 /// Basic usage:
1127 ///
1128 /// ```
1129 /// # #![feature(never_type)]
1130 /// # #![feature(unwrap_infallible)]
1131 ///
1132 /// fn only_good_news() -> Result<String, !> {
1133 /// Ok("this is fine".into())
1134 /// }
1135 ///
1136 /// let s: String = only_good_news().into_ok();
1137 /// println!("{}", s);
1138 /// ```
1139 #[inline]
1140 pub fn into_ok(self) -> T {
1141 match self {
1142 Ok(x) => x,
1143 Err(e) => e.into(),
1144 }
1145 }
1146}
1147
f035d41b 1148#[unstable(feature = "inner_deref", issue = "50264")]
b7449926 1149impl<T: Deref, E> Result<T, E> {
f035d41b 1150 /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&<T as Deref>::Target, &E>`.
b7449926 1151 ///
f035d41b
XL
1152 /// Coerces the [`Ok`] variant of the original [`Result`] via [`Deref`](crate::ops::Deref)
1153 /// and returns the new [`Result`].
1154 ///
1155 /// # Examples
1156 ///
1157 /// ```
1158 /// #![feature(inner_deref)]
1159 /// let x: Result<String, u32> = Ok("hello".to_string());
1160 /// let y: Result<&str, &u32> = Ok("hello");
1161 /// assert_eq!(x.as_deref(), y);
1162 ///
1163 /// let x: Result<String, u32> = Err(42);
1164 /// let y: Result<&str, &u32> = Err(&42);
1165 /// assert_eq!(x.as_deref(), y);
1166 /// ```
dfeec247 1167 pub fn as_deref(&self) -> Result<&T::Target, &E> {
b7449926
XL
1168 self.as_ref().map(|t| t.deref())
1169 }
1170}
1171
f035d41b 1172#[unstable(feature = "inner_deref", issue = "50264")]
b7449926 1173impl<T, E: Deref> Result<T, E> {
f035d41b 1174 /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&T, &<E as Deref>::Target>`.
b7449926 1175 ///
f035d41b
XL
1176 /// Coerces the [`Err`] variant of the original [`Result`] via [`Deref`](crate::ops::Deref)
1177 /// and returns the new [`Result`].
dfeec247 1178 pub fn as_deref_err(&self) -> Result<&T, &E::Target> {
b7449926
XL
1179 self.as_ref().map_err(|e| e.deref())
1180 }
1181}
1182
f035d41b 1183#[unstable(feature = "inner_deref", issue = "50264")]
416331ca 1184impl<T: DerefMut, E> Result<T, E> {
f035d41b 1185 /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut <T as DerefMut>::Target, &mut E>`.
416331ca 1186 ///
f035d41b
XL
1187 /// Coerces the [`Ok`] variant of the original [`Result`] via [`DerefMut`](crate::ops::DerefMut)
1188 /// and returns the new [`Result`].
1189 ///
1190 /// # Examples
1191 ///
1192 /// ```
1193 /// #![feature(inner_deref)]
1194 /// let mut s = "HELLO".to_string();
1195 /// let mut x: Result<String, u32> = Ok("hello".to_string());
1196 /// let y: Result<&mut str, &mut u32> = Ok(&mut s);
1197 /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
1198 ///
1199 /// let mut i = 42;
1200 /// let mut x: Result<String, u32> = Err(42);
1201 /// let y: Result<&mut str, &mut u32> = Err(&mut i);
1202 /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
1203 /// ```
dfeec247 1204 pub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E> {
416331ca
XL
1205 self.as_mut().map(|t| t.deref_mut())
1206 }
1207}
1208
f035d41b 1209#[unstable(feature = "inner_deref", issue = "50264")]
416331ca 1210impl<T, E: DerefMut> Result<T, E> {
f035d41b 1211 /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut T, &mut <E as DerefMut>::Target>`.
416331ca 1212 ///
f035d41b
XL
1213 /// Coerces the [`Err`] variant of the original [`Result`] via [`DerefMut`](crate::ops::DerefMut)
1214 /// and returns the new [`Result`].
dfeec247 1215 pub fn as_deref_mut_err(&mut self) -> Result<&mut T, &mut E::Target> {
416331ca
XL
1216 self.as_mut().map_err(|e| e.deref_mut())
1217 }
1218}
1219
2c00a5a8
XL
1220impl<T, E> Result<Option<T>, E> {
1221 /// Transposes a `Result` of an `Option` into an `Option` of a `Result`.
1222 ///
1223 /// `Ok(None)` will be mapped to `None`.
1224 /// `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`.
1225 ///
1226 /// # Examples
1227 ///
1228 /// ```
2c00a5a8
XL
1229 /// #[derive(Debug, Eq, PartialEq)]
1230 /// struct SomeErr;
1231 ///
1232 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1233 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1234 /// assert_eq!(x.transpose(), y);
1235 /// ```
1236 #[inline]
0731742a 1237 #[stable(feature = "transpose_result", since = "1.33.0")]
2c00a5a8
XL
1238 pub fn transpose(self) -> Option<Result<T, E>> {
1239 match self {
1240 Ok(Some(x)) => Some(Ok(x)),
1241 Ok(None) => None,
1242 Err(e) => Some(Err(e)),
c30ab7b3
SL
1243 }
1244 }
1245}
1246
ba9703b0
XL
1247impl<T, E> Result<Result<T, E>, E> {
1248 /// Converts from `Result<Result<T, E>, E>` to `Result<T, E>`
1249 ///
1250 /// # Examples
1251 /// Basic usage:
1252 /// ```
1253 /// #![feature(result_flattening)]
1254 /// let x: Result<Result<&'static str, u32>, u32> = Ok(Ok("hello"));
1255 /// assert_eq!(Ok("hello"), x.flatten());
1256 ///
1257 /// let x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));
1258 /// assert_eq!(Err(6), x.flatten());
1259 ///
1260 /// let x: Result<Result<&'static str, u32>, u32> = Err(6);
1261 /// assert_eq!(Err(6), x.flatten());
1262 /// ```
1263 ///
1264 /// Flattening once only removes one level of nesting:
1265 ///
1266 /// ```
1267 /// #![feature(result_flattening)]
1268 /// let x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok("hello")));
1269 /// assert_eq!(Ok(Ok("hello")), x.flatten());
1270 /// assert_eq!(Ok("hello"), x.flatten().flatten());
1271 /// ```
1272 #[inline]
1273 #[unstable(feature = "result_flattening", issue = "70142")]
1274 pub fn flatten(self) -> Result<T, E> {
1275 self.and_then(convert::identity)
1276 }
1277}
1278
7453a54e
SL
1279// This is a separate function to reduce the code size of the methods
1280#[inline(never)]
1281#[cold]
dfeec247 1282#[track_caller]
416331ca 1283fn unwrap_failed(msg: &str, error: &dyn fmt::Debug) -> ! {
7453a54e
SL
1284 panic!("{}: {:?}", msg, error)
1285}
1286
1a4d82fc
JJ
1287/////////////////////////////////////////////////////////////////////////////
1288// Trait implementations
1289/////////////////////////////////////////////////////////////////////////////
1290
dc9dc135
XL
1291#[stable(feature = "rust1", since = "1.0.0")]
1292impl<T: Clone, E: Clone> Clone for Result<T, E> {
1293 #[inline]
1294 fn clone(&self) -> Self {
1295 match self {
1296 Ok(x) => Ok(x.clone()),
1297 Err(x) => Err(x.clone()),
1298 }
1299 }
1300
1301 #[inline]
1302 fn clone_from(&mut self, source: &Self) {
1303 match (self, source) {
1304 (Ok(to), Ok(from)) => to.clone_from(from),
1305 (Err(to), Err(from)) => to.clone_from(from),
1306 (to, from) => *to = from.clone(),
1307 }
1308 }
1309}
1310
9346a6ac
AL
1311#[stable(feature = "rust1", since = "1.0.0")]
1312impl<T, E> IntoIterator for Result<T, E> {
1313 type Item = T;
1314 type IntoIter = IntoIter<T>;
1315
1316 /// Returns a consuming iterator over the possibly contained value.
1317 ///
b7449926 1318 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
32a655c1 1319 ///
9346a6ac
AL
1320 /// # Examples
1321 ///
a7813a04
XL
1322 /// Basic usage:
1323 ///
9346a6ac
AL
1324 /// ```
1325 /// let x: Result<u32, &str> = Ok(5);
1326 /// let v: Vec<u32> = x.into_iter().collect();
1327 /// assert_eq!(v, [5]);
1328 ///
1329 /// let x: Result<u32, &str> = Err("nothing!");
1330 /// let v: Vec<u32> = x.into_iter().collect();
1331 /// assert_eq!(v, []);
1332 /// ```
1a4d82fc 1333 #[inline]
9346a6ac
AL
1334 fn into_iter(self) -> IntoIter<T> {
1335 IntoIter { inner: self.ok() }
1a4d82fc
JJ
1336 }
1337}
1338
e9174d1e
SL
1339#[stable(since = "1.4.0", feature = "result_iter")]
1340impl<'a, T, E> IntoIterator for &'a Result<T, E> {
1341 type Item = &'a T;
1342 type IntoIter = Iter<'a, T>;
1343
1344 fn into_iter(self) -> Iter<'a, T> {
1345 self.iter()
1346 }
1347}
1348
1349#[stable(since = "1.4.0", feature = "result_iter")]
1350impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
1351 type Item = &'a mut T;
1352 type IntoIter = IterMut<'a, T>;
1353
3b2f2976 1354 fn into_iter(self) -> IterMut<'a, T> {
e9174d1e
SL
1355 self.iter_mut()
1356 }
1357}
1358
1a4d82fc
JJ
1359/////////////////////////////////////////////////////////////////////////////
1360// The Result Iterators
1361/////////////////////////////////////////////////////////////////////////////
1362
9e0c209e
SL
1363/// An iterator over a reference to the [`Ok`] variant of a [`Result`].
1364///
32a655c1
SL
1365/// The iterator yields one value if the result is [`Ok`], otherwise none.
1366///
1367/// Created by [`Result::iter`].
1368///
9e0c209e
SL
1369/// [`Ok`]: enum.Result.html#variant.Ok
1370/// [`Result`]: enum.Result.html
32a655c1 1371/// [`Result::iter`]: enum.Result.html#method.iter
54a0048b 1372#[derive(Debug)]
85aaf69f 1373#[stable(feature = "rust1", since = "1.0.0")]
dfeec247
XL
1374pub struct Iter<'a, T: 'a> {
1375 inner: Option<&'a T>,
1376}
1a4d82fc 1377
85aaf69f 1378#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1379impl<'a, T> Iterator for Iter<'a, T> {
1380 type Item = &'a T;
1381
1382 #[inline]
dfeec247
XL
1383 fn next(&mut self) -> Option<&'a T> {
1384 self.inner.take()
1385 }
1a4d82fc 1386 #[inline]
85aaf69f 1387 fn size_hint(&self) -> (usize, Option<usize>) {
dfeec247 1388 let n = if self.inner.is_some() { 1 } else { 0 };
1a4d82fc
JJ
1389 (n, Some(n))
1390 }
1391}
1392
85aaf69f 1393#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1394impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1395 #[inline]
dfeec247
XL
1396 fn next_back(&mut self) -> Option<&'a T> {
1397 self.inner.take()
1398 }
1a4d82fc
JJ
1399}
1400
85aaf69f 1401#[stable(feature = "rust1", since = "1.0.0")]
0bf4aa26 1402impl<T> ExactSizeIterator for Iter<'_, T> {}
1a4d82fc 1403
0531ce1d 1404#[stable(feature = "fused", since = "1.26.0")]
0bf4aa26 1405impl<T> FusedIterator for Iter<'_, T> {}
9e0c209e 1406
c30ab7b3 1407#[unstable(feature = "trusted_len", issue = "37572")]
0bf4aa26 1408unsafe impl<A> TrustedLen for Iter<'_, A> {}
c30ab7b3 1409
92a42be0 1410#[stable(feature = "rust1", since = "1.0.0")]
0bf4aa26 1411impl<T> Clone for Iter<'_, T> {
b7449926 1412 #[inline]
dfeec247
XL
1413 fn clone(&self) -> Self {
1414 Iter { inner: self.inner }
1415 }
1a4d82fc
JJ
1416}
1417
9e0c209e
SL
1418/// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
1419///
32a655c1
SL
1420/// Created by [`Result::iter_mut`].
1421///
9e0c209e
SL
1422/// [`Ok`]: enum.Result.html#variant.Ok
1423/// [`Result`]: enum.Result.html
32a655c1 1424/// [`Result::iter_mut`]: enum.Result.html#method.iter_mut
54a0048b 1425#[derive(Debug)]
85aaf69f 1426#[stable(feature = "rust1", since = "1.0.0")]
dfeec247
XL
1427pub struct IterMut<'a, T: 'a> {
1428 inner: Option<&'a mut T>,
1429}
1a4d82fc 1430
85aaf69f 1431#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1432impl<'a, T> Iterator for IterMut<'a, T> {
1433 type Item = &'a mut T;
1434
1435 #[inline]
dfeec247
XL
1436 fn next(&mut self) -> Option<&'a mut T> {
1437 self.inner.take()
1438 }
1a4d82fc 1439 #[inline]
85aaf69f 1440 fn size_hint(&self) -> (usize, Option<usize>) {
dfeec247 1441 let n = if self.inner.is_some() { 1 } else { 0 };
1a4d82fc
JJ
1442 (n, Some(n))
1443 }
1444}
1445
85aaf69f 1446#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1447impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1448 #[inline]
dfeec247
XL
1449 fn next_back(&mut self) -> Option<&'a mut T> {
1450 self.inner.take()
1451 }
1a4d82fc
JJ
1452}
1453
85aaf69f 1454#[stable(feature = "rust1", since = "1.0.0")]
0bf4aa26 1455impl<T> ExactSizeIterator for IterMut<'_, T> {}
1a4d82fc 1456
0531ce1d 1457#[stable(feature = "fused", since = "1.26.0")]
0bf4aa26 1458impl<T> FusedIterator for IterMut<'_, T> {}
9e0c209e 1459
c30ab7b3 1460#[unstable(feature = "trusted_len", issue = "37572")]
0bf4aa26 1461unsafe impl<A> TrustedLen for IterMut<'_, A> {}
c30ab7b3 1462
32a655c1
SL
1463/// An iterator over the value in a [`Ok`] variant of a [`Result`].
1464///
1465/// The iterator yields one value if the result is [`Ok`], otherwise none.
1466///
1467/// This struct is created by the [`into_iter`] method on
dfeec247 1468/// [`Result`] (provided by the [`IntoIterator`] trait).
9e0c209e
SL
1469///
1470/// [`Ok`]: enum.Result.html#variant.Ok
1471/// [`Result`]: enum.Result.html
1472/// [`into_iter`]: ../iter/trait.IntoIterator.html#tymethod.into_iter
1473/// [`IntoIterator`]: ../iter/trait.IntoIterator.html
abe05a73 1474#[derive(Clone, Debug)]
85aaf69f 1475#[stable(feature = "rust1", since = "1.0.0")]
dfeec247
XL
1476pub struct IntoIter<T> {
1477 inner: Option<T>,
1478}
1a4d82fc 1479
85aaf69f 1480#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1481impl<T> Iterator for IntoIter<T> {
1482 type Item = T;
1483
1484 #[inline]
dfeec247
XL
1485 fn next(&mut self) -> Option<T> {
1486 self.inner.take()
1487 }
1a4d82fc 1488 #[inline]
85aaf69f 1489 fn size_hint(&self) -> (usize, Option<usize>) {
dfeec247 1490 let n = if self.inner.is_some() { 1 } else { 0 };
1a4d82fc
JJ
1491 (n, Some(n))
1492 }
1493}
1494
85aaf69f 1495#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1496impl<T> DoubleEndedIterator for IntoIter<T> {
1497 #[inline]
dfeec247
XL
1498 fn next_back(&mut self) -> Option<T> {
1499 self.inner.take()
1500 }
1a4d82fc
JJ
1501}
1502
85aaf69f 1503#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1504impl<T> ExactSizeIterator for IntoIter<T> {}
1505
0531ce1d 1506#[stable(feature = "fused", since = "1.26.0")]
9e0c209e
SL
1507impl<T> FusedIterator for IntoIter<T> {}
1508
c30ab7b3
SL
1509#[unstable(feature = "trusted_len", issue = "37572")]
1510unsafe impl<A> TrustedLen for IntoIter<A> {}
1511
1a4d82fc
JJ
1512/////////////////////////////////////////////////////////////////////////////
1513// FromIterator
1514/////////////////////////////////////////////////////////////////////////////
1515
85aaf69f 1516#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
1517impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
1518 /// Takes each element in the `Iterator`: if it is an `Err`, no further
1519 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
1520 /// container with the values of each `Result` is returned.
1521 ///
1522 /// Here is an example which increments every integer in a vector,
1523 /// checking for overflow:
1524 ///
c34b1796 1525 /// ```
c30ab7b3 1526 /// let v = vec![1, 2];
041b39d2
XL
1527 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1528 /// x.checked_add(1).ok_or("Overflow!")
1a4d82fc 1529 /// ).collect();
532ac7d7 1530 /// assert_eq!(res, Ok(vec![2, 3]));
1a4d82fc 1531 /// ```
532ac7d7
XL
1532 ///
1533 /// Here is another example that tries to subtract one from another list
1534 /// of integers, this time checking for underflow:
1535 ///
1536 /// ```
1537 /// let v = vec![1, 2, 0];
1538 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1539 /// x.checked_sub(1).ok_or("Underflow!")
1540 /// ).collect();
1541 /// assert_eq!(res, Err("Underflow!"));
1542 /// ```
1543 ///
1544 /// Here is a variation on the previous example, showing that no
1545 /// further elements are taken from `iter` after the first `Err`.
1546 ///
1547 /// ```
1548 /// let v = vec![3, 2, 1, 10];
1549 /// let mut shared = 0;
1550 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {
1551 /// shared += x;
1552 /// x.checked_sub(2).ok_or("Underflow!")
1553 /// }).collect();
1554 /// assert_eq!(res, Err("Underflow!"));
1555 /// assert_eq!(shared, 6);
1556 /// ```
1557 ///
1558 /// Since the third element caused an underflow, no further elements were taken,
1559 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1a4d82fc 1560 #[inline]
dfeec247 1561 fn from_iter<I: IntoIterator<Item = Result<A, E>>>(iter: I) -> Result<V, E> {
1a4d82fc
JJ
1562 // FIXME(#11084): This could be replaced with Iterator::scan when this
1563 // performance bug is closed.
1564
416331ca 1565 iter::process_results(iter.into_iter(), |i| i.collect())
1a4d82fc
JJ
1566 }
1567}
7cac9316
XL
1568
1569#[unstable(feature = "try_trait", issue = "42327")]
dfeec247 1570impl<T, E> ops::Try for Result<T, E> {
7cac9316
XL
1571 type Ok = T;
1572 type Error = E;
1573
b7449926 1574 #[inline]
7cac9316
XL
1575 fn into_result(self) -> Self {
1576 self
1577 }
1578
b7449926 1579 #[inline]
7cac9316
XL
1580 fn from_ok(v: T) -> Self {
1581 Ok(v)
1582 }
1583
b7449926 1584 #[inline]
7cac9316
XL
1585 fn from_error(v: E) -> Self {
1586 Err(v)
1587 }
041b39d2 1588}