1 //! Error handling with the `Result` type.
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
6 //! and containing an error value.
9 //! # #[allow(dead_code)]
10 //! enum Result<T, E> {
16 //! Functions return [`Result`] whenever errors are expected and
17 //! recoverable. In the `std` crate, [`Result`] is most prominently used
18 //! for [I/O](../../std/io/index.html).
20 //! A simple function returning [`Result`] might be
21 //! defined and used like so:
25 //! enum Version { Version1, Version2 }
27 //! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
28 //! match header.get(0) {
29 //! None => Err("invalid header length"),
30 //! Some(&1) => Ok(Version::Version1),
31 //! Some(&2) => Ok(Version::Version2),
32 //! Some(_) => Err("invalid version"),
36 //! let version = parse_version(&[1, 2, 3, 4]);
38 //! Ok(v) => println!("working with version: {v:?}"),
39 //! Err(e) => println!("error parsing header: {e:?}"),
43 //! Pattern matching on [`Result`]s is clear and straightforward for
44 //! simple cases, but [`Result`] comes with some convenience methods
45 //! that make working with it more succinct.
48 //! let good_result: Result<i32, i32> = Ok(10);
49 //! let bad_result: Result<i32, i32> = Err(10);
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());
55 //! // `map` consumes the `Result` and produces another.
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);
59 //! // Use `and_then` to continue the computation.
60 //! let good_result: Result<bool, i32> = good_result.and_then(|i| Ok(i == 11));
62 //! // Use `or_else` to handle the error.
63 //! let bad_result: Result<i32, i32> = bad_result.or_else(|i| Ok(i + 20));
65 //! // Consume the result and return the contents with `unwrap`.
66 //! let final_awesome_result = good_result.unwrap();
69 //! # Results must be used
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
73 //! the error. [`Result`] is annotated with the `#[must_use]` attribute,
74 //! which will cause the compiler to issue a warning when a Result
75 //! value is ignored. This makes [`Result`] especially useful with
76 //! functions that may encounter errors but don't otherwise return a
79 //! Consider the [`write_all`] method defined for I/O types
80 //! by the [`Write`] trait:
86 //! fn write_all(&mut self, bytes: &[u8]) -> Result<(), io::Error>;
90 //! *Note: The actual definition of [`Write`] uses [`io::Result`], which
91 //! is just a synonym for <code>[Result]<T, [io::Error]></code>.*
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:
98 //! # #![allow(unused_must_use)] // \o/
99 //! use std::fs::File;
100 //! use std::io::prelude::*;
102 //! let mut file = File::create("valuable_data.txt").unwrap();
103 //! // If `write_all` errors, then we'll never know, because the return
104 //! // value is ignored.
105 //! file.write_all(b"important message");
108 //! If you *do* write that in Rust, the compiler will give you a
109 //! warning (by default, controlled by the `unused_must_use` lint).
111 //! You might instead, if you don't want to handle the error, simply
112 //! assert success with [`expect`]. This will panic if the
113 //! write fails, providing a marginally useful message indicating why:
116 //! use std::fs::File;
117 //! use std::io::prelude::*;
119 //! let mut file = File::create("valuable_data.txt").unwrap();
120 //! file.write_all(b"important message").expect("failed to write message");
123 //! You might also simply assert success:
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());
132 //! Or propagate the error up the call stack with [`?`]:
135 //! # use std::fs::File;
136 //! # use std::io::prelude::*;
138 //! # #[allow(dead_code)]
139 //! fn write_message() -> io::Result<()> {
140 //! let mut file = File::create("valuable_data.txt")?;
141 //! file.write_all(b"important message")?;
146 //! # The question mark operator, `?`
148 //! When writing code that calls many functions that return the
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.
153 //! It replaces this:
156 //! # #![allow(dead_code)]
157 //! use std::fs::File;
158 //! use std::io::prelude::*;
167 //! fn write_info(info: &Info) -> io::Result<()> {
168 //! // Early return on error
169 //! let mut file = match File::create("my_best_friends.txt") {
170 //! Err(e) => return Err(e),
173 //! if let Err(e) = file.write_all(format!("name: {}\n", info.name).as_bytes()) {
176 //! if let Err(e) = file.write_all(format!("age: {}\n", info.age).as_bytes()) {
179 //! if let Err(e) = file.write_all(format!("rating: {}\n", info.rating).as_bytes()) {
189 //! # #![allow(dead_code)]
190 //! use std::fs::File;
191 //! use std::io::prelude::*;
200 //! fn write_info(info: &Info) -> io::Result<()> {
201 //! let mut file = File::create("my_best_friends.txt")?;
202 //! // Early return on error
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())?;
210 //! *It's much nicer!*
212 //! Ending the expression with [`?`] will result in the [`Ok`]'s unwrapped value, unless the result
213 //! is [`Err`], in which case [`Err`] is returned early from the enclosing function.
215 //! [`?`] can be used in functions that return [`Result`] because of the
216 //! early return of [`Err`] that it provides.
218 //! [`expect`]: Result::expect
219 //! [`Write`]: ../../std/io/trait.Write.html "io::Write"
220 //! [`write_all`]: ../../std/io/trait.Write.html#method.write_all "io::Write::write_all"
221 //! [`io::Result`]: ../../std/io/type.Result.html "io::Result"
222 //! [`?`]: crate::ops::Try
225 //! [io::Error]: ../../std/io/struct.Error.html "io::Error"
227 //! # Method overview
229 //! In addition to working with pattern matching, [`Result`] provides a
230 //! wide variety of different methods.
232 //! ## Querying the variant
234 //! The [`is_ok`] and [`is_err`] methods return [`true`] if the [`Result`]
235 //! is [`Ok`] or [`Err`], respectively.
237 //! [`is_err`]: Result::is_err
238 //! [`is_ok`]: Result::is_ok
240 //! ## Adapters for working with references
242 //! * [`as_ref`] converts from `&Result<T, E>` to `Result<&T, &E>`
243 //! * [`as_mut`] converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`
244 //! * [`as_deref`] converts from `&Result<T, E>` to `Result<&T::Target, &E>`
245 //! * [`as_deref_mut`] converts from `&mut Result<T, E>` to
246 //! `Result<&mut T::Target, &mut E>`
248 //! [`as_deref`]: Result::as_deref
249 //! [`as_deref_mut`]: Result::as_deref_mut
250 //! [`as_mut`]: Result::as_mut
251 //! [`as_ref`]: Result::as_ref
253 //! ## Extracting contained values
255 //! These methods extract the contained value in a [`Result<T, E>`] when it
256 //! is the [`Ok`] variant. If the [`Result`] is [`Err`]:
258 //! * [`expect`] panics with a provided custom message
259 //! * [`unwrap`] panics with a generic message
260 //! * [`unwrap_or`] returns the provided default value
261 //! * [`unwrap_or_default`] returns the default value of the type `T`
262 //! (which must implement the [`Default`] trait)
263 //! * [`unwrap_or_else`] returns the result of evaluating the provided
266 //! The panicking methods [`expect`] and [`unwrap`] require `E` to
267 //! implement the [`Debug`] trait.
269 //! [`Debug`]: crate::fmt::Debug
270 //! [`expect`]: Result::expect
271 //! [`unwrap`]: Result::unwrap
272 //! [`unwrap_or`]: Result::unwrap_or
273 //! [`unwrap_or_default`]: Result::unwrap_or_default
274 //! [`unwrap_or_else`]: Result::unwrap_or_else
276 //! These methods extract the contained value in a [`Result<T, E>`] when it
277 //! is the [`Err`] variant. They require `T` to implement the [`Debug`]
278 //! trait. If the [`Result`] is [`Ok`]:
280 //! * [`expect_err`] panics with a provided custom message
281 //! * [`unwrap_err`] panics with a generic message
283 //! [`Debug`]: crate::fmt::Debug
284 //! [`expect_err`]: Result::expect_err
285 //! [`unwrap_err`]: Result::unwrap_err
287 //! ## Transforming contained values
289 //! These methods transform [`Result`] to [`Option`]:
291 //! * [`err`][Result::err] transforms [`Result<T, E>`] into [`Option<E>`],
292 //! mapping [`Err(e)`] to [`Some(e)`] and [`Ok(v)`] to [`None`]
293 //! * [`ok`][Result::ok] transforms [`Result<T, E>`] into [`Option<T>`],
294 //! mapping [`Ok(v)`] to [`Some(v)`] and [`Err(e)`] to [`None`]
295 //! * [`transpose`] transposes a [`Result`] of an [`Option`] into an
296 //! [`Option`] of a [`Result`]
298 // Do NOT add link reference definitions for `err` or `ok`, because they
299 // will generate numerous incorrect URLs for `Err` and `Ok` elsewhere, due
304 //! [`Some(e)`]: Option::Some
305 //! [`Some(v)`]: Option::Some
306 //! [`transpose`]: Result::transpose
308 //! This method transforms the contained value of the [`Ok`] variant:
310 //! * [`map`] transforms [`Result<T, E>`] into [`Result<U, E>`] by applying
311 //! the provided function to the contained value of [`Ok`] and leaving
312 //! [`Err`] values unchanged
314 //! [`map`]: Result::map
316 //! This method transforms the contained value of the [`Err`] variant:
318 //! * [`map_err`] transforms [`Result<T, E>`] into [`Result<T, F>`] by
319 //! applying the provided function to the contained value of [`Err`] and
320 //! leaving [`Ok`] values unchanged
322 //! [`map_err`]: Result::map_err
324 //! These methods transform a [`Result<T, E>`] into a value of a possibly
325 //! different type `U`:
327 //! * [`map_or`] applies the provided function to the contained value of
328 //! [`Ok`], or returns the provided default value if the [`Result`] is
330 //! * [`map_or_else`] applies the provided function to the contained value
331 //! of [`Ok`], or applies the provided default fallback function to the
332 //! contained value of [`Err`]
334 //! [`map_or`]: Result::map_or
335 //! [`map_or_else`]: Result::map_or_else
337 //! ## Boolean operators
339 //! These methods treat the [`Result`] as a boolean value, where [`Ok`]
340 //! acts like [`true`] and [`Err`] acts like [`false`]. There are two
341 //! categories of these methods: ones that take a [`Result`] as input, and
342 //! ones that take a function as input (to be lazily evaluated).
344 //! The [`and`] and [`or`] methods take another [`Result`] as input, and
345 //! produce a [`Result`] as output. The [`and`] method can produce a
346 //! [`Result<U, E>`] value having a different inner type `U` than
347 //! [`Result<T, E>`]. The [`or`] method can produce a [`Result<T, F>`]
348 //! value having a different error type `F` than [`Result<T, E>`].
350 //! | method | self | input | output |
351 //! |---------|----------|-----------|----------|
352 //! | [`and`] | `Err(e)` | (ignored) | `Err(e)` |
353 //! | [`and`] | `Ok(x)` | `Err(d)` | `Err(d)` |
354 //! | [`and`] | `Ok(x)` | `Ok(y)` | `Ok(y)` |
355 //! | [`or`] | `Err(e)` | `Err(d)` | `Err(d)` |
356 //! | [`or`] | `Err(e)` | `Ok(y)` | `Ok(y)` |
357 //! | [`or`] | `Ok(x)` | (ignored) | `Ok(x)` |
359 //! [`and`]: Result::and
360 //! [`or`]: Result::or
362 //! The [`and_then`] and [`or_else`] methods take a function as input, and
363 //! only evaluate the function when they need to produce a new value. The
364 //! [`and_then`] method can produce a [`Result<U, E>`] value having a
365 //! different inner type `U` than [`Result<T, E>`]. The [`or_else`] method
366 //! can produce a [`Result<T, F>`] value having a different error type `F`
367 //! than [`Result<T, E>`].
369 //! | method | self | function input | function result | output |
370 //! |--------------|----------|----------------|-----------------|----------|
371 //! | [`and_then`] | `Err(e)` | (not provided) | (not evaluated) | `Err(e)` |
372 //! | [`and_then`] | `Ok(x)` | `x` | `Err(d)` | `Err(d)` |
373 //! | [`and_then`] | `Ok(x)` | `x` | `Ok(y)` | `Ok(y)` |
374 //! | [`or_else`] | `Err(e)` | `e` | `Err(d)` | `Err(d)` |
375 //! | [`or_else`] | `Err(e)` | `e` | `Ok(y)` | `Ok(y)` |
376 //! | [`or_else`] | `Ok(x)` | (not provided) | (not evaluated) | `Ok(x)` |
378 //! [`and_then`]: Result::and_then
379 //! [`or_else`]: Result::or_else
381 //! ## Comparison operators
383 //! If `T` and `E` both implement [`PartialOrd`] then [`Result<T, E>`] will
384 //! derive its [`PartialOrd`] implementation. With this order, an [`Ok`]
385 //! compares as less than any [`Err`], while two [`Ok`] or two [`Err`]
386 //! compare as their contained values would in `T` or `E` respectively. If `T`
387 //! and `E` both also implement [`Ord`], then so does [`Result<T, E>`].
390 //! assert!(Ok(1) < Err(0));
391 //! let x: Result<i32, ()> = Ok(0);
394 //! let x: Result<(), i32> = Err(0);
399 //! ## Iterating over `Result`
401 //! A [`Result`] can be iterated over. This can be helpful if you need an
402 //! iterator that is conditionally empty. The iterator will either produce
403 //! a single value (when the [`Result`] is [`Ok`]), or produce no values
404 //! (when the [`Result`] is [`Err`]). For example, [`into_iter`] acts like
405 //! [`once(v)`] if the [`Result`] is [`Ok(v)`], and like [`empty()`] if the
406 //! [`Result`] is [`Err`].
409 //! [`empty()`]: crate::iter::empty
410 //! [`once(v)`]: crate::iter::once
412 //! Iterators over [`Result<T, E>`] come in three types:
414 //! * [`into_iter`] consumes the [`Result`] and produces the contained
416 //! * [`iter`] produces an immutable reference of type `&T` to the
418 //! * [`iter_mut`] produces a mutable reference of type `&mut T` to the
421 //! See [Iterating over `Option`] for examples of how this can be useful.
423 //! [Iterating over `Option`]: crate::option#iterating-over-option
424 //! [`into_iter`]: Result::into_iter
425 //! [`iter`]: Result::iter
426 //! [`iter_mut`]: Result::iter_mut
428 //! You might want to use an iterator chain to do multiple instances of an
429 //! operation that can fail, but would like to ignore failures while
430 //! continuing to process the successful results. In this example, we take
431 //! advantage of the iterable nature of [`Result`] to select only the
432 //! [`Ok`] values using [`flatten`][Iterator::flatten].
435 //! # use std::str::FromStr;
436 //! let mut results = vec![];
437 //! let mut errs = vec![];
438 //! let nums: Vec<_> = ["17", "not a number", "99", "-27", "768"]
440 //! .map(u8::from_str)
441 //! // Save clones of the raw `Result` values to inspect
442 //! .inspect(|x| results.push(x.clone()))
443 //! // Challenge: explain how this captures only the `Err` values
444 //! .inspect(|x| errs.extend(x.clone().err()))
447 //! assert_eq!(errs.len(), 3);
448 //! assert_eq!(nums, [17, 99]);
449 //! println!("results {results:?}");
450 //! println!("errs {errs:?}");
451 //! println!("nums {nums:?}");
454 //! ## Collecting into `Result`
456 //! [`Result`] implements the [`FromIterator`][impl-FromIterator] trait,
457 //! which allows an iterator over [`Result`] values to be collected into a
458 //! [`Result`] of a collection of each contained value of the original
459 //! [`Result`] values, or [`Err`] if any of the elements was [`Err`].
461 //! [impl-FromIterator]: Result#impl-FromIterator%3CResult%3CA,+E%3E%3E-for-Result%3CV,+E%3E
464 //! let v = [Ok(2), Ok(4), Err("err!"), Ok(8)];
465 //! let res: Result<Vec<_>, &str> = v.into_iter().collect();
466 //! assert_eq!(res, Err("err!"));
467 //! let v = [Ok(2), Ok(4), Ok(8)];
468 //! let res: Result<Vec<_>, &str> = v.into_iter().collect();
469 //! assert_eq!(res, Ok(vec![2, 4, 8]));
472 //! [`Result`] also implements the [`Product`][impl-Product] and
473 //! [`Sum`][impl-Sum] traits, allowing an iterator over [`Result`] values
474 //! to provide the [`product`][Iterator::product] and
475 //! [`sum`][Iterator::sum] methods.
477 //! [impl-Product]: Result#impl-Product%3CResult%3CU,+E%3E%3E-for-Result%3CT,+E%3E
478 //! [impl-Sum]: Result#impl-Sum%3CResult%3CU,+E%3E%3E-for-Result%3CT,+E%3E
481 //! let v = [Err("error!"), Ok(1), Ok(2), Ok(3), Err("foo")];
482 //! let res: Result<i32, &str> = v.into_iter().sum();
483 //! assert_eq!(res, Err("error!"));
484 //! let v = [Ok(1), Ok(2), Ok(21)];
485 //! let res: Result<i32, &str> = v.into_iter().product();
486 //! assert_eq!(res, Ok(42));
489 #![stable(feature = "rust1", since = "1.0.0")]
491 use crate::iter
::{self, FromIterator, FusedIterator, TrustedLen}
;
492 use crate::ops
::{self, ControlFlow, Deref, DerefMut}
;
493 use crate::{convert, fmt, hint}
;
495 /// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]).
497 /// See the [module documentation](self) for details.
498 #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
499 #[must_use = "this `Result` may be an `Err` variant, which should be handled"]
500 #[rustc_diagnostic_item = "Result"]
501 #[stable(feature = "rust1", since = "1.0.0")]
502 pub enum Result
<T
, E
> {
503 /// Contains the success value
505 #[stable(feature = "rust1", since = "1.0.0")]
506 Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
508 /// Contains the error value
510 #[stable(feature = "rust1", since = "1.0.0")]
511 Err(#[stable(feature = "rust1", since = "1.0.0")] E),
514 /////////////////////////////////////////////////////////////////////////////
515 // Type implementation
516 /////////////////////////////////////////////////////////////////////////////
518 impl<T
, E
> Result
<T
, E
> {
519 /////////////////////////////////////////////////////////////////////////
520 // Querying the contained values
521 /////////////////////////////////////////////////////////////////////////
523 /// Returns `true` if the result is [`Ok`].
528 /// let x: Result<i32, &str> = Ok(-3);
529 /// assert_eq!(x.is_ok(), true);
531 /// let x: Result<i32, &str> = Err("Some error message");
532 /// assert_eq!(x.is_ok(), false);
534 #[must_use = "if you intended to assert that this is ok, consider `.unwrap()` instead"]
535 #[rustc_const_stable(feature = "const_result_basics", since = "1.48.0")]
537 #[stable(feature = "rust1", since = "1.0.0")]
538 pub const fn is_ok(&self) -> bool
{
539 matches
!(*self, Ok(_
))
542 /// Returns `true` if the result is [`Ok`] and the value inside of it matches a predicate.
547 /// let x: Result<u32, &str> = Ok(2);
548 /// assert_eq!(x.is_ok_and(|x| x > 1), true);
550 /// let x: Result<u32, &str> = Ok(0);
551 /// assert_eq!(x.is_ok_and(|x| x > 1), false);
553 /// let x: Result<u32, &str> = Err("hey");
554 /// assert_eq!(x.is_ok_and(|x| x > 1), false);
558 #[stable(feature = "is_some_and", since = "1.70.0")]
559 pub fn is_ok_and(self, f
: impl FnOnce(T
) -> bool
) -> bool
{
566 /// Returns `true` if the result is [`Err`].
571 /// let x: Result<i32, &str> = Ok(-3);
572 /// assert_eq!(x.is_err(), false);
574 /// let x: Result<i32, &str> = Err("Some error message");
575 /// assert_eq!(x.is_err(), true);
577 #[must_use = "if you intended to assert that this is err, consider `.unwrap_err()` instead"]
578 #[rustc_const_stable(feature = "const_result_basics", since = "1.48.0")]
580 #[stable(feature = "rust1", since = "1.0.0")]
581 pub const fn is_err(&self) -> bool
{
585 /// Returns `true` if the result is [`Err`] and the value inside of it matches a predicate.
590 /// use std::io::{Error, ErrorKind};
592 /// let x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, "!"));
593 /// assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);
595 /// let x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, "!"));
596 /// assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
598 /// let x: Result<u32, Error> = Ok(123);
599 /// assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
603 #[stable(feature = "is_some_and", since = "1.70.0")]
604 pub fn is_err_and(self, f
: impl FnOnce(E
) -> bool
) -> bool
{
611 /////////////////////////////////////////////////////////////////////////
612 // Adapter for each variant
613 /////////////////////////////////////////////////////////////////////////
615 /// Converts from `Result<T, E>` to [`Option<T>`].
617 /// Converts `self` into an [`Option<T>`], consuming `self`,
618 /// and discarding the error, if any.
623 /// let x: Result<u32, &str> = Ok(2);
624 /// assert_eq!(x.ok(), Some(2));
626 /// let x: Result<u32, &str> = Err("Nothing here");
627 /// assert_eq!(x.ok(), None);
630 #[stable(feature = "rust1", since = "1.0.0")]
631 pub fn ok(self) -> Option
<T
> {
638 /// Converts from `Result<T, E>` to [`Option<E>`].
640 /// Converts `self` into an [`Option<E>`], consuming `self`,
641 /// and discarding the success value, if any.
646 /// let x: Result<u32, &str> = Ok(2);
647 /// assert_eq!(x.err(), None);
649 /// let x: Result<u32, &str> = Err("Nothing here");
650 /// assert_eq!(x.err(), Some("Nothing here"));
653 #[stable(feature = "rust1", since = "1.0.0")]
654 pub fn err(self) -> Option
<E
> {
661 /////////////////////////////////////////////////////////////////////////
662 // Adapter for working with references
663 /////////////////////////////////////////////////////////////////////////
665 /// Converts from `&Result<T, E>` to `Result<&T, &E>`.
667 /// Produces a new `Result`, containing a reference
668 /// into the original, leaving the original in place.
673 /// let x: Result<u32, &str> = Ok(2);
674 /// assert_eq!(x.as_ref(), Ok(&2));
676 /// let x: Result<u32, &str> = Err("Error");
677 /// assert_eq!(x.as_ref(), Err(&"Error"));
680 #[rustc_const_stable(feature = "const_result_basics", since = "1.48.0")]
681 #[stable(feature = "rust1", since = "1.0.0")]
682 pub const fn as_ref(&self) -> Result
<&T
, &E
> {
685 Err(ref x
) => Err(x
),
689 /// Converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`.
694 /// fn mutate(r: &mut Result<i32, i32>) {
695 /// match r.as_mut() {
696 /// Ok(v) => *v = 42,
697 /// Err(e) => *e = 0,
701 /// let mut x: Result<i32, i32> = Ok(2);
703 /// assert_eq!(x.unwrap(), 42);
705 /// let mut x: Result<i32, i32> = Err(13);
707 /// assert_eq!(x.unwrap_err(), 0);
710 #[stable(feature = "rust1", since = "1.0.0")]
711 #[rustc_const_unstable(feature = "const_result", issue = "82814")]
712 pub const fn as_mut(&mut self) -> Result
<&mut T
, &mut E
> {
714 Ok(ref mut x
) => Ok(x
),
715 Err(ref mut x
) => Err(x
),
719 /////////////////////////////////////////////////////////////////////////
720 // Transforming contained values
721 /////////////////////////////////////////////////////////////////////////
723 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
724 /// contained [`Ok`] value, leaving an [`Err`] value untouched.
726 /// This function can be used to compose the results of two functions.
730 /// Print the numbers on each line of a string multiplied by two.
733 /// let line = "1\n2\n3\n4\n";
735 /// for num in line.lines() {
736 /// match num.parse::<i32>().map(|i| i * 2) {
737 /// Ok(n) => println!("{n}"),
743 #[stable(feature = "rust1", since = "1.0.0")]
744 pub fn map
<U
, F
: FnOnce(T
) -> U
>(self, op
: F
) -> Result
<U
, E
> {
751 /// Returns the provided default (if [`Err`]), or
752 /// applies a function to the contained value (if [`Ok`]).
754 /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
755 /// the result of a function call, it is recommended to use [`map_or_else`],
756 /// which is lazily evaluated.
758 /// [`map_or_else`]: Result::map_or_else
763 /// let x: Result<_, &str> = Ok("foo");
764 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
766 /// let x: Result<&str, _> = Err("bar");
767 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
770 #[stable(feature = "result_map_or", since = "1.41.0")]
771 #[must_use = "if you don't need the returned value, use `if let` instead"]
772 pub fn map_or
<U
, F
: FnOnce(T
) -> U
>(self, default: U
, f
: F
) -> U
{
779 /// Maps a `Result<T, E>` to `U` by applying fallback function `default` to
780 /// a contained [`Err`] value, or function `f` to a contained [`Ok`] value.
782 /// This function can be used to unpack a successful result
783 /// while handling an error.
791 /// let x : Result<_, &str> = Ok("foo");
792 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);
794 /// let x : Result<&str, _> = Err("bar");
795 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
798 #[stable(feature = "result_map_or_else", since = "1.41.0")]
799 pub fn map_or_else
<U
, D
: FnOnce(E
) -> U
, F
: FnOnce(T
) -> U
>(self, default: D
, f
: F
) -> U
{
802 Err(e
) => default(e
),
806 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
807 /// contained [`Err`] value, leaving an [`Ok`] value untouched.
809 /// This function can be used to pass through a successful result while handling
816 /// fn stringify(x: u32) -> String { format!("error code: {x}") }
818 /// let x: Result<u32, u32> = Ok(2);
819 /// assert_eq!(x.map_err(stringify), Ok(2));
821 /// let x: Result<u32, u32> = Err(13);
822 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
825 #[stable(feature = "rust1", since = "1.0.0")]
826 pub fn map_err
<F
, O
: FnOnce(E
) -> F
>(self, op
: O
) -> Result
<T
, F
> {
829 Err(e
) => Err(op(e
)),
833 /// Calls the provided closure with a reference to the contained value (if [`Ok`]).
838 /// #![feature(result_option_inspect)]
842 /// .inspect(|x| println!("original: {x}"))
843 /// .map(|x| x.pow(3))
844 /// .expect("failed to parse number");
847 #[unstable(feature = "result_option_inspect", issue = "91345")]
848 pub fn inspect
<F
: FnOnce(&T
)>(self, f
: F
) -> Self {
849 if let Ok(ref t
) = self {
856 /// Calls the provided closure with a reference to the contained error (if [`Err`]).
861 /// #![feature(result_option_inspect)]
863 /// use std::{fs, io};
865 /// fn read() -> io::Result<String> {
866 /// fs::read_to_string("address.txt")
867 /// .inspect_err(|e| eprintln!("failed to read file: {e}"))
871 #[unstable(feature = "result_option_inspect", issue = "91345")]
872 pub fn inspect_err
<F
: FnOnce(&E
)>(self, f
: F
) -> Self {
873 if let Err(ref e
) = self {
880 /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&<T as Deref>::Target, &E>`.
882 /// Coerces the [`Ok`] variant of the original [`Result`] via [`Deref`](crate::ops::Deref)
883 /// and returns the new [`Result`].
888 /// let x: Result<String, u32> = Ok("hello".to_string());
889 /// let y: Result<&str, &u32> = Ok("hello");
890 /// assert_eq!(x.as_deref(), y);
892 /// let x: Result<String, u32> = Err(42);
893 /// let y: Result<&str, &u32> = Err(&42);
894 /// assert_eq!(x.as_deref(), y);
897 #[stable(feature = "inner_deref", since = "1.47.0")]
898 pub fn as_deref(&self) -> Result
<&T
::Target
, &E
>
902 self.as_ref().map(|t
| t
.deref())
905 /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut <T as DerefMut>::Target, &mut E>`.
907 /// Coerces the [`Ok`] variant of the original [`Result`] via [`DerefMut`](crate::ops::DerefMut)
908 /// and returns the new [`Result`].
913 /// let mut s = "HELLO".to_string();
914 /// let mut x: Result<String, u32> = Ok("hello".to_string());
915 /// let y: Result<&mut str, &mut u32> = Ok(&mut s);
916 /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
919 /// let mut x: Result<String, u32> = Err(42);
920 /// let y: Result<&mut str, &mut u32> = Err(&mut i);
921 /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
924 #[stable(feature = "inner_deref", since = "1.47.0")]
925 pub fn as_deref_mut(&mut self) -> Result
<&mut T
::Target
, &mut E
>
929 self.as_mut().map(|t
| t
.deref_mut())
932 /////////////////////////////////////////////////////////////////////////
933 // Iterator constructors
934 /////////////////////////////////////////////////////////////////////////
936 /// Returns an iterator over the possibly contained value.
938 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
943 /// let x: Result<u32, &str> = Ok(7);
944 /// assert_eq!(x.iter().next(), Some(&7));
946 /// let x: Result<u32, &str> = Err("nothing!");
947 /// assert_eq!(x.iter().next(), None);
950 #[stable(feature = "rust1", since = "1.0.0")]
951 pub fn iter(&self) -> Iter
<'_
, T
> {
952 Iter { inner: self.as_ref().ok() }
955 /// Returns a mutable iterator over the possibly contained value.
957 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
962 /// let mut x: Result<u32, &str> = Ok(7);
963 /// match x.iter_mut().next() {
964 /// Some(v) => *v = 40,
967 /// assert_eq!(x, Ok(40));
969 /// let mut x: Result<u32, &str> = Err("nothing!");
970 /// assert_eq!(x.iter_mut().next(), None);
973 #[stable(feature = "rust1", since = "1.0.0")]
974 pub fn iter_mut(&mut self) -> IterMut
<'_
, T
> {
975 IterMut { inner: self.as_mut().ok() }
978 /////////////////////////////////////////////////////////////////////////
980 /////////////////////////////////////////////////////////////////////////
982 /// Returns the contained [`Ok`] value, consuming the `self` value.
984 /// Because this function may panic, its use is generally discouraged.
985 /// Instead, prefer to use pattern matching and handle the [`Err`]
986 /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
987 /// [`unwrap_or_default`].
989 /// [`unwrap_or`]: Result::unwrap_or
990 /// [`unwrap_or_else`]: Result::unwrap_or_else
991 /// [`unwrap_or_default`]: Result::unwrap_or_default
995 /// Panics if the value is an [`Err`], with a panic message including the
996 /// passed message, and the content of the [`Err`].
1002 /// let x: Result<u32, &str> = Err("emergency failure");
1003 /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
1006 /// # Recommended Message Style
1008 /// We recommend that `expect` messages are used to describe the reason you
1009 /// _expect_ the `Result` should be `Ok`.
1012 /// let path = std::env::var("IMPORTANT_PATH")
1013 /// .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`");
1016 /// **Hint**: If you're having trouble remembering how to phrase expect
1017 /// error messages remember to focus on the word "should" as in "env
1018 /// variable should be set by blah" or "the given binary should be available
1019 /// and executable by the current user".
1021 /// For more detail on expect message styles and the reasoning behind our recommendation please
1022 /// refer to the section on ["Common Message
1023 /// Styles"](../../std/error/index.html#common-message-styles) in the
1024 /// [`std::error`](../../std/error/index.html) module docs.
1027 #[stable(feature = "result_expect", since = "1.4.0")]
1028 pub fn expect(self, msg
: &str) -> T
1034 Err(e
) => unwrap_failed(msg
, &e
),
1038 /// Returns the contained [`Ok`] value, consuming the `self` value.
1040 /// Because this function may panic, its use is generally discouraged.
1041 /// Instead, prefer to use pattern matching and handle the [`Err`]
1042 /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
1043 /// [`unwrap_or_default`].
1045 /// [`unwrap_or`]: Result::unwrap_or
1046 /// [`unwrap_or_else`]: Result::unwrap_or_else
1047 /// [`unwrap_or_default`]: Result::unwrap_or_default
1051 /// Panics if the value is an [`Err`], with a panic message provided by the
1052 /// [`Err`]'s value.
1060 /// let x: Result<u32, &str> = Ok(2);
1061 /// assert_eq!(x.unwrap(), 2);
1065 /// let x: Result<u32, &str> = Err("emergency failure");
1066 /// x.unwrap(); // panics with `emergency failure`
1070 #[stable(feature = "rust1", since = "1.0.0")]
1071 pub fn unwrap(self) -> T
1077 Err(e
) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e
),
1081 /// Returns the contained [`Ok`] value or a default
1083 /// Consumes the `self` argument then, if [`Ok`], returns the contained
1084 /// value, otherwise if [`Err`], returns the default value for that
1089 /// Converts a string to an integer, turning poorly-formed strings
1090 /// into 0 (the default value for integers). [`parse`] converts
1091 /// a string to any other type that implements [`FromStr`], returning an
1092 /// [`Err`] on error.
1095 /// let good_year_from_input = "1909";
1096 /// let bad_year_from_input = "190blarg";
1097 /// let good_year = good_year_from_input.parse().unwrap_or_default();
1098 /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
1100 /// assert_eq!(1909, good_year);
1101 /// assert_eq!(0, bad_year);
1104 /// [`parse`]: str::parse
1105 /// [`FromStr`]: crate::str::FromStr
1107 #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
1108 pub fn unwrap_or_default(self) -> T
1114 Err(_
) => Default
::default(),
1118 /// Returns the contained [`Err`] value, consuming the `self` value.
1122 /// Panics if the value is an [`Ok`], with a panic message including the
1123 /// passed message, and the content of the [`Ok`].
1129 /// let x: Result<u32, &str> = Ok(10);
1130 /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
1134 #[stable(feature = "result_expect_err", since = "1.17.0")]
1135 pub fn expect_err(self, msg
: &str) -> E
1140 Ok(t
) => unwrap_failed(msg
, &t
),
1145 /// Returns the contained [`Err`] value, consuming the `self` value.
1149 /// Panics if the value is an [`Ok`], with a custom panic message provided
1150 /// by the [`Ok`]'s value.
1155 /// let x: Result<u32, &str> = Ok(2);
1156 /// x.unwrap_err(); // panics with `2`
1160 /// let x: Result<u32, &str> = Err("emergency failure");
1161 /// assert_eq!(x.unwrap_err(), "emergency failure");
1165 #[stable(feature = "rust1", since = "1.0.0")]
1166 pub fn unwrap_err(self) -> E
1171 Ok(t
) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t
),
1176 /// Returns the contained [`Ok`] value, but never panics.
1178 /// Unlike [`unwrap`], this method is known to never panic on the
1179 /// result types it is implemented for. Therefore, it can be used
1180 /// instead of `unwrap` as a maintainability safeguard that will fail
1181 /// to compile if the error type of the `Result` is later changed
1182 /// to an error that can actually occur.
1184 /// [`unwrap`]: Result::unwrap
1189 /// # #![feature(never_type)]
1190 /// # #![feature(unwrap_infallible)]
1192 /// fn only_good_news() -> Result<String, !> {
1193 /// Ok("this is fine".into())
1196 /// let s: String = only_good_news().into_ok();
1197 /// println!("{s}");
1199 #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
1201 pub fn into_ok(self) -> T
1211 /// Returns the contained [`Err`] value, but never panics.
1213 /// Unlike [`unwrap_err`], this method is known to never panic on the
1214 /// result types it is implemented for. Therefore, it can be used
1215 /// instead of `unwrap_err` as a maintainability safeguard that will fail
1216 /// to compile if the ok type of the `Result` is later changed
1217 /// to a type that can actually occur.
1219 /// [`unwrap_err`]: Result::unwrap_err
1224 /// # #![feature(never_type)]
1225 /// # #![feature(unwrap_infallible)]
1227 /// fn only_bad_news() -> Result<!, String> {
1228 /// Err("Oops, it failed".into())
1231 /// let error: String = only_bad_news().into_err();
1232 /// println!("{error}");
1234 #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
1236 pub fn into_err(self) -> E
1246 ////////////////////////////////////////////////////////////////////////
1247 // Boolean operations on the values, eager and lazy
1248 /////////////////////////////////////////////////////////////////////////
1250 /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
1252 /// Arguments passed to `and` are eagerly evaluated; if you are passing the
1253 /// result of a function call, it is recommended to use [`and_then`], which is
1254 /// lazily evaluated.
1256 /// [`and_then`]: Result::and_then
1261 /// let x: Result<u32, &str> = Ok(2);
1262 /// let y: Result<&str, &str> = Err("late error");
1263 /// assert_eq!(x.and(y), Err("late error"));
1265 /// let x: Result<u32, &str> = Err("early error");
1266 /// let y: Result<&str, &str> = Ok("foo");
1267 /// assert_eq!(x.and(y), Err("early error"));
1269 /// let x: Result<u32, &str> = Err("not a 2");
1270 /// let y: Result<&str, &str> = Err("late error");
1271 /// assert_eq!(x.and(y), Err("not a 2"));
1273 /// let x: Result<u32, &str> = Ok(2);
1274 /// let y: Result<&str, &str> = Ok("different result type");
1275 /// assert_eq!(x.and(y), Ok("different result type"));
1278 #[stable(feature = "rust1", since = "1.0.0")]
1279 pub fn and
<U
>(self, res
: Result
<U
, E
>) -> Result
<U
, E
> {
1286 /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
1289 /// This function can be used for control flow based on `Result` values.
1294 /// fn sq_then_to_string(x: u32) -> Result<String, &'static str> {
1295 /// x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed")
1298 /// assert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));
1299 /// assert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err("overflowed"));
1300 /// assert_eq!(Err("not a number").and_then(sq_then_to_string), Err("not a number"));
1303 /// Often used to chain fallible operations that may return [`Err`].
1306 /// use std::{io::ErrorKind, path::Path};
1308 /// // Note: on Windows "/" maps to "C:\"
1309 /// let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified());
1310 /// assert!(root_modified_time.is_ok());
1312 /// let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified());
1313 /// assert!(should_fail.is_err());
1314 /// assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
1317 #[stable(feature = "rust1", since = "1.0.0")]
1318 pub fn and_then
<U
, F
: FnOnce(T
) -> Result
<U
, E
>>(self, op
: F
) -> Result
<U
, E
> {
1325 /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
1327 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
1328 /// result of a function call, it is recommended to use [`or_else`], which is
1329 /// lazily evaluated.
1331 /// [`or_else`]: Result::or_else
1336 /// let x: Result<u32, &str> = Ok(2);
1337 /// let y: Result<u32, &str> = Err("late error");
1338 /// assert_eq!(x.or(y), Ok(2));
1340 /// let x: Result<u32, &str> = Err("early error");
1341 /// let y: Result<u32, &str> = Ok(2);
1342 /// assert_eq!(x.or(y), Ok(2));
1344 /// let x: Result<u32, &str> = Err("not a 2");
1345 /// let y: Result<u32, &str> = Err("late error");
1346 /// assert_eq!(x.or(y), Err("late error"));
1348 /// let x: Result<u32, &str> = Ok(2);
1349 /// let y: Result<u32, &str> = Ok(100);
1350 /// assert_eq!(x.or(y), Ok(2));
1353 #[stable(feature = "rust1", since = "1.0.0")]
1354 pub fn or
<F
>(self, res
: Result
<T
, F
>) -> Result
<T
, F
> {
1361 /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
1363 /// This function can be used for control flow based on result values.
1369 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
1370 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
1372 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
1373 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
1374 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
1375 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
1378 #[stable(feature = "rust1", since = "1.0.0")]
1379 pub fn or_else
<F
, O
: FnOnce(E
) -> Result
<T
, F
>>(self, op
: O
) -> Result
<T
, F
> {
1386 /// Returns the contained [`Ok`] value or a provided default.
1388 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
1389 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
1390 /// which is lazily evaluated.
1392 /// [`unwrap_or_else`]: Result::unwrap_or_else
1397 /// let default = 2;
1398 /// let x: Result<u32, &str> = Ok(9);
1399 /// assert_eq!(x.unwrap_or(default), 9);
1401 /// let x: Result<u32, &str> = Err("error");
1402 /// assert_eq!(x.unwrap_or(default), default);
1405 #[stable(feature = "rust1", since = "1.0.0")]
1406 pub fn unwrap_or(self, default: T
) -> T
{
1413 /// Returns the contained [`Ok`] value or computes it from a closure.
1419 /// fn count(x: &str) -> usize { x.len() }
1421 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
1422 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
1426 #[stable(feature = "rust1", since = "1.0.0")]
1427 pub fn unwrap_or_else
<F
: FnOnce(E
) -> T
>(self, op
: F
) -> T
{
1434 /// Returns the contained [`Ok`] value, consuming the `self` value,
1435 /// without checking that the value is not an [`Err`].
1439 /// Calling this method on an [`Err`] is *[undefined behavior]*.
1441 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1446 /// let x: Result<u32, &str> = Ok(2);
1447 /// assert_eq!(unsafe { x.unwrap_unchecked() }, 2);
1451 /// let x: Result<u32, &str> = Err("emergency failure");
1452 /// unsafe { x.unwrap_unchecked(); } // Undefined behavior!
1456 #[stable(feature = "option_result_unwrap_unchecked", since = "1.58.0")]
1457 pub unsafe fn unwrap_unchecked(self) -> T
{
1458 debug_assert
!(self.is_ok());
1461 // SAFETY: the safety contract must be upheld by the caller.
1462 Err(_
) => unsafe { hint::unreachable_unchecked() }
,
1466 /// Returns the contained [`Err`] value, consuming the `self` value,
1467 /// without checking that the value is not an [`Ok`].
1471 /// Calling this method on an [`Ok`] is *[undefined behavior]*.
1473 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1478 /// let x: Result<u32, &str> = Ok(2);
1479 /// unsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
1483 /// let x: Result<u32, &str> = Err("emergency failure");
1484 /// assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure");
1488 #[stable(feature = "option_result_unwrap_unchecked", since = "1.58.0")]
1489 pub unsafe fn unwrap_err_unchecked(self) -> E
{
1490 debug_assert
!(self.is_err());
1492 // SAFETY: the safety contract must be upheld by the caller.
1493 Ok(_
) => unsafe { hint::unreachable_unchecked() }
,
1499 impl<T
, E
> Result
<&T
, E
> {
1500 /// Maps a `Result<&T, E>` to a `Result<T, E>` by copying the contents of the
1507 /// let x: Result<&i32, i32> = Ok(&val);
1508 /// assert_eq!(x, Ok(&12));
1509 /// let copied = x.copied();
1510 /// assert_eq!(copied, Ok(12));
1513 #[stable(feature = "result_copied", since = "1.59.0")]
1514 pub fn copied(self) -> Result
<T
, E
>
1521 /// Maps a `Result<&T, E>` to a `Result<T, E>` by cloning the contents of the
1528 /// let x: Result<&i32, i32> = Ok(&val);
1529 /// assert_eq!(x, Ok(&12));
1530 /// let cloned = x.cloned();
1531 /// assert_eq!(cloned, Ok(12));
1534 #[stable(feature = "result_cloned", since = "1.59.0")]
1535 pub fn cloned(self) -> Result
<T
, E
>
1539 self.map(|t
| t
.clone())
1543 impl<T
, E
> Result
<&mut T
, E
> {
1544 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by copying the contents of the
1550 /// let mut val = 12;
1551 /// let x: Result<&mut i32, i32> = Ok(&mut val);
1552 /// assert_eq!(x, Ok(&mut 12));
1553 /// let copied = x.copied();
1554 /// assert_eq!(copied, Ok(12));
1557 #[stable(feature = "result_copied", since = "1.59.0")]
1558 pub fn copied(self) -> Result
<T
, E
>
1562 self.map(|&mut t
| t
)
1565 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by cloning the contents of the
1571 /// let mut val = 12;
1572 /// let x: Result<&mut i32, i32> = Ok(&mut val);
1573 /// assert_eq!(x, Ok(&mut 12));
1574 /// let cloned = x.cloned();
1575 /// assert_eq!(cloned, Ok(12));
1578 #[stable(feature = "result_cloned", since = "1.59.0")]
1579 pub fn cloned(self) -> Result
<T
, E
>
1583 self.map(|t
| t
.clone())
1587 impl<T
, E
> Result
<Option
<T
>, E
> {
1588 /// Transposes a `Result` of an `Option` into an `Option` of a `Result`.
1590 /// `Ok(None)` will be mapped to `None`.
1591 /// `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`.
1596 /// #[derive(Debug, Eq, PartialEq)]
1599 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1600 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1601 /// assert_eq!(x.transpose(), y);
1604 #[stable(feature = "transpose_result", since = "1.33.0")]
1605 #[rustc_const_unstable(feature = "const_result", issue = "82814")]
1606 pub const fn transpose(self) -> Option
<Result
<T
, E
>> {
1608 Ok(Some(x
)) => Some(Ok(x
)),
1610 Err(e
) => Some(Err(e
)),
1615 impl<T
, E
> Result
<Result
<T
, E
>, E
> {
1616 /// Converts from `Result<Result<T, E>, E>` to `Result<T, E>`
1621 /// #![feature(result_flattening)]
1622 /// let x: Result<Result<&'static str, u32>, u32> = Ok(Ok("hello"));
1623 /// assert_eq!(Ok("hello"), x.flatten());
1625 /// let x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));
1626 /// assert_eq!(Err(6), x.flatten());
1628 /// let x: Result<Result<&'static str, u32>, u32> = Err(6);
1629 /// assert_eq!(Err(6), x.flatten());
1632 /// Flattening only removes one level of nesting at a time:
1635 /// #![feature(result_flattening)]
1636 /// let x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok("hello")));
1637 /// assert_eq!(Ok(Ok("hello")), x.flatten());
1638 /// assert_eq!(Ok("hello"), x.flatten().flatten());
1641 #[unstable(feature = "result_flattening", issue = "70142")]
1642 pub fn flatten(self) -> Result
<T
, E
> {
1643 self.and_then(convert
::identity
)
1647 // This is a separate function to reduce the code size of the methods
1648 #[cfg(not(feature = "panic_immediate_abort"))]
1652 fn unwrap_failed(msg
: &str, error
: &dyn fmt
::Debug
) -> ! {
1653 panic
!("{msg}: {error:?}")
1656 // This is a separate function to avoid constructing a `dyn Debug`
1657 // that gets immediately thrown away, since vtables don't get cleaned up
1658 // by dead code elimination if a trait object is constructed even if it goes
1660 #[cfg(feature = "panic_immediate_abort")]
1664 fn unwrap_failed
<T
>(_msg
: &str, _error
: &T
) -> ! {
1668 /////////////////////////////////////////////////////////////////////////////
1669 // Trait implementations
1670 /////////////////////////////////////////////////////////////////////////////
1672 #[stable(feature = "rust1", since = "1.0.0")]
1673 impl<T
, E
> Clone
for Result
<T
, E
>
1679 fn clone(&self) -> Self {
1681 Ok(x
) => Ok(x
.clone()),
1682 Err(x
) => Err(x
.clone()),
1687 fn clone_from(&mut self, source
: &Self) {
1688 match (self, source
) {
1689 (Ok(to
), Ok(from
)) => to
.clone_from(from
),
1690 (Err(to
), Err(from
)) => to
.clone_from(from
),
1691 (to
, from
) => *to
= from
.clone(),
1696 #[stable(feature = "rust1", since = "1.0.0")]
1697 impl<T
, E
> IntoIterator
for Result
<T
, E
> {
1699 type IntoIter
= IntoIter
<T
>;
1701 /// Returns a consuming iterator over the possibly contained value.
1703 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
1708 /// let x: Result<u32, &str> = Ok(5);
1709 /// let v: Vec<u32> = x.into_iter().collect();
1710 /// assert_eq!(v, [5]);
1712 /// let x: Result<u32, &str> = Err("nothing!");
1713 /// let v: Vec<u32> = x.into_iter().collect();
1714 /// assert_eq!(v, []);
1717 fn into_iter(self) -> IntoIter
<T
> {
1718 IntoIter { inner: self.ok() }
1722 #[stable(since = "1.4.0", feature = "result_iter")]
1723 impl<'a
, T
, E
> IntoIterator
for &'a Result
<T
, E
> {
1725 type IntoIter
= Iter
<'a
, T
>;
1727 fn into_iter(self) -> Iter
<'a
, T
> {
1732 #[stable(since = "1.4.0", feature = "result_iter")]
1733 impl<'a
, T
, E
> IntoIterator
for &'a
mut Result
<T
, E
> {
1734 type Item
= &'a
mut T
;
1735 type IntoIter
= IterMut
<'a
, T
>;
1737 fn into_iter(self) -> IterMut
<'a
, T
> {
1742 /////////////////////////////////////////////////////////////////////////////
1743 // The Result Iterators
1744 /////////////////////////////////////////////////////////////////////////////
1746 /// An iterator over a reference to the [`Ok`] variant of a [`Result`].
1748 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1750 /// Created by [`Result::iter`].
1752 #[stable(feature = "rust1", since = "1.0.0")]
1753 pub struct Iter
<'a
, T
: 'a
> {
1754 inner
: Option
<&'a T
>,
1757 #[stable(feature = "rust1", since = "1.0.0")]
1758 impl<'a
, T
> Iterator
for Iter
<'a
, T
> {
1762 fn next(&mut self) -> Option
<&'a T
> {
1766 fn size_hint(&self) -> (usize, Option
<usize>) {
1767 let n
= if self.inner
.is_some() { 1 }
else { 0 }
;
1772 #[stable(feature = "rust1", since = "1.0.0")]
1773 impl<'a
, T
> DoubleEndedIterator
for Iter
<'a
, T
> {
1775 fn next_back(&mut self) -> Option
<&'a T
> {
1780 #[stable(feature = "rust1", since = "1.0.0")]
1781 impl<T
> ExactSizeIterator
for Iter
<'_
, T
> {}
1783 #[stable(feature = "fused", since = "1.26.0")]
1784 impl<T
> FusedIterator
for Iter
<'_
, T
> {}
1786 #[unstable(feature = "trusted_len", issue = "37572")]
1787 unsafe impl<A
> TrustedLen
for Iter
<'_
, A
> {}
1789 #[stable(feature = "rust1", since = "1.0.0")]
1790 impl<T
> Clone
for Iter
<'_
, T
> {
1792 fn clone(&self) -> Self {
1793 Iter { inner: self.inner }
1797 /// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
1799 /// Created by [`Result::iter_mut`].
1801 #[stable(feature = "rust1", since = "1.0.0")]
1802 pub struct IterMut
<'a
, T
: 'a
> {
1803 inner
: Option
<&'a
mut T
>,
1806 #[stable(feature = "rust1", since = "1.0.0")]
1807 impl<'a
, T
> Iterator
for IterMut
<'a
, T
> {
1808 type Item
= &'a
mut T
;
1811 fn next(&mut self) -> Option
<&'a
mut T
> {
1815 fn size_hint(&self) -> (usize, Option
<usize>) {
1816 let n
= if self.inner
.is_some() { 1 }
else { 0 }
;
1821 #[stable(feature = "rust1", since = "1.0.0")]
1822 impl<'a
, T
> DoubleEndedIterator
for IterMut
<'a
, T
> {
1824 fn next_back(&mut self) -> Option
<&'a
mut T
> {
1829 #[stable(feature = "rust1", since = "1.0.0")]
1830 impl<T
> ExactSizeIterator
for IterMut
<'_
, T
> {}
1832 #[stable(feature = "fused", since = "1.26.0")]
1833 impl<T
> FusedIterator
for IterMut
<'_
, T
> {}
1835 #[unstable(feature = "trusted_len", issue = "37572")]
1836 unsafe impl<A
> TrustedLen
for IterMut
<'_
, A
> {}
1838 /// An iterator over the value in a [`Ok`] variant of a [`Result`].
1840 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1842 /// This struct is created by the [`into_iter`] method on
1843 /// [`Result`] (provided by the [`IntoIterator`] trait).
1845 /// [`into_iter`]: IntoIterator::into_iter
1846 #[derive(Clone, Debug)]
1847 #[stable(feature = "rust1", since = "1.0.0")]
1848 pub struct IntoIter
<T
> {
1852 #[stable(feature = "rust1", since = "1.0.0")]
1853 impl<T
> Iterator
for IntoIter
<T
> {
1857 fn next(&mut self) -> Option
<T
> {
1861 fn size_hint(&self) -> (usize, Option
<usize>) {
1862 let n
= if self.inner
.is_some() { 1 }
else { 0 }
;
1867 #[stable(feature = "rust1", since = "1.0.0")]
1868 impl<T
> DoubleEndedIterator
for IntoIter
<T
> {
1870 fn next_back(&mut self) -> Option
<T
> {
1875 #[stable(feature = "rust1", since = "1.0.0")]
1876 impl<T
> ExactSizeIterator
for IntoIter
<T
> {}
1878 #[stable(feature = "fused", since = "1.26.0")]
1879 impl<T
> FusedIterator
for IntoIter
<T
> {}
1881 #[unstable(feature = "trusted_len", issue = "37572")]
1882 unsafe impl<A
> TrustedLen
for IntoIter
<A
> {}
1884 /////////////////////////////////////////////////////////////////////////////
1886 /////////////////////////////////////////////////////////////////////////////
1888 #[stable(feature = "rust1", since = "1.0.0")]
1889 impl<A
, E
, V
: FromIterator
<A
>> FromIterator
<Result
<A
, E
>> for Result
<V
, E
> {
1890 /// Takes each element in the `Iterator`: if it is an `Err`, no further
1891 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
1892 /// container with the values of each `Result` is returned.
1894 /// Here is an example which increments every integer in a vector,
1895 /// checking for overflow:
1898 /// let v = vec![1, 2];
1899 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1900 /// x.checked_add(1).ok_or("Overflow!")
1902 /// assert_eq!(res, Ok(vec![2, 3]));
1905 /// Here is another example that tries to subtract one from another list
1906 /// of integers, this time checking for underflow:
1909 /// let v = vec![1, 2, 0];
1910 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1911 /// x.checked_sub(1).ok_or("Underflow!")
1913 /// assert_eq!(res, Err("Underflow!"));
1916 /// Here is a variation on the previous example, showing that no
1917 /// further elements are taken from `iter` after the first `Err`.
1920 /// let v = vec![3, 2, 1, 10];
1921 /// let mut shared = 0;
1922 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {
1924 /// x.checked_sub(2).ok_or("Underflow!")
1926 /// assert_eq!(res, Err("Underflow!"));
1927 /// assert_eq!(shared, 6);
1930 /// Since the third element caused an underflow, no further elements were taken,
1931 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1933 fn from_iter
<I
: IntoIterator
<Item
= Result
<A
, E
>>>(iter
: I
) -> Result
<V
, E
> {
1934 iter
::try_process(iter
.into_iter(), |i
| i
.collect())
1938 #[unstable(feature = "try_trait_v2", issue = "84277")]
1939 impl<T
, E
> ops
::Try
for Result
<T
, E
> {
1941 type Residual
= Result
<convert
::Infallible
, E
>;
1944 fn from_output(output
: Self::Output
) -> Self {
1949 fn branch(self) -> ControlFlow
<Self::Residual
, Self::Output
> {
1951 Ok(v
) => ControlFlow
::Continue(v
),
1952 Err(e
) => ControlFlow
::Break(Err(e
)),
1957 #[unstable(feature = "try_trait_v2", issue = "84277")]
1958 impl<T
, E
, F
: From
<E
>> ops
::FromResidual
<Result
<convert
::Infallible
, E
>> for Result
<T
, F
> {
1961 fn from_residual(residual
: Result
<convert
::Infallible
, E
>) -> Self {
1963 Err(e
) => Err(From
::from(e
)),
1968 #[unstable(feature = "try_trait_v2_yeet", issue = "96374")]
1969 impl<T
, E
, F
: From
<E
>> ops
::FromResidual
<ops
::Yeet
<E
>> for Result
<T
, F
> {
1971 fn from_residual(ops
::Yeet(e
): ops
::Yeet
<E
>) -> Self {
1976 #[unstable(feature = "try_trait_v2_residual", issue = "91285")]
1977 impl<T
, E
> ops
::Residual
<T
> for Result
<convert
::Infallible
, E
> {
1978 type TryType
= Result
<T
, E
>;