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