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