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