]> git.lizzy.rs Git - rust.git/blob - library/core/src/result.rs
Rollup merge of #99716 - sourcelliu:iomut, r=Mark-Simulacrum
[rust.git] / library / core / src / result.rs
1 //! Error handling with the `Result` type.
2 //!
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.
7 //!
8 //! ```
9 //! # #[allow(dead_code)]
10 //! enum Result<T, E> {
11 //!    Ok(T),
12 //!    Err(E),
13 //! }
14 //! ```
15 //!
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).
19 //!
20 //! A simple function returning [`Result`] might be
21 //! defined and used like so:
22 //!
23 //! ```
24 //! #[derive(Debug)]
25 //! enum Version { Version1, Version2 }
26 //!
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"),
33 //!     }
34 //! }
35 //!
36 //! let version = parse_version(&[1, 2, 3, 4]);
37 //! match version {
38 //!     Ok(v) => println!("working with version: {v:?}"),
39 //!     Err(e) => println!("error parsing header: {e:?}"),
40 //! }
41 //! ```
42 //!
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.
46 //!
47 //! ```
48 //! let good_result: Result<i32, i32> = Ok(10);
49 //! let bad_result: Result<i32, i32> = Err(10);
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.
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);
58 //!
59 //! // Use `and_then` to continue the computation.
60 //! let good_result: Result<bool, i32> = good_result.and_then(|i| Ok(i == 11));
61 //!
62 //! // Use `or_else` to handle the error.
63 //! let bad_result: Result<i32, i32> = bad_result.or_else(|i| Ok(i + 20));
64 //!
65 //! // Consume the result and return the contents with `unwrap`.
66 //! let final_awesome_result = good_result.unwrap();
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
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
77 //! useful value.
78 //!
79 //! Consider the [`write_all`] method defined for I/O types
80 //! by the [`Write`] trait:
81 //!
82 //! ```
83 //! use std::io;
84 //!
85 //! trait Write {
86 //!     fn write_all(&mut self, bytes: &[u8]) -> Result<(), io::Error>;
87 //! }
88 //! ```
89 //!
90 //! *Note: The actual definition of [`Write`] uses [`io::Result`], which
91 //! is just a synonym for <code>[Result]<T, [io::Error]></code>.*
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 //!
97 //! ```no_run
98 //! # #![allow(unused_must_use)] // \o/
99 //! use std::fs::File;
100 //! use std::io::prelude::*;
101 //!
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");
106 //! ```
107 //!
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).
110 //!
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:
114 //!
115 //! ```no_run
116 //! use std::fs::File;
117 //! use std::io::prelude::*;
118 //!
119 //! let mut file = File::create("valuable_data.txt").unwrap();
120 //! file.write_all(b"important message").expect("failed to write message");
121 //! ```
122 //!
123 //! You might also simply assert success:
124 //!
125 //! ```no_run
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());
130 //! ```
131 //!
132 //! Or propagate the error up the call stack with [`?`]:
133 //!
134 //! ```
135 //! # use std::fs::File;
136 //! # use std::io::prelude::*;
137 //! # use std::io;
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")?;
142 //!     Ok(())
143 //! }
144 //! ```
145 //!
146 //! # The question mark operator, `?`
147 //!
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.
152 //!
153 //! It replaces this:
154 //!
155 //! ```
156 //! # #![allow(dead_code)]
157 //! use std::fs::File;
158 //! use std::io::prelude::*;
159 //! use std::io;
160 //!
161 //! struct Info {
162 //!     name: String,
163 //!     age: i32,
164 //!     rating: i32,
165 //! }
166 //!
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),
171 //!            Ok(f) => f,
172 //!     };
173 //!     if let Err(e) = file.write_all(format!("name: {}\n", info.name).as_bytes()) {
174 //!         return Err(e)
175 //!     }
176 //!     if let Err(e) = file.write_all(format!("age: {}\n", info.age).as_bytes()) {
177 //!         return Err(e)
178 //!     }
179 //!     if let Err(e) = file.write_all(format!("rating: {}\n", info.rating).as_bytes()) {
180 //!         return Err(e)
181 //!     }
182 //!     Ok(())
183 //! }
184 //! ```
185 //!
186 //! With this:
187 //!
188 //! ```
189 //! # #![allow(dead_code)]
190 //! use std::fs::File;
191 //! use std::io::prelude::*;
192 //! use std::io;
193 //!
194 //! struct Info {
195 //!     name: String,
196 //!     age: i32,
197 //!     rating: i32,
198 //! }
199 //!
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())?;
206 //!     Ok(())
207 //! }
208 //! ```
209 //!
210 //! *It's much nicer!*
211 //!
212 //! Ending the expression with [`?`] will result in the unwrapped
213 //! success ([`Ok`]) value, unless the result is [`Err`], in which case
214 //! [`Err`] is returned early from the enclosing function.
215 //!
216 //! [`?`] can only be used in functions that return [`Result`] because of the
217 //! early return of [`Err`] that it provides.
218 //!
219 //! [`expect`]: Result::expect
220 //! [`Write`]: ../../std/io/trait.Write.html "io::Write"
221 //! [`write_all`]: ../../std/io/trait.Write.html#method.write_all "io::Write::write_all"
222 //! [`io::Result`]: ../../std/io/type.Result.html "io::Result"
223 //! [`?`]: crate::ops::Try
224 //! [`Ok(T)`]: Ok
225 //! [`Err(E)`]: Err
226 //! [io::Error]: ../../std/io/struct.Error.html "io::Error"
227 //!
228 //! # Method overview
229 //!
230 //! In addition to working with pattern matching, [`Result`] provides a
231 //! wide variety of different methods.
232 //!
233 //! ## Querying the variant
234 //!
235 //! The [`is_ok`] and [`is_err`] methods return [`true`] if the [`Result`]
236 //! is [`Ok`] or [`Err`], respectively.
237 //!
238 //! [`is_err`]: Result::is_err
239 //! [`is_ok`]: Result::is_ok
240 //!
241 //! ## Adapters for working with references
242 //!
243 //! * [`as_ref`] converts from `&Result<T, E>` to `Result<&T, &E>`
244 //! * [`as_mut`] converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`
245 //! * [`as_deref`] converts from `&Result<T, E>` to `Result<&T::Target, &E>`
246 //! * [`as_deref_mut`] converts from `&mut Result<T, E>` to
247 //!   `Result<&mut T::Target, &mut E>`
248 //!
249 //! [`as_deref`]: Result::as_deref
250 //! [`as_deref_mut`]: Result::as_deref_mut
251 //! [`as_mut`]: Result::as_mut
252 //! [`as_ref`]: Result::as_ref
253 //!
254 //! ## Extracting contained values
255 //!
256 //! These methods extract the contained value in a [`Result<T, E>`] when it
257 //! is the [`Ok`] variant. If the [`Result`] is [`Err`]:
258 //!
259 //! * [`expect`] panics with a provided custom message
260 //! * [`unwrap`] panics with a generic message
261 //! * [`unwrap_or`] returns the provided default value
262 //! * [`unwrap_or_default`] returns the default value of the type `T`
263 //!   (which must implement the [`Default`] trait)
264 //! * [`unwrap_or_else`] returns the result of evaluating the provided
265 //!   function
266 //!
267 //! The panicking methods [`expect`] and [`unwrap`] require `E` to
268 //! implement the [`Debug`] trait.
269 //!
270 //! [`Debug`]: crate::fmt::Debug
271 //! [`expect`]: Result::expect
272 //! [`unwrap`]: Result::unwrap
273 //! [`unwrap_or`]: Result::unwrap_or
274 //! [`unwrap_or_default`]: Result::unwrap_or_default
275 //! [`unwrap_or_else`]: Result::unwrap_or_else
276 //!
277 //! These methods extract the contained value in a [`Result<T, E>`] when it
278 //! is the [`Err`] variant. They require `T` to implement the [`Debug`]
279 //! trait. If the [`Result`] is [`Ok`]:
280 //!
281 //! * [`expect_err`] panics with a provided custom message
282 //! * [`unwrap_err`] panics with a generic message
283 //!
284 //! [`Debug`]: crate::fmt::Debug
285 //! [`expect_err`]: Result::expect_err
286 //! [`unwrap_err`]: Result::unwrap_err
287 //!
288 //! ## Transforming contained values
289 //!
290 //! These methods transform [`Result`] to [`Option`]:
291 //!
292 //! * [`err`][Result::err] transforms [`Result<T, E>`] into [`Option<E>`],
293 //!   mapping [`Err(e)`] to [`Some(e)`] and [`Ok(v)`] to [`None`]
294 //! * [`ok`][Result::ok] transforms [`Result<T, E>`] into [`Option<T>`],
295 //!   mapping [`Ok(v)`] to [`Some(v)`] and [`Err(e)`] to [`None`]
296 //! * [`transpose`] transposes a [`Result`] of an [`Option`] into an
297 //!   [`Option`] of a [`Result`]
298 //!
299 // Do NOT add link reference definitions for `err` or `ok`, because they
300 // will generate numerous incorrect URLs for `Err` and `Ok` elsewhere, due
301 // to case folding.
302 //!
303 //! [`Err(e)`]: Err
304 //! [`Ok(v)`]: Ok
305 //! [`Some(e)`]: Option::Some
306 //! [`Some(v)`]: Option::Some
307 //! [`transpose`]: Result::transpose
308 //!
309 //! This method transforms the contained value of the [`Ok`] variant:
310 //!
311 //! * [`map`] transforms [`Result<T, E>`] into [`Result<U, E>`] by applying
312 //!   the provided function to the contained value of [`Ok`] and leaving
313 //!   [`Err`] values unchanged
314 //!
315 //! [`map`]: Result::map
316 //!
317 //! This method transforms the contained value of the [`Err`] variant:
318 //!
319 //! * [`map_err`] transforms [`Result<T, E>`] into [`Result<T, F>`] by
320 //!   applying the provided function to the contained value of [`Err`] and
321 //!   leaving [`Ok`] values unchanged
322 //!
323 //! [`map_err`]: Result::map_err
324 //!
325 //! These methods transform a [`Result<T, E>`] into a value of a possibly
326 //! different type `U`:
327 //!
328 //! * [`map_or`] applies the provided function to the contained value of
329 //!   [`Ok`], or returns the provided default value if the [`Result`] is
330 //!   [`Err`]
331 //! * [`map_or_else`] applies the provided function to the contained value
332 //!   of [`Ok`], or applies the provided default fallback function to the
333 //!   contained value of [`Err`]
334 //!
335 //! [`map_or`]: Result::map_or
336 //! [`map_or_else`]: Result::map_or_else
337 //!
338 //! ## Boolean operators
339 //!
340 //! These methods treat the [`Result`] as a boolean value, where [`Ok`]
341 //! acts like [`true`] and [`Err`] acts like [`false`]. There are two
342 //! categories of these methods: ones that take a [`Result`] as input, and
343 //! ones that take a function as input (to be lazily evaluated).
344 //!
345 //! The [`and`] and [`or`] methods take another [`Result`] as input, and
346 //! produce a [`Result`] as output. The [`and`] method can produce a
347 //! [`Result<U, E>`] value having a different inner type `U` than
348 //! [`Result<T, E>`]. The [`or`] method can produce a [`Result<T, F>`]
349 //! value having a different error type `F` than [`Result<T, E>`].
350 //!
351 //! | method  | self     | input     | output   |
352 //! |---------|----------|-----------|----------|
353 //! | [`and`] | `Err(e)` | (ignored) | `Err(e)` |
354 //! | [`and`] | `Ok(x)`  | `Err(d)`  | `Err(d)` |
355 //! | [`and`] | `Ok(x)`  | `Ok(y)`   | `Ok(y)`  |
356 //! | [`or`]  | `Err(e)` | `Err(d)`  | `Err(d)` |
357 //! | [`or`]  | `Err(e)` | `Ok(y)`   | `Ok(y)`  |
358 //! | [`or`]  | `Ok(x)`  | (ignored) | `Ok(x)`  |
359 //!
360 //! [`and`]: Result::and
361 //! [`or`]: Result::or
362 //!
363 //! The [`and_then`] and [`or_else`] methods take a function as input, and
364 //! only evaluate the function when they need to produce a new value. The
365 //! [`and_then`] method can produce a [`Result<U, E>`] value having a
366 //! different inner type `U` than [`Result<T, E>`]. The [`or_else`] method
367 //! can produce a [`Result<T, F>`] value having a different error type `F`
368 //! than [`Result<T, E>`].
369 //!
370 //! | method       | self     | function input | function result | output   |
371 //! |--------------|----------|----------------|-----------------|----------|
372 //! | [`and_then`] | `Err(e)` | (not provided) | (not evaluated) | `Err(e)` |
373 //! | [`and_then`] | `Ok(x)`  | `x`            | `Err(d)`        | `Err(d)` |
374 //! | [`and_then`] | `Ok(x)`  | `x`            | `Ok(y)`         | `Ok(y)`  |
375 //! | [`or_else`]  | `Err(e)` | `e`            | `Err(d)`        | `Err(d)` |
376 //! | [`or_else`]  | `Err(e)` | `e`            | `Ok(y)`         | `Ok(y)`  |
377 //! | [`or_else`]  | `Ok(x)`  | (not provided) | (not evaluated) | `Ok(x)`  |
378 //!
379 //! [`and_then`]: Result::and_then
380 //! [`or_else`]: Result::or_else
381 //!
382 //! ## Comparison operators
383 //!
384 //! If `T` and `E` both implement [`PartialOrd`] then [`Result<T, E>`] will
385 //! derive its [`PartialOrd`] implementation.  With this order, an [`Ok`]
386 //! compares as less than any [`Err`], while two [`Ok`] or two [`Err`]
387 //! compare as their contained values would in `T` or `E` respectively.  If `T`
388 //! and `E` both also implement [`Ord`], then so does [`Result<T, E>`].
389 //!
390 //! ```
391 //! assert!(Ok(1) < Err(0));
392 //! let x: Result<i32, ()> = Ok(0);
393 //! let y = Ok(1);
394 //! assert!(x < y);
395 //! let x: Result<(), i32> = Err(0);
396 //! let y = Err(1);
397 //! assert!(x < y);
398 //! ```
399 //!
400 //! ## Iterating over `Result`
401 //!
402 //! A [`Result`] can be iterated over. This can be helpful if you need an
403 //! iterator that is conditionally empty. The iterator will either produce
404 //! a single value (when the [`Result`] is [`Ok`]), or produce no values
405 //! (when the [`Result`] is [`Err`]). For example, [`into_iter`] acts like
406 //! [`once(v)`] if the [`Result`] is [`Ok(v)`], and like [`empty()`] if the
407 //! [`Result`] is [`Err`].
408 //!
409 //! [`Ok(v)`]: Ok
410 //! [`empty()`]: crate::iter::empty
411 //! [`once(v)`]: crate::iter::once
412 //!
413 //! Iterators over [`Result<T, E>`] come in three types:
414 //!
415 //! * [`into_iter`] consumes the [`Result`] and produces the contained
416 //!   value
417 //! * [`iter`] produces an immutable reference of type `&T` to the
418 //!   contained value
419 //! * [`iter_mut`] produces a mutable reference of type `&mut T` to the
420 //!   contained value
421 //!
422 //! See [Iterating over `Option`] for examples of how this can be useful.
423 //!
424 //! [Iterating over `Option`]: crate::option#iterating-over-option
425 //! [`into_iter`]: Result::into_iter
426 //! [`iter`]: Result::iter
427 //! [`iter_mut`]: Result::iter_mut
428 //!
429 //! You might want to use an iterator chain to do multiple instances of an
430 //! operation that can fail, but would like to ignore failures while
431 //! continuing to process the successful results. In this example, we take
432 //! advantage of the iterable nature of [`Result`] to select only the
433 //! [`Ok`] values using [`flatten`][Iterator::flatten].
434 //!
435 //! ```
436 //! # use std::str::FromStr;
437 //! let mut results = vec![];
438 //! let mut errs = vec![];
439 //! let nums: Vec<_> = ["17", "not a number", "99", "-27", "768"]
440 //!    .into_iter()
441 //!    .map(u8::from_str)
442 //!    // Save clones of the raw `Result` values to inspect
443 //!    .inspect(|x| results.push(x.clone()))
444 //!    // Challenge: explain how this captures only the `Err` values
445 //!    .inspect(|x| errs.extend(x.clone().err()))
446 //!    .flatten()
447 //!    .collect();
448 //! assert_eq!(errs.len(), 3);
449 //! assert_eq!(nums, [17, 99]);
450 //! println!("results {results:?}");
451 //! println!("errs {errs:?}");
452 //! println!("nums {nums:?}");
453 //! ```
454 //!
455 //! ## Collecting into `Result`
456 //!
457 //! [`Result`] implements the [`FromIterator`][impl-FromIterator] trait,
458 //! which allows an iterator over [`Result`] values to be collected into a
459 //! [`Result`] of a collection of each contained value of the original
460 //! [`Result`] values, or [`Err`] if any of the elements was [`Err`].
461 //!
462 //! [impl-FromIterator]: Result#impl-FromIterator%3CResult%3CA%2C%20E%3E%3E-for-Result%3CV%2C%20E%3E
463 //!
464 //! ```
465 //! let v = [Ok(2), Ok(4), Err("err!"), Ok(8)];
466 //! let res: Result<Vec<_>, &str> = v.into_iter().collect();
467 //! assert_eq!(res, Err("err!"));
468 //! let v = [Ok(2), Ok(4), Ok(8)];
469 //! let res: Result<Vec<_>, &str> = v.into_iter().collect();
470 //! assert_eq!(res, Ok(vec![2, 4, 8]));
471 //! ```
472 //!
473 //! [`Result`] also implements the [`Product`][impl-Product] and
474 //! [`Sum`][impl-Sum] traits, allowing an iterator over [`Result`] values
475 //! to provide the [`product`][Iterator::product] and
476 //! [`sum`][Iterator::sum] methods.
477 //!
478 //! [impl-Product]: Result#impl-Product%3CResult%3CU%2C%20E%3E%3E-for-Result%3CT%2C%20E%3E
479 //! [impl-Sum]: Result#impl-Sum%3CResult%3CU%2C%20E%3E%3E-for-Result%3CT%2C%20E%3E
480 //!
481 //! ```
482 //! let v = [Err("error!"), Ok(1), Ok(2), Ok(3), Err("foo")];
483 //! let res: Result<i32, &str> = v.into_iter().sum();
484 //! assert_eq!(res, Err("error!"));
485 //! let v = [Ok(1), Ok(2), Ok(21)];
486 //! let res: Result<i32, &str> = v.into_iter().product();
487 //! assert_eq!(res, Ok(42));
488 //! ```
489
490 #![stable(feature = "rust1", since = "1.0.0")]
491
492 use crate::iter::{self, FromIterator, FusedIterator, TrustedLen};
493 use crate::marker::Destruct;
494 use crate::ops::{self, ControlFlow, Deref, DerefMut};
495 use crate::{convert, fmt, hint};
496
497 /// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]).
498 ///
499 /// See the [module documentation](self) for details.
500 #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
501 #[must_use = "this `Result` may be an `Err` variant, which should be handled"]
502 #[rustc_diagnostic_item = "Result"]
503 #[stable(feature = "rust1", since = "1.0.0")]
504 pub enum Result<T, E> {
505     /// Contains the success value
506     #[lang = "Ok"]
507     #[stable(feature = "rust1", since = "1.0.0")]
508     Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
509
510     /// Contains the error value
511     #[lang = "Err"]
512     #[stable(feature = "rust1", since = "1.0.0")]
513     Err(#[stable(feature = "rust1", since = "1.0.0")] E),
514 }
515
516 /////////////////////////////////////////////////////////////////////////////
517 // Type implementation
518 /////////////////////////////////////////////////////////////////////////////
519
520 impl<T, E> Result<T, E> {
521     /////////////////////////////////////////////////////////////////////////
522     // Querying the contained values
523     /////////////////////////////////////////////////////////////////////////
524
525     /// Returns `true` if the result is [`Ok`].
526     ///
527     /// # Examples
528     ///
529     /// Basic usage:
530     ///
531     /// ```
532     /// let x: Result<i32, &str> = Ok(-3);
533     /// assert_eq!(x.is_ok(), true);
534     ///
535     /// let x: Result<i32, &str> = Err("Some error message");
536     /// assert_eq!(x.is_ok(), false);
537     /// ```
538     #[must_use = "if you intended to assert that this is ok, consider `.unwrap()` instead"]
539     #[rustc_const_stable(feature = "const_result_basics", since = "1.48.0")]
540     #[inline]
541     #[stable(feature = "rust1", since = "1.0.0")]
542     pub const fn is_ok(&self) -> bool {
543         matches!(*self, Ok(_))
544     }
545
546     /// Returns `true` if the result is [`Ok`] and the value inside of it matches a predicate.
547     ///
548     /// # Examples
549     ///
550     /// ```
551     /// #![feature(is_some_with)]
552     ///
553     /// let x: Result<u32, &str> = Ok(2);
554     /// assert_eq!(x.is_ok_and(|&x| x > 1), true);
555     ///
556     /// let x: Result<u32, &str> = Ok(0);
557     /// assert_eq!(x.is_ok_and(|&x| x > 1), false);
558     ///
559     /// let x: Result<u32, &str> = Err("hey");
560     /// assert_eq!(x.is_ok_and(|&x| x > 1), false);
561     /// ```
562     #[must_use]
563     #[inline]
564     #[unstable(feature = "is_some_with", issue = "93050")]
565     pub fn is_ok_and(&self, f: impl FnOnce(&T) -> bool) -> bool {
566         matches!(self, Ok(x) if f(x))
567     }
568
569     /// Returns `true` if the result is [`Err`].
570     ///
571     /// # Examples
572     ///
573     /// Basic usage:
574     ///
575     /// ```
576     /// let x: Result<i32, &str> = Ok(-3);
577     /// assert_eq!(x.is_err(), false);
578     ///
579     /// let x: Result<i32, &str> = Err("Some error message");
580     /// assert_eq!(x.is_err(), true);
581     /// ```
582     #[must_use = "if you intended to assert that this is err, consider `.unwrap_err()` instead"]
583     #[rustc_const_stable(feature = "const_result_basics", since = "1.48.0")]
584     #[inline]
585     #[stable(feature = "rust1", since = "1.0.0")]
586     pub const fn is_err(&self) -> bool {
587         !self.is_ok()
588     }
589
590     /// Returns `true` if the result is [`Err`] and the value inside of it matches a predicate.
591     ///
592     /// # Examples
593     ///
594     /// ```
595     /// #![feature(is_some_with)]
596     /// use std::io::{Error, ErrorKind};
597     ///
598     /// let x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, "!"));
599     /// assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);
600     ///
601     /// let x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, "!"));
602     /// assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
603     ///
604     /// let x: Result<u32, Error> = Ok(123);
605     /// assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
606     /// ```
607     #[must_use]
608     #[inline]
609     #[unstable(feature = "is_some_with", issue = "93050")]
610     pub fn is_err_and(&self, f: impl FnOnce(&E) -> bool) -> bool {
611         matches!(self, Err(x) if f(x))
612     }
613
614     /////////////////////////////////////////////////////////////////////////
615     // Adapter for each variant
616     /////////////////////////////////////////////////////////////////////////
617
618     /// Converts from `Result<T, E>` to [`Option<T>`].
619     ///
620     /// Converts `self` into an [`Option<T>`], consuming `self`,
621     /// and discarding the error, if any.
622     ///
623     /// # Examples
624     ///
625     /// Basic usage:
626     ///
627     /// ```
628     /// let x: Result<u32, &str> = Ok(2);
629     /// assert_eq!(x.ok(), Some(2));
630     ///
631     /// let x: Result<u32, &str> = Err("Nothing here");
632     /// assert_eq!(x.ok(), None);
633     /// ```
634     #[inline]
635     #[stable(feature = "rust1", since = "1.0.0")]
636     #[rustc_const_unstable(feature = "const_result_drop", issue = "92384")]
637     pub const fn ok(self) -> Option<T>
638     where
639         E: ~const Destruct,
640     {
641         match self {
642             Ok(x) => Some(x),
643             // FIXME: ~const Drop doesn't quite work right yet
644             #[allow(unused_variables)]
645             Err(x) => None,
646         }
647     }
648
649     /// Converts from `Result<T, E>` to [`Option<E>`].
650     ///
651     /// Converts `self` into an [`Option<E>`], consuming `self`,
652     /// and discarding the success value, if any.
653     ///
654     /// # Examples
655     ///
656     /// Basic usage:
657     ///
658     /// ```
659     /// let x: Result<u32, &str> = Ok(2);
660     /// assert_eq!(x.err(), None);
661     ///
662     /// let x: Result<u32, &str> = Err("Nothing here");
663     /// assert_eq!(x.err(), Some("Nothing here"));
664     /// ```
665     #[inline]
666     #[stable(feature = "rust1", since = "1.0.0")]
667     #[rustc_const_unstable(feature = "const_result_drop", issue = "92384")]
668     pub const fn err(self) -> Option<E>
669     where
670         T: ~const Destruct,
671     {
672         match self {
673             // FIXME: ~const Drop doesn't quite work right yet
674             #[allow(unused_variables)]
675             Ok(x) => None,
676             Err(x) => Some(x),
677         }
678     }
679
680     /////////////////////////////////////////////////////////////////////////
681     // Adapter for working with references
682     /////////////////////////////////////////////////////////////////////////
683
684     /// Converts from `&Result<T, E>` to `Result<&T, &E>`.
685     ///
686     /// Produces a new `Result`, containing a reference
687     /// into the original, leaving the original in place.
688     ///
689     /// # Examples
690     ///
691     /// Basic usage:
692     ///
693     /// ```
694     /// let x: Result<u32, &str> = Ok(2);
695     /// assert_eq!(x.as_ref(), Ok(&2));
696     ///
697     /// let x: Result<u32, &str> = Err("Error");
698     /// assert_eq!(x.as_ref(), Err(&"Error"));
699     /// ```
700     #[inline]
701     #[rustc_const_stable(feature = "const_result_basics", since = "1.48.0")]
702     #[stable(feature = "rust1", since = "1.0.0")]
703     pub const fn as_ref(&self) -> Result<&T, &E> {
704         match *self {
705             Ok(ref x) => Ok(x),
706             Err(ref x) => Err(x),
707         }
708     }
709
710     /// Converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`.
711     ///
712     /// # Examples
713     ///
714     /// Basic usage:
715     ///
716     /// ```
717     /// fn mutate(r: &mut Result<i32, i32>) {
718     ///     match r.as_mut() {
719     ///         Ok(v) => *v = 42,
720     ///         Err(e) => *e = 0,
721     ///     }
722     /// }
723     ///
724     /// let mut x: Result<i32, i32> = Ok(2);
725     /// mutate(&mut x);
726     /// assert_eq!(x.unwrap(), 42);
727     ///
728     /// let mut x: Result<i32, i32> = Err(13);
729     /// mutate(&mut x);
730     /// assert_eq!(x.unwrap_err(), 0);
731     /// ```
732     #[inline]
733     #[stable(feature = "rust1", since = "1.0.0")]
734     #[rustc_const_unstable(feature = "const_result", issue = "82814")]
735     pub const fn as_mut(&mut self) -> Result<&mut T, &mut E> {
736         match *self {
737             Ok(ref mut x) => Ok(x),
738             Err(ref mut x) => Err(x),
739         }
740     }
741
742     /////////////////////////////////////////////////////////////////////////
743     // Transforming contained values
744     /////////////////////////////////////////////////////////////////////////
745
746     /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
747     /// contained [`Ok`] value, leaving an [`Err`] value untouched.
748     ///
749     /// This function can be used to compose the results of two functions.
750     ///
751     /// # Examples
752     ///
753     /// Print the numbers on each line of a string multiplied by two.
754     ///
755     /// ```
756     /// let line = "1\n2\n3\n4\n";
757     ///
758     /// for num in line.lines() {
759     ///     match num.parse::<i32>().map(|i| i * 2) {
760     ///         Ok(n) => println!("{n}"),
761     ///         Err(..) => {}
762     ///     }
763     /// }
764     /// ```
765     #[inline]
766     #[stable(feature = "rust1", since = "1.0.0")]
767     pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U, E> {
768         match self {
769             Ok(t) => Ok(op(t)),
770             Err(e) => Err(e),
771         }
772     }
773
774     /// Returns the provided default (if [`Err`]), or
775     /// applies a function to the contained value (if [`Ok`]),
776     ///
777     /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
778     /// the result of a function call, it is recommended to use [`map_or_else`],
779     /// which is lazily evaluated.
780     ///
781     /// [`map_or_else`]: Result::map_or_else
782     ///
783     /// # Examples
784     ///
785     /// ```
786     /// let x: Result<_, &str> = Ok("foo");
787     /// assert_eq!(x.map_or(42, |v| v.len()), 3);
788     ///
789     /// let x: Result<&str, _> = Err("bar");
790     /// assert_eq!(x.map_or(42, |v| v.len()), 42);
791     /// ```
792     #[inline]
793     #[stable(feature = "result_map_or", since = "1.41.0")]
794     pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
795         match self {
796             Ok(t) => f(t),
797             Err(_) => default,
798         }
799     }
800
801     /// Maps a `Result<T, E>` to `U` by applying fallback function `default` to
802     /// a contained [`Err`] value, or function `f` to a contained [`Ok`] value.
803     ///
804     /// This function can be used to unpack a successful result
805     /// while handling an error.
806     ///
807     ///
808     /// # Examples
809     ///
810     /// Basic usage:
811     ///
812     /// ```
813     /// let k = 21;
814     ///
815     /// let x : Result<_, &str> = Ok("foo");
816     /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);
817     ///
818     /// let x : Result<&str, _> = Err("bar");
819     /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
820     /// ```
821     #[inline]
822     #[stable(feature = "result_map_or_else", since = "1.41.0")]
823     pub fn map_or_else<U, D: FnOnce(E) -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
824         match self {
825             Ok(t) => f(t),
826             Err(e) => default(e),
827         }
828     }
829
830     /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
831     /// contained [`Err`] value, leaving an [`Ok`] value untouched.
832     ///
833     /// This function can be used to pass through a successful result while handling
834     /// an error.
835     ///
836     ///
837     /// # Examples
838     ///
839     /// Basic usage:
840     ///
841     /// ```
842     /// fn stringify(x: u32) -> String { format!("error code: {x}") }
843     ///
844     /// let x: Result<u32, u32> = Ok(2);
845     /// assert_eq!(x.map_err(stringify), Ok(2));
846     ///
847     /// let x: Result<u32, u32> = Err(13);
848     /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
849     /// ```
850     #[inline]
851     #[stable(feature = "rust1", since = "1.0.0")]
852     pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T, F> {
853         match self {
854             Ok(t) => Ok(t),
855             Err(e) => Err(op(e)),
856         }
857     }
858
859     /// Calls the provided closure with a reference to the contained value (if [`Ok`]).
860     ///
861     /// # Examples
862     ///
863     /// ```
864     /// #![feature(result_option_inspect)]
865     ///
866     /// let x: u8 = "4"
867     ///     .parse::<u8>()
868     ///     .inspect(|x| println!("original: {x}"))
869     ///     .map(|x| x.pow(3))
870     ///     .expect("failed to parse number");
871     /// ```
872     #[inline]
873     #[unstable(feature = "result_option_inspect", issue = "91345")]
874     pub fn inspect<F: FnOnce(&T)>(self, f: F) -> Self {
875         if let Ok(ref t) = self {
876             f(t);
877         }
878
879         self
880     }
881
882     /// Calls the provided closure with a reference to the contained error (if [`Err`]).
883     ///
884     /// # Examples
885     ///
886     /// ```
887     /// #![feature(result_option_inspect)]
888     ///
889     /// use std::{fs, io};
890     ///
891     /// fn read() -> io::Result<String> {
892     ///     fs::read_to_string("address.txt")
893     ///         .inspect_err(|e| eprintln!("failed to read file: {e}"))
894     /// }
895     /// ```
896     #[inline]
897     #[unstable(feature = "result_option_inspect", issue = "91345")]
898     pub fn inspect_err<F: FnOnce(&E)>(self, f: F) -> Self {
899         if let Err(ref e) = self {
900             f(e);
901         }
902
903         self
904     }
905
906     /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&<T as Deref>::Target, &E>`.
907     ///
908     /// Coerces the [`Ok`] variant of the original [`Result`] via [`Deref`](crate::ops::Deref)
909     /// and returns the new [`Result`].
910     ///
911     /// # Examples
912     ///
913     /// ```
914     /// let x: Result<String, u32> = Ok("hello".to_string());
915     /// let y: Result<&str, &u32> = Ok("hello");
916     /// assert_eq!(x.as_deref(), y);
917     ///
918     /// let x: Result<String, u32> = Err(42);
919     /// let y: Result<&str, &u32> = Err(&42);
920     /// assert_eq!(x.as_deref(), y);
921     /// ```
922     #[stable(feature = "inner_deref", since = "1.47.0")]
923     pub fn as_deref(&self) -> Result<&T::Target, &E>
924     where
925         T: Deref,
926     {
927         self.as_ref().map(|t| t.deref())
928     }
929
930     /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut <T as DerefMut>::Target, &mut E>`.
931     ///
932     /// Coerces the [`Ok`] variant of the original [`Result`] via [`DerefMut`](crate::ops::DerefMut)
933     /// and returns the new [`Result`].
934     ///
935     /// # Examples
936     ///
937     /// ```
938     /// let mut s = "HELLO".to_string();
939     /// let mut x: Result<String, u32> = Ok("hello".to_string());
940     /// let y: Result<&mut str, &mut u32> = Ok(&mut s);
941     /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
942     ///
943     /// let mut i = 42;
944     /// let mut x: Result<String, u32> = Err(42);
945     /// let y: Result<&mut str, &mut u32> = Err(&mut i);
946     /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
947     /// ```
948     #[stable(feature = "inner_deref", since = "1.47.0")]
949     pub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E>
950     where
951         T: DerefMut,
952     {
953         self.as_mut().map(|t| t.deref_mut())
954     }
955
956     /////////////////////////////////////////////////////////////////////////
957     // Iterator constructors
958     /////////////////////////////////////////////////////////////////////////
959
960     /// Returns an iterator over the possibly contained value.
961     ///
962     /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
963     ///
964     /// # Examples
965     ///
966     /// Basic usage:
967     ///
968     /// ```
969     /// let x: Result<u32, &str> = Ok(7);
970     /// assert_eq!(x.iter().next(), Some(&7));
971     ///
972     /// let x: Result<u32, &str> = Err("nothing!");
973     /// assert_eq!(x.iter().next(), None);
974     /// ```
975     #[inline]
976     #[stable(feature = "rust1", since = "1.0.0")]
977     pub fn iter(&self) -> Iter<'_, T> {
978         Iter { inner: self.as_ref().ok() }
979     }
980
981     /// Returns a mutable iterator over the possibly contained value.
982     ///
983     /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
984     ///
985     /// # Examples
986     ///
987     /// Basic usage:
988     ///
989     /// ```
990     /// let mut x: Result<u32, &str> = Ok(7);
991     /// match x.iter_mut().next() {
992     ///     Some(v) => *v = 40,
993     ///     None => {},
994     /// }
995     /// assert_eq!(x, Ok(40));
996     ///
997     /// let mut x: Result<u32, &str> = Err("nothing!");
998     /// assert_eq!(x.iter_mut().next(), None);
999     /// ```
1000     #[inline]
1001     #[stable(feature = "rust1", since = "1.0.0")]
1002     pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1003         IterMut { inner: self.as_mut().ok() }
1004     }
1005
1006     /////////////////////////////////////////////////////////////////////////
1007     // Extract a value
1008     /////////////////////////////////////////////////////////////////////////
1009
1010     /// Returns the contained [`Ok`] value, consuming the `self` value.
1011     ///
1012     /// Because this function may panic, its use is generally discouraged.
1013     /// Instead, prefer to use pattern matching and handle the [`Err`]
1014     /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
1015     /// [`unwrap_or_default`].
1016     ///
1017     /// [`unwrap_or`]: Result::unwrap_or
1018     /// [`unwrap_or_else`]: Result::unwrap_or_else
1019     /// [`unwrap_or_default`]: Result::unwrap_or_default
1020     ///
1021     /// # Panics
1022     ///
1023     /// Panics if the value is an [`Err`], with a panic message including the
1024     /// passed message, and the content of the [`Err`].
1025     ///
1026     ///
1027     /// # Examples
1028     ///
1029     /// Basic usage:
1030     ///
1031     /// ```should_panic
1032     /// let x: Result<u32, &str> = Err("emergency failure");
1033     /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
1034     /// ```
1035     ///
1036     /// # Recommended Message Style
1037     ///
1038     /// We recommend that `expect` messages are used to describe the reason you
1039     /// _expect_ the `Result` should be `Ok`.
1040     ///
1041     /// ```should_panic
1042     /// let path = std::env::var("IMPORTANT_PATH")
1043     ///     .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`");
1044     /// ```
1045     ///
1046     /// **Hint**: If you're having trouble remembering how to phrase expect
1047     /// error messages remember to focus on the word "should" as in "env
1048     /// variable should be set by blah" or "the given binary should be available
1049     /// and executable by the current user".
1050     ///
1051     /// For more detail on expect message styles and the reasoning behind our recommendation please
1052     /// refer to the section on ["Common Message
1053     /// Styles"](../../std/error/index.html#common-message-styles) in the
1054     /// [`std::error`](../../std/error/index.html) module docs.
1055     #[inline]
1056     #[track_caller]
1057     #[stable(feature = "result_expect", since = "1.4.0")]
1058     pub fn expect(self, msg: &str) -> T
1059     where
1060         E: fmt::Debug,
1061     {
1062         match self {
1063             Ok(t) => t,
1064             Err(e) => unwrap_failed(msg, &e),
1065         }
1066     }
1067
1068     /// Returns the contained [`Ok`] value, consuming the `self` value.
1069     ///
1070     /// Because this function may panic, its use is generally discouraged.
1071     /// Instead, prefer to use pattern matching and handle the [`Err`]
1072     /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
1073     /// [`unwrap_or_default`].
1074     ///
1075     /// [`unwrap_or`]: Result::unwrap_or
1076     /// [`unwrap_or_else`]: Result::unwrap_or_else
1077     /// [`unwrap_or_default`]: Result::unwrap_or_default
1078     ///
1079     /// # Panics
1080     ///
1081     /// Panics if the value is an [`Err`], with a panic message provided by the
1082     /// [`Err`]'s value.
1083     ///
1084     ///
1085     /// # Examples
1086     ///
1087     /// Basic usage:
1088     ///
1089     /// ```
1090     /// let x: Result<u32, &str> = Ok(2);
1091     /// assert_eq!(x.unwrap(), 2);
1092     /// ```
1093     ///
1094     /// ```should_panic
1095     /// let x: Result<u32, &str> = Err("emergency failure");
1096     /// x.unwrap(); // panics with `emergency failure`
1097     /// ```
1098     #[inline]
1099     #[track_caller]
1100     #[stable(feature = "rust1", since = "1.0.0")]
1101     pub fn unwrap(self) -> T
1102     where
1103         E: fmt::Debug,
1104     {
1105         match self {
1106             Ok(t) => t,
1107             Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e),
1108         }
1109     }
1110
1111     /// Returns the contained [`Ok`] value or a default
1112     ///
1113     /// Consumes the `self` argument then, if [`Ok`], returns the contained
1114     /// value, otherwise if [`Err`], returns the default value for that
1115     /// type.
1116     ///
1117     /// # Examples
1118     ///
1119     /// Converts a string to an integer, turning poorly-formed strings
1120     /// into 0 (the default value for integers). [`parse`] converts
1121     /// a string to any other type that implements [`FromStr`], returning an
1122     /// [`Err`] on error.
1123     ///
1124     /// ```
1125     /// let good_year_from_input = "1909";
1126     /// let bad_year_from_input = "190blarg";
1127     /// let good_year = good_year_from_input.parse().unwrap_or_default();
1128     /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
1129     ///
1130     /// assert_eq!(1909, good_year);
1131     /// assert_eq!(0, bad_year);
1132     /// ```
1133     ///
1134     /// [`parse`]: str::parse
1135     /// [`FromStr`]: crate::str::FromStr
1136     #[inline]
1137     #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
1138     pub fn unwrap_or_default(self) -> T
1139     where
1140         T: Default,
1141     {
1142         match self {
1143             Ok(x) => x,
1144             Err(_) => Default::default(),
1145         }
1146     }
1147
1148     /// Returns the contained [`Err`] value, consuming the `self` value.
1149     ///
1150     /// # Panics
1151     ///
1152     /// Panics if the value is an [`Ok`], with a panic message including the
1153     /// passed message, and the content of the [`Ok`].
1154     ///
1155     ///
1156     /// # Examples
1157     ///
1158     /// Basic usage:
1159     ///
1160     /// ```should_panic
1161     /// let x: Result<u32, &str> = Ok(10);
1162     /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
1163     /// ```
1164     #[inline]
1165     #[track_caller]
1166     #[stable(feature = "result_expect_err", since = "1.17.0")]
1167     pub fn expect_err(self, msg: &str) -> E
1168     where
1169         T: fmt::Debug,
1170     {
1171         match self {
1172             Ok(t) => unwrap_failed(msg, &t),
1173             Err(e) => e,
1174         }
1175     }
1176
1177     /// Returns the contained [`Err`] value, consuming the `self` value.
1178     ///
1179     /// # Panics
1180     ///
1181     /// Panics if the value is an [`Ok`], with a custom panic message provided
1182     /// by the [`Ok`]'s value.
1183     ///
1184     /// # Examples
1185     ///
1186     /// ```should_panic
1187     /// let x: Result<u32, &str> = Ok(2);
1188     /// x.unwrap_err(); // panics with `2`
1189     /// ```
1190     ///
1191     /// ```
1192     /// let x: Result<u32, &str> = Err("emergency failure");
1193     /// assert_eq!(x.unwrap_err(), "emergency failure");
1194     /// ```
1195     #[inline]
1196     #[track_caller]
1197     #[stable(feature = "rust1", since = "1.0.0")]
1198     pub fn unwrap_err(self) -> E
1199     where
1200         T: fmt::Debug,
1201     {
1202         match self {
1203             Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t),
1204             Err(e) => e,
1205         }
1206     }
1207
1208     /// Returns the contained [`Ok`] value, but never panics.
1209     ///
1210     /// Unlike [`unwrap`], this method is known to never panic on the
1211     /// result types it is implemented for. Therefore, it can be used
1212     /// instead of `unwrap` as a maintainability safeguard that will fail
1213     /// to compile if the error type of the `Result` is later changed
1214     /// to an error that can actually occur.
1215     ///
1216     /// [`unwrap`]: Result::unwrap
1217     ///
1218     /// # Examples
1219     ///
1220     /// Basic usage:
1221     ///
1222     /// ```
1223     /// # #![feature(never_type)]
1224     /// # #![feature(unwrap_infallible)]
1225     ///
1226     /// fn only_good_news() -> Result<String, !> {
1227     ///     Ok("this is fine".into())
1228     /// }
1229     ///
1230     /// let s: String = only_good_news().into_ok();
1231     /// println!("{s}");
1232     /// ```
1233     #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
1234     #[inline]
1235     pub fn into_ok(self) -> T
1236     where
1237         E: Into<!>,
1238     {
1239         match self {
1240             Ok(x) => x,
1241             Err(e) => e.into(),
1242         }
1243     }
1244
1245     /// Returns the contained [`Err`] value, but never panics.
1246     ///
1247     /// Unlike [`unwrap_err`], this method is known to never panic on the
1248     /// result types it is implemented for. Therefore, it can be used
1249     /// instead of `unwrap_err` as a maintainability safeguard that will fail
1250     /// to compile if the ok type of the `Result` is later changed
1251     /// to a type that can actually occur.
1252     ///
1253     /// [`unwrap_err`]: Result::unwrap_err
1254     ///
1255     /// # Examples
1256     ///
1257     /// Basic usage:
1258     ///
1259     /// ```
1260     /// # #![feature(never_type)]
1261     /// # #![feature(unwrap_infallible)]
1262     ///
1263     /// fn only_bad_news() -> Result<!, String> {
1264     ///     Err("Oops, it failed".into())
1265     /// }
1266     ///
1267     /// let error: String = only_bad_news().into_err();
1268     /// println!("{error}");
1269     /// ```
1270     #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
1271     #[inline]
1272     pub fn into_err(self) -> E
1273     where
1274         T: Into<!>,
1275     {
1276         match self {
1277             Ok(x) => x.into(),
1278             Err(e) => e,
1279         }
1280     }
1281
1282     ////////////////////////////////////////////////////////////////////////
1283     // Boolean operations on the values, eager and lazy
1284     /////////////////////////////////////////////////////////////////////////
1285
1286     /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
1287     ///
1288     ///
1289     /// # Examples
1290     ///
1291     /// Basic usage:
1292     ///
1293     /// ```
1294     /// let x: Result<u32, &str> = Ok(2);
1295     /// let y: Result<&str, &str> = Err("late error");
1296     /// assert_eq!(x.and(y), Err("late error"));
1297     ///
1298     /// let x: Result<u32, &str> = Err("early error");
1299     /// let y: Result<&str, &str> = Ok("foo");
1300     /// assert_eq!(x.and(y), Err("early error"));
1301     ///
1302     /// let x: Result<u32, &str> = Err("not a 2");
1303     /// let y: Result<&str, &str> = Err("late error");
1304     /// assert_eq!(x.and(y), Err("not a 2"));
1305     ///
1306     /// let x: Result<u32, &str> = Ok(2);
1307     /// let y: Result<&str, &str> = Ok("different result type");
1308     /// assert_eq!(x.and(y), Ok("different result type"));
1309     /// ```
1310     #[inline]
1311     #[rustc_const_unstable(feature = "const_result_drop", issue = "92384")]
1312     #[stable(feature = "rust1", since = "1.0.0")]
1313     pub const fn and<U>(self, res: Result<U, E>) -> Result<U, E>
1314     where
1315         T: ~const Destruct,
1316         U: ~const Destruct,
1317         E: ~const Destruct,
1318     {
1319         match self {
1320             // FIXME: ~const Drop doesn't quite work right yet
1321             #[allow(unused_variables)]
1322             Ok(x) => res,
1323             Err(e) => Err(e),
1324         }
1325     }
1326
1327     /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
1328     ///
1329     ///
1330     /// This function can be used for control flow based on `Result` values.
1331     ///
1332     /// # Examples
1333     ///
1334     /// ```
1335     /// fn sq_then_to_string(x: u32) -> Result<String, &'static str> {
1336     ///     x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed")
1337     /// }
1338     ///
1339     /// assert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));
1340     /// assert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err("overflowed"));
1341     /// assert_eq!(Err("not a number").and_then(sq_then_to_string), Err("not a number"));
1342     /// ```
1343     ///
1344     /// Often used to chain fallible operations that may return [`Err`].
1345     ///
1346     /// ```
1347     /// use std::{io::ErrorKind, path::Path};
1348     ///
1349     /// // Note: on Windows "/" maps to "C:\"
1350     /// let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified());
1351     /// assert!(root_modified_time.is_ok());
1352     ///
1353     /// let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified());
1354     /// assert!(should_fail.is_err());
1355     /// assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
1356     /// ```
1357     #[inline]
1358     #[stable(feature = "rust1", since = "1.0.0")]
1359     pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
1360         match self {
1361             Ok(t) => op(t),
1362             Err(e) => Err(e),
1363         }
1364     }
1365
1366     /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
1367     ///
1368     /// Arguments passed to `or` are eagerly evaluated; if you are passing the
1369     /// result of a function call, it is recommended to use [`or_else`], which is
1370     /// lazily evaluated.
1371     ///
1372     /// [`or_else`]: Result::or_else
1373     ///
1374     /// # Examples
1375     ///
1376     /// Basic usage:
1377     ///
1378     /// ```
1379     /// let x: Result<u32, &str> = Ok(2);
1380     /// let y: Result<u32, &str> = Err("late error");
1381     /// assert_eq!(x.or(y), Ok(2));
1382     ///
1383     /// let x: Result<u32, &str> = Err("early error");
1384     /// let y: Result<u32, &str> = Ok(2);
1385     /// assert_eq!(x.or(y), Ok(2));
1386     ///
1387     /// let x: Result<u32, &str> = Err("not a 2");
1388     /// let y: Result<u32, &str> = Err("late error");
1389     /// assert_eq!(x.or(y), Err("late error"));
1390     ///
1391     /// let x: Result<u32, &str> = Ok(2);
1392     /// let y: Result<u32, &str> = Ok(100);
1393     /// assert_eq!(x.or(y), Ok(2));
1394     /// ```
1395     #[inline]
1396     #[rustc_const_unstable(feature = "const_result_drop", issue = "92384")]
1397     #[stable(feature = "rust1", since = "1.0.0")]
1398     pub const fn or<F>(self, res: Result<T, F>) -> Result<T, F>
1399     where
1400         T: ~const Destruct,
1401         E: ~const Destruct,
1402         F: ~const Destruct,
1403     {
1404         match self {
1405             Ok(v) => Ok(v),
1406             // FIXME: ~const Drop doesn't quite work right yet
1407             #[allow(unused_variables)]
1408             Err(e) => res,
1409         }
1410     }
1411
1412     /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
1413     ///
1414     /// This function can be used for control flow based on result values.
1415     ///
1416     ///
1417     /// # Examples
1418     ///
1419     /// Basic usage:
1420     ///
1421     /// ```
1422     /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
1423     /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
1424     ///
1425     /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
1426     /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
1427     /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
1428     /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
1429     /// ```
1430     #[inline]
1431     #[stable(feature = "rust1", since = "1.0.0")]
1432     pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
1433         match self {
1434             Ok(t) => Ok(t),
1435             Err(e) => op(e),
1436         }
1437     }
1438
1439     /// Returns the contained [`Ok`] value or a provided default.
1440     ///
1441     /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
1442     /// the result of a function call, it is recommended to use [`unwrap_or_else`],
1443     /// which is lazily evaluated.
1444     ///
1445     /// [`unwrap_or_else`]: Result::unwrap_or_else
1446     ///
1447     /// # Examples
1448     ///
1449     /// Basic usage:
1450     ///
1451     /// ```
1452     /// let default = 2;
1453     /// let x: Result<u32, &str> = Ok(9);
1454     /// assert_eq!(x.unwrap_or(default), 9);
1455     ///
1456     /// let x: Result<u32, &str> = Err("error");
1457     /// assert_eq!(x.unwrap_or(default), default);
1458     /// ```
1459     #[inline]
1460     #[rustc_const_unstable(feature = "const_result_drop", issue = "92384")]
1461     #[stable(feature = "rust1", since = "1.0.0")]
1462     pub const fn unwrap_or(self, default: T) -> T
1463     where
1464         T: ~const Destruct,
1465         E: ~const Destruct,
1466     {
1467         match self {
1468             Ok(t) => t,
1469             // FIXME: ~const Drop doesn't quite work right yet
1470             #[allow(unused_variables)]
1471             Err(e) => default,
1472         }
1473     }
1474
1475     /// Returns the contained [`Ok`] value or computes it from a closure.
1476     ///
1477     ///
1478     /// # Examples
1479     ///
1480     /// Basic usage:
1481     ///
1482     /// ```
1483     /// fn count(x: &str) -> usize { x.len() }
1484     ///
1485     /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
1486     /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
1487     /// ```
1488     #[inline]
1489     #[stable(feature = "rust1", since = "1.0.0")]
1490     pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
1491         match self {
1492             Ok(t) => t,
1493             Err(e) => op(e),
1494         }
1495     }
1496
1497     /// Returns the contained [`Ok`] value, consuming the `self` value,
1498     /// without checking that the value is not an [`Err`].
1499     ///
1500     /// # Safety
1501     ///
1502     /// Calling this method on an [`Err`] is *[undefined behavior]*.
1503     ///
1504     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1505     ///
1506     /// # Examples
1507     ///
1508     /// ```
1509     /// let x: Result<u32, &str> = Ok(2);
1510     /// assert_eq!(unsafe { x.unwrap_unchecked() }, 2);
1511     /// ```
1512     ///
1513     /// ```no_run
1514     /// let x: Result<u32, &str> = Err("emergency failure");
1515     /// unsafe { x.unwrap_unchecked(); } // Undefined behavior!
1516     /// ```
1517     #[inline]
1518     #[track_caller]
1519     #[stable(feature = "option_result_unwrap_unchecked", since = "1.58.0")]
1520     pub unsafe fn unwrap_unchecked(self) -> T {
1521         debug_assert!(self.is_ok());
1522         match self {
1523             Ok(t) => t,
1524             // SAFETY: the safety contract must be upheld by the caller.
1525             Err(_) => unsafe { hint::unreachable_unchecked() },
1526         }
1527     }
1528
1529     /// Returns the contained [`Err`] value, consuming the `self` value,
1530     /// without checking that the value is not an [`Ok`].
1531     ///
1532     /// # Safety
1533     ///
1534     /// Calling this method on an [`Ok`] is *[undefined behavior]*.
1535     ///
1536     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1537     ///
1538     /// # Examples
1539     ///
1540     /// ```no_run
1541     /// let x: Result<u32, &str> = Ok(2);
1542     /// unsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
1543     /// ```
1544     ///
1545     /// ```
1546     /// let x: Result<u32, &str> = Err("emergency failure");
1547     /// assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure");
1548     /// ```
1549     #[inline]
1550     #[track_caller]
1551     #[stable(feature = "option_result_unwrap_unchecked", since = "1.58.0")]
1552     pub unsafe fn unwrap_err_unchecked(self) -> E {
1553         debug_assert!(self.is_err());
1554         match self {
1555             // SAFETY: the safety contract must be upheld by the caller.
1556             Ok(_) => unsafe { hint::unreachable_unchecked() },
1557             Err(e) => e,
1558         }
1559     }
1560
1561     /////////////////////////////////////////////////////////////////////////
1562     // Misc or niche
1563     /////////////////////////////////////////////////////////////////////////
1564
1565     /// Returns `true` if the result is an [`Ok`] value containing the given value.
1566     ///
1567     /// # Examples
1568     ///
1569     /// ```
1570     /// #![feature(option_result_contains)]
1571     ///
1572     /// let x: Result<u32, &str> = Ok(2);
1573     /// assert_eq!(x.contains(&2), true);
1574     ///
1575     /// let x: Result<u32, &str> = Ok(3);
1576     /// assert_eq!(x.contains(&2), false);
1577     ///
1578     /// let x: Result<u32, &str> = Err("Some error message");
1579     /// assert_eq!(x.contains(&2), false);
1580     /// ```
1581     #[must_use]
1582     #[inline]
1583     #[unstable(feature = "option_result_contains", issue = "62358")]
1584     pub fn contains<U>(&self, x: &U) -> bool
1585     where
1586         U: PartialEq<T>,
1587     {
1588         match self {
1589             Ok(y) => x == y,
1590             Err(_) => false,
1591         }
1592     }
1593
1594     /// Returns `true` if the result is an [`Err`] value containing the given value.
1595     ///
1596     /// # Examples
1597     ///
1598     /// ```
1599     /// #![feature(result_contains_err)]
1600     ///
1601     /// let x: Result<u32, &str> = Ok(2);
1602     /// assert_eq!(x.contains_err(&"Some error message"), false);
1603     ///
1604     /// let x: Result<u32, &str> = Err("Some error message");
1605     /// assert_eq!(x.contains_err(&"Some error message"), true);
1606     ///
1607     /// let x: Result<u32, &str> = Err("Some other error message");
1608     /// assert_eq!(x.contains_err(&"Some error message"), false);
1609     /// ```
1610     #[must_use]
1611     #[inline]
1612     #[unstable(feature = "result_contains_err", issue = "62358")]
1613     pub fn contains_err<F>(&self, f: &F) -> bool
1614     where
1615         F: PartialEq<E>,
1616     {
1617         match self {
1618             Ok(_) => false,
1619             Err(e) => f == e,
1620         }
1621     }
1622 }
1623
1624 impl<T, E> Result<&T, E> {
1625     /// Maps a `Result<&T, E>` to a `Result<T, E>` by copying the contents of the
1626     /// `Ok` part.
1627     ///
1628     /// # Examples
1629     ///
1630     /// ```
1631     /// let val = 12;
1632     /// let x: Result<&i32, i32> = Ok(&val);
1633     /// assert_eq!(x, Ok(&12));
1634     /// let copied = x.copied();
1635     /// assert_eq!(copied, Ok(12));
1636     /// ```
1637     #[inline]
1638     #[stable(feature = "result_copied", since = "1.59.0")]
1639     pub fn copied(self) -> Result<T, E>
1640     where
1641         T: Copy,
1642     {
1643         self.map(|&t| t)
1644     }
1645
1646     /// Maps a `Result<&T, E>` to a `Result<T, E>` by cloning the contents of the
1647     /// `Ok` part.
1648     ///
1649     /// # Examples
1650     ///
1651     /// ```
1652     /// let val = 12;
1653     /// let x: Result<&i32, i32> = Ok(&val);
1654     /// assert_eq!(x, Ok(&12));
1655     /// let cloned = x.cloned();
1656     /// assert_eq!(cloned, Ok(12));
1657     /// ```
1658     #[inline]
1659     #[stable(feature = "result_cloned", since = "1.59.0")]
1660     pub fn cloned(self) -> Result<T, E>
1661     where
1662         T: Clone,
1663     {
1664         self.map(|t| t.clone())
1665     }
1666 }
1667
1668 impl<T, E> Result<&mut T, E> {
1669     /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by copying the contents of the
1670     /// `Ok` part.
1671     ///
1672     /// # Examples
1673     ///
1674     /// ```
1675     /// let mut val = 12;
1676     /// let x: Result<&mut i32, i32> = Ok(&mut val);
1677     /// assert_eq!(x, Ok(&mut 12));
1678     /// let copied = x.copied();
1679     /// assert_eq!(copied, Ok(12));
1680     /// ```
1681     #[inline]
1682     #[stable(feature = "result_copied", since = "1.59.0")]
1683     pub fn copied(self) -> Result<T, E>
1684     where
1685         T: Copy,
1686     {
1687         self.map(|&mut t| t)
1688     }
1689
1690     /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by cloning the contents of the
1691     /// `Ok` part.
1692     ///
1693     /// # Examples
1694     ///
1695     /// ```
1696     /// let mut val = 12;
1697     /// let x: Result<&mut i32, i32> = Ok(&mut val);
1698     /// assert_eq!(x, Ok(&mut 12));
1699     /// let cloned = x.cloned();
1700     /// assert_eq!(cloned, Ok(12));
1701     /// ```
1702     #[inline]
1703     #[stable(feature = "result_cloned", since = "1.59.0")]
1704     pub fn cloned(self) -> Result<T, E>
1705     where
1706         T: Clone,
1707     {
1708         self.map(|t| t.clone())
1709     }
1710 }
1711
1712 impl<T, E> Result<Option<T>, E> {
1713     /// Transposes a `Result` of an `Option` into an `Option` of a `Result`.
1714     ///
1715     /// `Ok(None)` will be mapped to `None`.
1716     /// `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`.
1717     ///
1718     /// # Examples
1719     ///
1720     /// ```
1721     /// #[derive(Debug, Eq, PartialEq)]
1722     /// struct SomeErr;
1723     ///
1724     /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1725     /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1726     /// assert_eq!(x.transpose(), y);
1727     /// ```
1728     #[inline]
1729     #[stable(feature = "transpose_result", since = "1.33.0")]
1730     #[rustc_const_unstable(feature = "const_result", issue = "82814")]
1731     pub const fn transpose(self) -> Option<Result<T, E>> {
1732         match self {
1733             Ok(Some(x)) => Some(Ok(x)),
1734             Ok(None) => None,
1735             Err(e) => Some(Err(e)),
1736         }
1737     }
1738 }
1739
1740 impl<T, E> Result<Result<T, E>, E> {
1741     /// Converts from `Result<Result<T, E>, E>` to `Result<T, E>`
1742     ///
1743     /// # Examples
1744     ///
1745     /// Basic usage:
1746     ///
1747     /// ```
1748     /// #![feature(result_flattening)]
1749     /// let x: Result<Result<&'static str, u32>, u32> = Ok(Ok("hello"));
1750     /// assert_eq!(Ok("hello"), x.flatten());
1751     ///
1752     /// let x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));
1753     /// assert_eq!(Err(6), x.flatten());
1754     ///
1755     /// let x: Result<Result<&'static str, u32>, u32> = Err(6);
1756     /// assert_eq!(Err(6), x.flatten());
1757     /// ```
1758     ///
1759     /// Flattening only removes one level of nesting at a time:
1760     ///
1761     /// ```
1762     /// #![feature(result_flattening)]
1763     /// let x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok("hello")));
1764     /// assert_eq!(Ok(Ok("hello")), x.flatten());
1765     /// assert_eq!(Ok("hello"), x.flatten().flatten());
1766     /// ```
1767     #[inline]
1768     #[unstable(feature = "result_flattening", issue = "70142")]
1769     pub fn flatten(self) -> Result<T, E> {
1770         self.and_then(convert::identity)
1771     }
1772 }
1773
1774 impl<T> Result<T, T> {
1775     /// Returns the [`Ok`] value if `self` is `Ok`, and the [`Err`] value if
1776     /// `self` is `Err`.
1777     ///
1778     /// In other words, this function returns the value (the `T`) of a
1779     /// `Result<T, T>`, regardless of whether or not that result is `Ok` or
1780     /// `Err`.
1781     ///
1782     /// This can be useful in conjunction with APIs such as
1783     /// [`Atomic*::compare_exchange`], or [`slice::binary_search`], but only in
1784     /// cases where you don't care if the result was `Ok` or not.
1785     ///
1786     /// [`Atomic*::compare_exchange`]: crate::sync::atomic::AtomicBool::compare_exchange
1787     ///
1788     /// # Examples
1789     ///
1790     /// ```
1791     /// #![feature(result_into_ok_or_err)]
1792     /// let ok: Result<u32, u32> = Ok(3);
1793     /// let err: Result<u32, u32> = Err(4);
1794     ///
1795     /// assert_eq!(ok.into_ok_or_err(), 3);
1796     /// assert_eq!(err.into_ok_or_err(), 4);
1797     /// ```
1798     #[inline]
1799     #[unstable(feature = "result_into_ok_or_err", reason = "newly added", issue = "82223")]
1800     pub const fn into_ok_or_err(self) -> T {
1801         match self {
1802             Ok(v) => v,
1803             Err(v) => v,
1804         }
1805     }
1806 }
1807
1808 // This is a separate function to reduce the code size of the methods
1809 #[cfg(not(feature = "panic_immediate_abort"))]
1810 #[inline(never)]
1811 #[cold]
1812 #[track_caller]
1813 fn unwrap_failed(msg: &str, error: &dyn fmt::Debug) -> ! {
1814     panic!("{msg}: {error:?}")
1815 }
1816
1817 // This is a separate function to avoid constructing a `dyn Debug`
1818 // that gets immediately thrown away, since vtables don't get cleaned up
1819 // by dead code elimination if a trait object is constructed even if it goes
1820 // unused
1821 #[cfg(feature = "panic_immediate_abort")]
1822 #[inline]
1823 #[cold]
1824 #[track_caller]
1825 fn unwrap_failed<T>(_msg: &str, _error: &T) -> ! {
1826     panic!()
1827 }
1828
1829 /////////////////////////////////////////////////////////////////////////////
1830 // Trait implementations
1831 /////////////////////////////////////////////////////////////////////////////
1832
1833 #[stable(feature = "rust1", since = "1.0.0")]
1834 #[rustc_const_unstable(feature = "const_clone", issue = "91805")]
1835 impl<T, E> const Clone for Result<T, E>
1836 where
1837     T: ~const Clone + ~const Destruct,
1838     E: ~const Clone + ~const Destruct,
1839 {
1840     #[inline]
1841     fn clone(&self) -> Self {
1842         match self {
1843             Ok(x) => Ok(x.clone()),
1844             Err(x) => Err(x.clone()),
1845         }
1846     }
1847
1848     #[inline]
1849     fn clone_from(&mut self, source: &Self) {
1850         match (self, source) {
1851             (Ok(to), Ok(from)) => to.clone_from(from),
1852             (Err(to), Err(from)) => to.clone_from(from),
1853             (to, from) => *to = from.clone(),
1854         }
1855     }
1856 }
1857
1858 #[stable(feature = "rust1", since = "1.0.0")]
1859 impl<T, E> IntoIterator for Result<T, E> {
1860     type Item = T;
1861     type IntoIter = IntoIter<T>;
1862
1863     /// Returns a consuming iterator over the possibly contained value.
1864     ///
1865     /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
1866     ///
1867     /// # Examples
1868     ///
1869     /// Basic usage:
1870     ///
1871     /// ```
1872     /// let x: Result<u32, &str> = Ok(5);
1873     /// let v: Vec<u32> = x.into_iter().collect();
1874     /// assert_eq!(v, [5]);
1875     ///
1876     /// let x: Result<u32, &str> = Err("nothing!");
1877     /// let v: Vec<u32> = x.into_iter().collect();
1878     /// assert_eq!(v, []);
1879     /// ```
1880     #[inline]
1881     fn into_iter(self) -> IntoIter<T> {
1882         IntoIter { inner: self.ok() }
1883     }
1884 }
1885
1886 #[stable(since = "1.4.0", feature = "result_iter")]
1887 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
1888     type Item = &'a T;
1889     type IntoIter = Iter<'a, T>;
1890
1891     fn into_iter(self) -> Iter<'a, T> {
1892         self.iter()
1893     }
1894 }
1895
1896 #[stable(since = "1.4.0", feature = "result_iter")]
1897 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
1898     type Item = &'a mut T;
1899     type IntoIter = IterMut<'a, T>;
1900
1901     fn into_iter(self) -> IterMut<'a, T> {
1902         self.iter_mut()
1903     }
1904 }
1905
1906 /////////////////////////////////////////////////////////////////////////////
1907 // The Result Iterators
1908 /////////////////////////////////////////////////////////////////////////////
1909
1910 /// An iterator over a reference to the [`Ok`] variant of a [`Result`].
1911 ///
1912 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1913 ///
1914 /// Created by [`Result::iter`].
1915 #[derive(Debug)]
1916 #[stable(feature = "rust1", since = "1.0.0")]
1917 pub struct Iter<'a, T: 'a> {
1918     inner: Option<&'a T>,
1919 }
1920
1921 #[stable(feature = "rust1", since = "1.0.0")]
1922 impl<'a, T> Iterator for Iter<'a, T> {
1923     type Item = &'a T;
1924
1925     #[inline]
1926     fn next(&mut self) -> Option<&'a T> {
1927         self.inner.take()
1928     }
1929     #[inline]
1930     fn size_hint(&self) -> (usize, Option<usize>) {
1931         let n = if self.inner.is_some() { 1 } else { 0 };
1932         (n, Some(n))
1933     }
1934 }
1935
1936 #[stable(feature = "rust1", since = "1.0.0")]
1937 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1938     #[inline]
1939     fn next_back(&mut self) -> Option<&'a T> {
1940         self.inner.take()
1941     }
1942 }
1943
1944 #[stable(feature = "rust1", since = "1.0.0")]
1945 impl<T> ExactSizeIterator for Iter<'_, T> {}
1946
1947 #[stable(feature = "fused", since = "1.26.0")]
1948 impl<T> FusedIterator for Iter<'_, T> {}
1949
1950 #[unstable(feature = "trusted_len", issue = "37572")]
1951 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1952
1953 #[stable(feature = "rust1", since = "1.0.0")]
1954 impl<T> Clone for Iter<'_, T> {
1955     #[inline]
1956     fn clone(&self) -> Self {
1957         Iter { inner: self.inner }
1958     }
1959 }
1960
1961 /// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
1962 ///
1963 /// Created by [`Result::iter_mut`].
1964 #[derive(Debug)]
1965 #[stable(feature = "rust1", since = "1.0.0")]
1966 pub struct IterMut<'a, T: 'a> {
1967     inner: Option<&'a mut T>,
1968 }
1969
1970 #[stable(feature = "rust1", since = "1.0.0")]
1971 impl<'a, T> Iterator for IterMut<'a, T> {
1972     type Item = &'a mut T;
1973
1974     #[inline]
1975     fn next(&mut self) -> Option<&'a mut T> {
1976         self.inner.take()
1977     }
1978     #[inline]
1979     fn size_hint(&self) -> (usize, Option<usize>) {
1980         let n = if self.inner.is_some() { 1 } else { 0 };
1981         (n, Some(n))
1982     }
1983 }
1984
1985 #[stable(feature = "rust1", since = "1.0.0")]
1986 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1987     #[inline]
1988     fn next_back(&mut self) -> Option<&'a mut T> {
1989         self.inner.take()
1990     }
1991 }
1992
1993 #[stable(feature = "rust1", since = "1.0.0")]
1994 impl<T> ExactSizeIterator for IterMut<'_, T> {}
1995
1996 #[stable(feature = "fused", since = "1.26.0")]
1997 impl<T> FusedIterator for IterMut<'_, T> {}
1998
1999 #[unstable(feature = "trusted_len", issue = "37572")]
2000 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
2001
2002 /// An iterator over the value in a [`Ok`] variant of a [`Result`].
2003 ///
2004 /// The iterator yields one value if the result is [`Ok`], otherwise none.
2005 ///
2006 /// This struct is created by the [`into_iter`] method on
2007 /// [`Result`] (provided by the [`IntoIterator`] trait).
2008 ///
2009 /// [`into_iter`]: IntoIterator::into_iter
2010 #[derive(Clone, Debug)]
2011 #[stable(feature = "rust1", since = "1.0.0")]
2012 pub struct IntoIter<T> {
2013     inner: Option<T>,
2014 }
2015
2016 #[stable(feature = "rust1", since = "1.0.0")]
2017 impl<T> Iterator for IntoIter<T> {
2018     type Item = T;
2019
2020     #[inline]
2021     fn next(&mut self) -> Option<T> {
2022         self.inner.take()
2023     }
2024     #[inline]
2025     fn size_hint(&self) -> (usize, Option<usize>) {
2026         let n = if self.inner.is_some() { 1 } else { 0 };
2027         (n, Some(n))
2028     }
2029 }
2030
2031 #[stable(feature = "rust1", since = "1.0.0")]
2032 impl<T> DoubleEndedIterator for IntoIter<T> {
2033     #[inline]
2034     fn next_back(&mut self) -> Option<T> {
2035         self.inner.take()
2036     }
2037 }
2038
2039 #[stable(feature = "rust1", since = "1.0.0")]
2040 impl<T> ExactSizeIterator for IntoIter<T> {}
2041
2042 #[stable(feature = "fused", since = "1.26.0")]
2043 impl<T> FusedIterator for IntoIter<T> {}
2044
2045 #[unstable(feature = "trusted_len", issue = "37572")]
2046 unsafe impl<A> TrustedLen for IntoIter<A> {}
2047
2048 /////////////////////////////////////////////////////////////////////////////
2049 // FromIterator
2050 /////////////////////////////////////////////////////////////////////////////
2051
2052 #[stable(feature = "rust1", since = "1.0.0")]
2053 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
2054     /// Takes each element in the `Iterator`: if it is an `Err`, no further
2055     /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
2056     /// container with the values of each `Result` is returned.
2057     ///
2058     /// Here is an example which increments every integer in a vector,
2059     /// checking for overflow:
2060     ///
2061     /// ```
2062     /// let v = vec![1, 2];
2063     /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
2064     ///     x.checked_add(1).ok_or("Overflow!")
2065     /// ).collect();
2066     /// assert_eq!(res, Ok(vec![2, 3]));
2067     /// ```
2068     ///
2069     /// Here is another example that tries to subtract one from another list
2070     /// of integers, this time checking for underflow:
2071     ///
2072     /// ```
2073     /// let v = vec![1, 2, 0];
2074     /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
2075     ///     x.checked_sub(1).ok_or("Underflow!")
2076     /// ).collect();
2077     /// assert_eq!(res, Err("Underflow!"));
2078     /// ```
2079     ///
2080     /// Here is a variation on the previous example, showing that no
2081     /// further elements are taken from `iter` after the first `Err`.
2082     ///
2083     /// ```
2084     /// let v = vec![3, 2, 1, 10];
2085     /// let mut shared = 0;
2086     /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {
2087     ///     shared += x;
2088     ///     x.checked_sub(2).ok_or("Underflow!")
2089     /// }).collect();
2090     /// assert_eq!(res, Err("Underflow!"));
2091     /// assert_eq!(shared, 6);
2092     /// ```
2093     ///
2094     /// Since the third element caused an underflow, no further elements were taken,
2095     /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
2096     #[inline]
2097     fn from_iter<I: IntoIterator<Item = Result<A, E>>>(iter: I) -> Result<V, E> {
2098         // FIXME(#11084): This could be replaced with Iterator::scan when this
2099         // performance bug is closed.
2100
2101         iter::try_process(iter.into_iter(), |i| i.collect())
2102     }
2103 }
2104
2105 #[unstable(feature = "try_trait_v2", issue = "84277")]
2106 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
2107 impl<T, E> const ops::Try for Result<T, E> {
2108     type Output = T;
2109     type Residual = Result<convert::Infallible, E>;
2110
2111     #[inline]
2112     fn from_output(output: Self::Output) -> Self {
2113         Ok(output)
2114     }
2115
2116     #[inline]
2117     fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
2118         match self {
2119             Ok(v) => ControlFlow::Continue(v),
2120             Err(e) => ControlFlow::Break(Err(e)),
2121         }
2122     }
2123 }
2124
2125 #[unstable(feature = "try_trait_v2", issue = "84277")]
2126 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
2127 impl<T, E, F: ~const From<E>> const ops::FromResidual<Result<convert::Infallible, E>>
2128     for Result<T, F>
2129 {
2130     #[inline]
2131     #[track_caller]
2132     fn from_residual(residual: Result<convert::Infallible, E>) -> Self {
2133         match residual {
2134             Err(e) => Err(From::from(e)),
2135         }
2136     }
2137 }
2138
2139 #[unstable(feature = "try_trait_v2_yeet", issue = "96374")]
2140 impl<T, E, F: From<E>> ops::FromResidual<ops::Yeet<E>> for Result<T, F> {
2141     #[inline]
2142     fn from_residual(ops::Yeet(e): ops::Yeet<E>) -> Self {
2143         Err(From::from(e))
2144     }
2145 }
2146
2147 #[unstable(feature = "try_trait_v2_residual", issue = "91285")]
2148 impl<T, E> ops::Residual<T> for Result<convert::Infallible, E> {
2149     type TryType = Result<T, E>;
2150 }