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