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