]> git.proxmox.com Git - rustc.git/blob - library/core/src/result.rs
New upstream version 1.51.0+dfsg1
[rustc.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 [`Result`]`<T, `[`io::Error`]`>`.*
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
221 //! [`write_all`]: ../../std/io/trait.Write.html#method.write_all
222 //! [`io::Result`]: ../../std/io/type.Result.html
223 //! [`?`]: crate::ops::Try
224 //! [`Ok(T)`]: Ok
225 //! [`Err(E)`]: Err
226 //! [`io::Error`]: ../../std/io/struct.Error.html
227
228 #![stable(feature = "rust1", since = "1.0.0")]
229
230 use crate::iter::{self, FromIterator, FusedIterator, TrustedLen};
231 use crate::ops::{self, Deref, DerefMut};
232 use crate::{convert, fmt, hint};
233
234 /// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]).
235 ///
236 /// See the [module documentation](self) for details.
237 #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
238 #[must_use = "this `Result` may be an `Err` variant, which should be handled"]
239 #[rustc_diagnostic_item = "result_type"]
240 #[stable(feature = "rust1", since = "1.0.0")]
241 pub enum Result<T, E> {
242 /// Contains the success value
243 #[lang = "Ok"]
244 #[stable(feature = "rust1", since = "1.0.0")]
245 Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
246
247 /// Contains the error value
248 #[lang = "Err"]
249 #[stable(feature = "rust1", since = "1.0.0")]
250 Err(#[stable(feature = "rust1", since = "1.0.0")] E),
251 }
252
253 /////////////////////////////////////////////////////////////////////////////
254 // Type implementation
255 /////////////////////////////////////////////////////////////////////////////
256
257 impl<T, E> Result<T, E> {
258 /////////////////////////////////////////////////////////////////////////
259 // Querying the contained values
260 /////////////////////////////////////////////////////////////////////////
261
262 /// Returns `true` if the result is [`Ok`].
263 ///
264 /// # Examples
265 ///
266 /// Basic usage:
267 ///
268 /// ```
269 /// let x: Result<i32, &str> = Ok(-3);
270 /// assert_eq!(x.is_ok(), true);
271 ///
272 /// let x: Result<i32, &str> = Err("Some error message");
273 /// assert_eq!(x.is_ok(), false);
274 /// ```
275 #[must_use = "if you intended to assert that this is ok, consider `.unwrap()` instead"]
276 #[rustc_const_stable(feature = "const_result", since = "1.48.0")]
277 #[inline]
278 #[stable(feature = "rust1", since = "1.0.0")]
279 pub const fn is_ok(&self) -> bool {
280 matches!(*self, Ok(_))
281 }
282
283 /// Returns `true` if the result is [`Err`].
284 ///
285 /// # Examples
286 ///
287 /// Basic usage:
288 ///
289 /// ```
290 /// let x: Result<i32, &str> = Ok(-3);
291 /// assert_eq!(x.is_err(), false);
292 ///
293 /// let x: Result<i32, &str> = Err("Some error message");
294 /// assert_eq!(x.is_err(), true);
295 /// ```
296 #[must_use = "if you intended to assert that this is err, consider `.unwrap_err()` instead"]
297 #[rustc_const_stable(feature = "const_result", since = "1.48.0")]
298 #[inline]
299 #[stable(feature = "rust1", since = "1.0.0")]
300 pub const fn is_err(&self) -> bool {
301 !self.is_ok()
302 }
303
304 /// Returns `true` if the result is an [`Ok`] value containing the given value.
305 ///
306 /// # Examples
307 ///
308 /// ```
309 /// #![feature(option_result_contains)]
310 ///
311 /// let x: Result<u32, &str> = Ok(2);
312 /// assert_eq!(x.contains(&2), true);
313 ///
314 /// let x: Result<u32, &str> = Ok(3);
315 /// assert_eq!(x.contains(&2), false);
316 ///
317 /// let x: Result<u32, &str> = Err("Some error message");
318 /// assert_eq!(x.contains(&2), false);
319 /// ```
320 #[must_use]
321 #[inline]
322 #[unstable(feature = "option_result_contains", issue = "62358")]
323 pub fn contains<U>(&self, x: &U) -> bool
324 where
325 U: PartialEq<T>,
326 {
327 match self {
328 Ok(y) => x == y,
329 Err(_) => false,
330 }
331 }
332
333 /// Returns `true` if the result is an [`Err`] value containing the given value.
334 ///
335 /// # Examples
336 ///
337 /// ```
338 /// #![feature(result_contains_err)]
339 ///
340 /// let x: Result<u32, &str> = Ok(2);
341 /// assert_eq!(x.contains_err(&"Some error message"), false);
342 ///
343 /// let x: Result<u32, &str> = Err("Some error message");
344 /// assert_eq!(x.contains_err(&"Some error message"), true);
345 ///
346 /// let x: Result<u32, &str> = Err("Some other error message");
347 /// assert_eq!(x.contains_err(&"Some error message"), false);
348 /// ```
349 #[must_use]
350 #[inline]
351 #[unstable(feature = "result_contains_err", issue = "62358")]
352 pub fn contains_err<F>(&self, f: &F) -> bool
353 where
354 F: PartialEq<E>,
355 {
356 match self {
357 Ok(_) => false,
358 Err(e) => f == e,
359 }
360 }
361
362 /////////////////////////////////////////////////////////////////////////
363 // Adapter for each variant
364 /////////////////////////////////////////////////////////////////////////
365
366 /// Converts from `Result<T, E>` to [`Option<T>`].
367 ///
368 /// Converts `self` into an [`Option<T>`], consuming `self`,
369 /// and discarding the error, if any.
370 ///
371 /// # Examples
372 ///
373 /// Basic usage:
374 ///
375 /// ```
376 /// let x: Result<u32, &str> = Ok(2);
377 /// assert_eq!(x.ok(), Some(2));
378 ///
379 /// let x: Result<u32, &str> = Err("Nothing here");
380 /// assert_eq!(x.ok(), None);
381 /// ```
382 #[inline]
383 #[stable(feature = "rust1", since = "1.0.0")]
384 pub fn ok(self) -> Option<T> {
385 match self {
386 Ok(x) => Some(x),
387 Err(_) => None,
388 }
389 }
390
391 /// Converts from `Result<T, E>` to [`Option<E>`].
392 ///
393 /// Converts `self` into an [`Option<E>`], consuming `self`,
394 /// and discarding the success value, if any.
395 ///
396 /// # Examples
397 ///
398 /// Basic usage:
399 ///
400 /// ```
401 /// let x: Result<u32, &str> = Ok(2);
402 /// assert_eq!(x.err(), None);
403 ///
404 /// let x: Result<u32, &str> = Err("Nothing here");
405 /// assert_eq!(x.err(), Some("Nothing here"));
406 /// ```
407 #[inline]
408 #[stable(feature = "rust1", since = "1.0.0")]
409 pub fn err(self) -> Option<E> {
410 match self {
411 Ok(_) => None,
412 Err(x) => Some(x),
413 }
414 }
415
416 /////////////////////////////////////////////////////////////////////////
417 // Adapter for working with references
418 /////////////////////////////////////////////////////////////////////////
419
420 /// Converts from `&Result<T, E>` to `Result<&T, &E>`.
421 ///
422 /// Produces a new `Result`, containing a reference
423 /// into the original, leaving the original in place.
424 ///
425 /// # Examples
426 ///
427 /// Basic usage:
428 ///
429 /// ```
430 /// let x: Result<u32, &str> = Ok(2);
431 /// assert_eq!(x.as_ref(), Ok(&2));
432 ///
433 /// let x: Result<u32, &str> = Err("Error");
434 /// assert_eq!(x.as_ref(), Err(&"Error"));
435 /// ```
436 #[inline]
437 #[rustc_const_stable(feature = "const_result", since = "1.48.0")]
438 #[stable(feature = "rust1", since = "1.0.0")]
439 pub const fn as_ref(&self) -> Result<&T, &E> {
440 match *self {
441 Ok(ref x) => Ok(x),
442 Err(ref x) => Err(x),
443 }
444 }
445
446 /// Converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`.
447 ///
448 /// # Examples
449 ///
450 /// Basic usage:
451 ///
452 /// ```
453 /// fn mutate(r: &mut Result<i32, i32>) {
454 /// match r.as_mut() {
455 /// Ok(v) => *v = 42,
456 /// Err(e) => *e = 0,
457 /// }
458 /// }
459 ///
460 /// let mut x: Result<i32, i32> = Ok(2);
461 /// mutate(&mut x);
462 /// assert_eq!(x.unwrap(), 42);
463 ///
464 /// let mut x: Result<i32, i32> = Err(13);
465 /// mutate(&mut x);
466 /// assert_eq!(x.unwrap_err(), 0);
467 /// ```
468 #[inline]
469 #[stable(feature = "rust1", since = "1.0.0")]
470 pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
471 match *self {
472 Ok(ref mut x) => Ok(x),
473 Err(ref mut x) => Err(x),
474 }
475 }
476
477 /////////////////////////////////////////////////////////////////////////
478 // Transforming contained values
479 /////////////////////////////////////////////////////////////////////////
480
481 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
482 /// contained [`Ok`] value, leaving an [`Err`] value untouched.
483 ///
484 /// This function can be used to compose the results of two functions.
485 ///
486 /// # Examples
487 ///
488 /// Print the numbers on each line of a string multiplied by two.
489 ///
490 /// ```
491 /// let line = "1\n2\n3\n4\n";
492 ///
493 /// for num in line.lines() {
494 /// match num.parse::<i32>().map(|i| i * 2) {
495 /// Ok(n) => println!("{}", n),
496 /// Err(..) => {}
497 /// }
498 /// }
499 /// ```
500 #[inline]
501 #[stable(feature = "rust1", since = "1.0.0")]
502 pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U, E> {
503 match self {
504 Ok(t) => Ok(op(t)),
505 Err(e) => Err(e),
506 }
507 }
508
509 /// Applies a function to the contained value (if [`Ok`]),
510 /// or returns the provided default (if [`Err`]).
511 ///
512 /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
513 /// the result of a function call, it is recommended to use [`map_or_else`],
514 /// which is lazily evaluated.
515 ///
516 /// [`map_or_else`]: Result::map_or_else
517 ///
518 /// # Examples
519 ///
520 /// ```
521 /// let x: Result<_, &str> = Ok("foo");
522 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
523 ///
524 /// let x: Result<&str, _> = Err("bar");
525 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
526 /// ```
527 #[inline]
528 #[stable(feature = "result_map_or", since = "1.41.0")]
529 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
530 match self {
531 Ok(t) => f(t),
532 Err(_) => default,
533 }
534 }
535
536 /// Maps a `Result<T, E>` to `U` by applying a function to a
537 /// contained [`Ok`] value, or a fallback function to a
538 /// contained [`Err`] value.
539 ///
540 /// This function can be used to unpack a successful result
541 /// while handling an error.
542 ///
543 ///
544 /// # Examples
545 ///
546 /// Basic usage:
547 ///
548 /// ```
549 /// let k = 21;
550 ///
551 /// let x : Result<_, &str> = Ok("foo");
552 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);
553 ///
554 /// let x : Result<&str, _> = Err("bar");
555 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
556 /// ```
557 #[inline]
558 #[stable(feature = "result_map_or_else", since = "1.41.0")]
559 pub fn map_or_else<U, D: FnOnce(E) -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
560 match self {
561 Ok(t) => f(t),
562 Err(e) => default(e),
563 }
564 }
565
566 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
567 /// contained [`Err`] value, leaving an [`Ok`] value untouched.
568 ///
569 /// This function can be used to pass through a successful result while handling
570 /// an error.
571 ///
572 ///
573 /// # Examples
574 ///
575 /// Basic usage:
576 ///
577 /// ```
578 /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
579 ///
580 /// let x: Result<u32, u32> = Ok(2);
581 /// assert_eq!(x.map_err(stringify), Ok(2));
582 ///
583 /// let x: Result<u32, u32> = Err(13);
584 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
585 /// ```
586 #[inline]
587 #[stable(feature = "rust1", since = "1.0.0")]
588 pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T, F> {
589 match self {
590 Ok(t) => Ok(t),
591 Err(e) => Err(op(e)),
592 }
593 }
594
595 /////////////////////////////////////////////////////////////////////////
596 // Iterator constructors
597 /////////////////////////////////////////////////////////////////////////
598
599 /// Returns an iterator over the possibly contained value.
600 ///
601 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
602 ///
603 /// # Examples
604 ///
605 /// Basic usage:
606 ///
607 /// ```
608 /// let x: Result<u32, &str> = Ok(7);
609 /// assert_eq!(x.iter().next(), Some(&7));
610 ///
611 /// let x: Result<u32, &str> = Err("nothing!");
612 /// assert_eq!(x.iter().next(), None);
613 /// ```
614 #[inline]
615 #[stable(feature = "rust1", since = "1.0.0")]
616 pub fn iter(&self) -> Iter<'_, T> {
617 Iter { inner: self.as_ref().ok() }
618 }
619
620 /// Returns a mutable iterator over the possibly contained value.
621 ///
622 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
623 ///
624 /// # Examples
625 ///
626 /// Basic usage:
627 ///
628 /// ```
629 /// let mut x: Result<u32, &str> = Ok(7);
630 /// match x.iter_mut().next() {
631 /// Some(v) => *v = 40,
632 /// None => {},
633 /// }
634 /// assert_eq!(x, Ok(40));
635 ///
636 /// let mut x: Result<u32, &str> = Err("nothing!");
637 /// assert_eq!(x.iter_mut().next(), None);
638 /// ```
639 #[inline]
640 #[stable(feature = "rust1", since = "1.0.0")]
641 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
642 IterMut { inner: self.as_mut().ok() }
643 }
644
645 ////////////////////////////////////////////////////////////////////////
646 // Boolean operations on the values, eager and lazy
647 /////////////////////////////////////////////////////////////////////////
648
649 /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
650 ///
651 ///
652 /// # Examples
653 ///
654 /// Basic usage:
655 ///
656 /// ```
657 /// let x: Result<u32, &str> = Ok(2);
658 /// let y: Result<&str, &str> = Err("late error");
659 /// assert_eq!(x.and(y), Err("late error"));
660 ///
661 /// let x: Result<u32, &str> = Err("early error");
662 /// let y: Result<&str, &str> = Ok("foo");
663 /// assert_eq!(x.and(y), Err("early error"));
664 ///
665 /// let x: Result<u32, &str> = Err("not a 2");
666 /// let y: Result<&str, &str> = Err("late error");
667 /// assert_eq!(x.and(y), Err("not a 2"));
668 ///
669 /// let x: Result<u32, &str> = Ok(2);
670 /// let y: Result<&str, &str> = Ok("different result type");
671 /// assert_eq!(x.and(y), Ok("different result type"));
672 /// ```
673 #[inline]
674 #[stable(feature = "rust1", since = "1.0.0")]
675 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
676 match self {
677 Ok(_) => res,
678 Err(e) => Err(e),
679 }
680 }
681
682 /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
683 ///
684 ///
685 /// This function can be used for control flow based on `Result` values.
686 ///
687 /// # Examples
688 ///
689 /// Basic usage:
690 ///
691 /// ```
692 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
693 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
694 ///
695 /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
696 /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
697 /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
698 /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
699 /// ```
700 #[inline]
701 #[stable(feature = "rust1", since = "1.0.0")]
702 pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
703 match self {
704 Ok(t) => op(t),
705 Err(e) => Err(e),
706 }
707 }
708
709 /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
710 ///
711 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
712 /// result of a function call, it is recommended to use [`or_else`], which is
713 /// lazily evaluated.
714 ///
715 /// [`or_else`]: Result::or_else
716 ///
717 /// # Examples
718 ///
719 /// Basic usage:
720 ///
721 /// ```
722 /// let x: Result<u32, &str> = Ok(2);
723 /// let y: Result<u32, &str> = Err("late error");
724 /// assert_eq!(x.or(y), Ok(2));
725 ///
726 /// let x: Result<u32, &str> = Err("early error");
727 /// let y: Result<u32, &str> = Ok(2);
728 /// assert_eq!(x.or(y), Ok(2));
729 ///
730 /// let x: Result<u32, &str> = Err("not a 2");
731 /// let y: Result<u32, &str> = Err("late error");
732 /// assert_eq!(x.or(y), Err("late error"));
733 ///
734 /// let x: Result<u32, &str> = Ok(2);
735 /// let y: Result<u32, &str> = Ok(100);
736 /// assert_eq!(x.or(y), Ok(2));
737 /// ```
738 #[inline]
739 #[stable(feature = "rust1", since = "1.0.0")]
740 pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
741 match self {
742 Ok(v) => Ok(v),
743 Err(_) => res,
744 }
745 }
746
747 /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
748 ///
749 /// This function can be used for control flow based on result values.
750 ///
751 ///
752 /// # Examples
753 ///
754 /// Basic usage:
755 ///
756 /// ```
757 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
758 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
759 ///
760 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
761 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
762 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
763 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
764 /// ```
765 #[inline]
766 #[stable(feature = "rust1", since = "1.0.0")]
767 pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
768 match self {
769 Ok(t) => Ok(t),
770 Err(e) => op(e),
771 }
772 }
773
774 /// Returns the contained [`Ok`] value or a provided default.
775 ///
776 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
777 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
778 /// which is lazily evaluated.
779 ///
780 /// [`unwrap_or_else`]: Result::unwrap_or_else
781 ///
782 /// # Examples
783 ///
784 /// Basic usage:
785 ///
786 /// ```
787 /// let default = 2;
788 /// let x: Result<u32, &str> = Ok(9);
789 /// assert_eq!(x.unwrap_or(default), 9);
790 ///
791 /// let x: Result<u32, &str> = Err("error");
792 /// assert_eq!(x.unwrap_or(default), default);
793 /// ```
794 #[inline]
795 #[stable(feature = "rust1", since = "1.0.0")]
796 pub fn unwrap_or(self, default: T) -> T {
797 match self {
798 Ok(t) => t,
799 Err(_) => default,
800 }
801 }
802
803 /// Returns the contained [`Ok`] value or computes it from a closure.
804 ///
805 ///
806 /// # Examples
807 ///
808 /// Basic usage:
809 ///
810 /// ```
811 /// fn count(x: &str) -> usize { x.len() }
812 ///
813 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
814 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
815 /// ```
816 #[inline]
817 #[stable(feature = "rust1", since = "1.0.0")]
818 pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
819 match self {
820 Ok(t) => t,
821 Err(e) => op(e),
822 }
823 }
824
825 /// Returns the contained [`Ok`] value, consuming the `self` value,
826 /// without checking that the value is not an [`Err`].
827 ///
828 /// # Safety
829 ///
830 /// Calling this method on an [`Err`] is *[undefined behavior]*.
831 ///
832 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
833 ///
834 /// # Examples
835 ///
836 /// ```
837 /// #![feature(option_result_unwrap_unchecked)]
838 /// let x: Result<u32, &str> = Ok(2);
839 /// assert_eq!(unsafe { x.unwrap_unchecked() }, 2);
840 /// ```
841 ///
842 /// ```no_run
843 /// #![feature(option_result_unwrap_unchecked)]
844 /// let x: Result<u32, &str> = Err("emergency failure");
845 /// unsafe { x.unwrap_unchecked(); } // Undefined behavior!
846 /// ```
847 #[inline]
848 #[track_caller]
849 #[unstable(feature = "option_result_unwrap_unchecked", reason = "newly added", issue = "81383")]
850 pub unsafe fn unwrap_unchecked(self) -> T {
851 debug_assert!(self.is_ok());
852 match self {
853 Ok(t) => t,
854 // SAFETY: the safety contract must be upheld by the caller.
855 Err(_) => unsafe { hint::unreachable_unchecked() },
856 }
857 }
858
859 /// Returns the contained [`Err`] value, consuming the `self` value,
860 /// without checking that the value is not an [`Ok`].
861 ///
862 /// # Safety
863 ///
864 /// Calling this method on an [`Ok`] is *[undefined behavior]*.
865 ///
866 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
867 ///
868 /// # Examples
869 ///
870 /// ```no_run
871 /// #![feature(option_result_unwrap_unchecked)]
872 /// let x: Result<u32, &str> = Ok(2);
873 /// unsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
874 /// ```
875 ///
876 /// ```
877 /// #![feature(option_result_unwrap_unchecked)]
878 /// let x: Result<u32, &str> = Err("emergency failure");
879 /// assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure");
880 /// ```
881 #[inline]
882 #[track_caller]
883 #[unstable(feature = "option_result_unwrap_unchecked", reason = "newly added", issue = "81383")]
884 pub unsafe fn unwrap_err_unchecked(self) -> E {
885 debug_assert!(self.is_err());
886 match self {
887 // SAFETY: the safety contract must be upheld by the caller.
888 Ok(_) => unsafe { hint::unreachable_unchecked() },
889 Err(e) => e,
890 }
891 }
892 }
893
894 impl<T: Copy, E> Result<&T, E> {
895 /// Maps a `Result<&T, E>` to a `Result<T, E>` by copying the contents of the
896 /// `Ok` part.
897 ///
898 /// # Examples
899 ///
900 /// ```
901 /// #![feature(result_copied)]
902 /// let val = 12;
903 /// let x: Result<&i32, i32> = Ok(&val);
904 /// assert_eq!(x, Ok(&12));
905 /// let copied = x.copied();
906 /// assert_eq!(copied, Ok(12));
907 /// ```
908 #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
909 pub fn copied(self) -> Result<T, E> {
910 self.map(|&t| t)
911 }
912 }
913
914 impl<T: Copy, E> Result<&mut T, E> {
915 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by copying the contents of the
916 /// `Ok` part.
917 ///
918 /// # Examples
919 ///
920 /// ```
921 /// #![feature(result_copied)]
922 /// let mut val = 12;
923 /// let x: Result<&mut i32, i32> = Ok(&mut val);
924 /// assert_eq!(x, Ok(&mut 12));
925 /// let copied = x.copied();
926 /// assert_eq!(copied, Ok(12));
927 /// ```
928 #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
929 pub fn copied(self) -> Result<T, E> {
930 self.map(|&mut t| t)
931 }
932 }
933
934 impl<T: Clone, E> Result<&T, E> {
935 /// Maps a `Result<&T, E>` to a `Result<T, E>` by cloning the contents of the
936 /// `Ok` part.
937 ///
938 /// # Examples
939 ///
940 /// ```
941 /// #![feature(result_cloned)]
942 /// let val = 12;
943 /// let x: Result<&i32, i32> = Ok(&val);
944 /// assert_eq!(x, Ok(&12));
945 /// let cloned = x.cloned();
946 /// assert_eq!(cloned, Ok(12));
947 /// ```
948 #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
949 pub fn cloned(self) -> Result<T, E> {
950 self.map(|t| t.clone())
951 }
952 }
953
954 impl<T: Clone, E> Result<&mut T, E> {
955 /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by cloning the contents of the
956 /// `Ok` part.
957 ///
958 /// # Examples
959 ///
960 /// ```
961 /// #![feature(result_cloned)]
962 /// let mut val = 12;
963 /// let x: Result<&mut i32, i32> = Ok(&mut val);
964 /// assert_eq!(x, Ok(&mut 12));
965 /// let cloned = x.cloned();
966 /// assert_eq!(cloned, Ok(12));
967 /// ```
968 #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
969 pub fn cloned(self) -> Result<T, E> {
970 self.map(|t| t.clone())
971 }
972 }
973
974 impl<T, E: fmt::Debug> Result<T, E> {
975 /// Returns the contained [`Ok`] value, consuming the `self` value.
976 ///
977 /// # Panics
978 ///
979 /// Panics if the value is an [`Err`], with a panic message including the
980 /// passed message, and the content of the [`Err`].
981 ///
982 ///
983 /// # Examples
984 ///
985 /// Basic usage:
986 ///
987 /// ```{.should_panic}
988 /// let x: Result<u32, &str> = Err("emergency failure");
989 /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
990 /// ```
991 #[inline]
992 #[track_caller]
993 #[stable(feature = "result_expect", since = "1.4.0")]
994 pub fn expect(self, msg: &str) -> T {
995 match self {
996 Ok(t) => t,
997 Err(e) => unwrap_failed(msg, &e),
998 }
999 }
1000
1001 /// Returns the contained [`Ok`] value, consuming the `self` value.
1002 ///
1003 /// Because this function may panic, its use is generally discouraged.
1004 /// Instead, prefer to use pattern matching and handle the [`Err`]
1005 /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
1006 /// [`unwrap_or_default`].
1007 ///
1008 /// [`unwrap_or`]: Result::unwrap_or
1009 /// [`unwrap_or_else`]: Result::unwrap_or_else
1010 /// [`unwrap_or_default`]: Result::unwrap_or_default
1011 ///
1012 /// # Panics
1013 ///
1014 /// Panics if the value is an [`Err`], with a panic message provided by the
1015 /// [`Err`]'s value.
1016 ///
1017 ///
1018 /// # Examples
1019 ///
1020 /// Basic usage:
1021 ///
1022 /// ```
1023 /// let x: Result<u32, &str> = Ok(2);
1024 /// assert_eq!(x.unwrap(), 2);
1025 /// ```
1026 ///
1027 /// ```{.should_panic}
1028 /// let x: Result<u32, &str> = Err("emergency failure");
1029 /// x.unwrap(); // panics with `emergency failure`
1030 /// ```
1031 #[inline]
1032 #[track_caller]
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 pub fn unwrap(self) -> T {
1035 match self {
1036 Ok(t) => t,
1037 Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e),
1038 }
1039 }
1040 }
1041
1042 impl<T: fmt::Debug, E> Result<T, E> {
1043 /// Returns the contained [`Err`] value, consuming the `self` value.
1044 ///
1045 /// # Panics
1046 ///
1047 /// Panics if the value is an [`Ok`], with a panic message including the
1048 /// passed message, and the content of the [`Ok`].
1049 ///
1050 ///
1051 /// # Examples
1052 ///
1053 /// Basic usage:
1054 ///
1055 /// ```{.should_panic}
1056 /// let x: Result<u32, &str> = Ok(10);
1057 /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
1058 /// ```
1059 #[inline]
1060 #[track_caller]
1061 #[stable(feature = "result_expect_err", since = "1.17.0")]
1062 pub fn expect_err(self, msg: &str) -> E {
1063 match self {
1064 Ok(t) => unwrap_failed(msg, &t),
1065 Err(e) => e,
1066 }
1067 }
1068
1069 /// Returns the contained [`Err`] value, consuming the `self` value.
1070 ///
1071 /// # Panics
1072 ///
1073 /// Panics if the value is an [`Ok`], with a custom panic message provided
1074 /// by the [`Ok`]'s value.
1075 ///
1076 /// # Examples
1077 ///
1078 /// ```{.should_panic}
1079 /// let x: Result<u32, &str> = Ok(2);
1080 /// x.unwrap_err(); // panics with `2`
1081 /// ```
1082 ///
1083 /// ```
1084 /// let x: Result<u32, &str> = Err("emergency failure");
1085 /// assert_eq!(x.unwrap_err(), "emergency failure");
1086 /// ```
1087 #[inline]
1088 #[track_caller]
1089 #[stable(feature = "rust1", since = "1.0.0")]
1090 pub fn unwrap_err(self) -> E {
1091 match self {
1092 Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t),
1093 Err(e) => e,
1094 }
1095 }
1096 }
1097
1098 impl<T: Default, E> Result<T, E> {
1099 /// Returns the contained [`Ok`] value or a default
1100 ///
1101 /// Consumes the `self` argument then, if [`Ok`], returns the contained
1102 /// value, otherwise if [`Err`], returns the default value for that
1103 /// type.
1104 ///
1105 /// # Examples
1106 ///
1107 /// Converts a string to an integer, turning poorly-formed strings
1108 /// into 0 (the default value for integers). [`parse`] converts
1109 /// a string to any other type that implements [`FromStr`], returning an
1110 /// [`Err`] on error.
1111 ///
1112 /// ```
1113 /// let good_year_from_input = "1909";
1114 /// let bad_year_from_input = "190blarg";
1115 /// let good_year = good_year_from_input.parse().unwrap_or_default();
1116 /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
1117 ///
1118 /// assert_eq!(1909, good_year);
1119 /// assert_eq!(0, bad_year);
1120 /// ```
1121 ///
1122 /// [`parse`]: str::parse
1123 /// [`FromStr`]: crate::str::FromStr
1124 #[inline]
1125 #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
1126 pub fn unwrap_or_default(self) -> T {
1127 match self {
1128 Ok(x) => x,
1129 Err(_) => Default::default(),
1130 }
1131 }
1132 }
1133
1134 #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
1135 impl<T, E: Into<!>> Result<T, E> {
1136 /// Returns the contained [`Ok`] value, but never panics.
1137 ///
1138 /// Unlike [`unwrap`], this method is known to never panic on the
1139 /// result types it is implemented for. Therefore, it can be used
1140 /// instead of `unwrap` as a maintainability safeguard that will fail
1141 /// to compile if the error type of the `Result` is later changed
1142 /// to an error that can actually occur.
1143 ///
1144 /// [`unwrap`]: Result::unwrap
1145 ///
1146 /// # Examples
1147 ///
1148 /// Basic usage:
1149 ///
1150 /// ```
1151 /// # #![feature(never_type)]
1152 /// # #![feature(unwrap_infallible)]
1153 ///
1154 /// fn only_good_news() -> Result<String, !> {
1155 /// Ok("this is fine".into())
1156 /// }
1157 ///
1158 /// let s: String = only_good_news().into_ok();
1159 /// println!("{}", s);
1160 /// ```
1161 #[inline]
1162 pub fn into_ok(self) -> T {
1163 match self {
1164 Ok(x) => x,
1165 Err(e) => e.into(),
1166 }
1167 }
1168 }
1169
1170 impl<T: Deref, E> Result<T, E> {
1171 /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&<T as Deref>::Target, &E>`.
1172 ///
1173 /// Coerces the [`Ok`] variant of the original [`Result`] via [`Deref`](crate::ops::Deref)
1174 /// and returns the new [`Result`].
1175 ///
1176 /// # Examples
1177 ///
1178 /// ```
1179 /// let x: Result<String, u32> = Ok("hello".to_string());
1180 /// let y: Result<&str, &u32> = Ok("hello");
1181 /// assert_eq!(x.as_deref(), y);
1182 ///
1183 /// let x: Result<String, u32> = Err(42);
1184 /// let y: Result<&str, &u32> = Err(&42);
1185 /// assert_eq!(x.as_deref(), y);
1186 /// ```
1187 #[stable(feature = "inner_deref", since = "1.47.0")]
1188 pub fn as_deref(&self) -> Result<&T::Target, &E> {
1189 self.as_ref().map(|t| t.deref())
1190 }
1191 }
1192
1193 impl<T: DerefMut, E> Result<T, E> {
1194 /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut <T as DerefMut>::Target, &mut E>`.
1195 ///
1196 /// Coerces the [`Ok`] variant of the original [`Result`] via [`DerefMut`](crate::ops::DerefMut)
1197 /// and returns the new [`Result`].
1198 ///
1199 /// # Examples
1200 ///
1201 /// ```
1202 /// let mut s = "HELLO".to_string();
1203 /// let mut x: Result<String, u32> = Ok("hello".to_string());
1204 /// let y: Result<&mut str, &mut u32> = Ok(&mut s);
1205 /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
1206 ///
1207 /// let mut i = 42;
1208 /// let mut x: Result<String, u32> = Err(42);
1209 /// let y: Result<&mut str, &mut u32> = Err(&mut i);
1210 /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
1211 /// ```
1212 #[stable(feature = "inner_deref", since = "1.47.0")]
1213 pub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E> {
1214 self.as_mut().map(|t| t.deref_mut())
1215 }
1216 }
1217
1218 impl<T, E> Result<Option<T>, E> {
1219 /// Transposes a `Result` of an `Option` into an `Option` of a `Result`.
1220 ///
1221 /// `Ok(None)` will be mapped to `None`.
1222 /// `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`.
1223 ///
1224 /// # Examples
1225 ///
1226 /// ```
1227 /// #[derive(Debug, Eq, PartialEq)]
1228 /// struct SomeErr;
1229 ///
1230 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1231 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1232 /// assert_eq!(x.transpose(), y);
1233 /// ```
1234 #[inline]
1235 #[stable(feature = "transpose_result", since = "1.33.0")]
1236 pub fn transpose(self) -> Option<Result<T, E>> {
1237 match self {
1238 Ok(Some(x)) => Some(Ok(x)),
1239 Ok(None) => None,
1240 Err(e) => Some(Err(e)),
1241 }
1242 }
1243 }
1244
1245 impl<T, E> Result<Result<T, E>, E> {
1246 /// Converts from `Result<Result<T, E>, E>` to `Result<T, E>`
1247 ///
1248 /// # Examples
1249 ///
1250 /// Basic usage:
1251 ///
1252 /// ```
1253 /// #![feature(result_flattening)]
1254 /// let x: Result<Result<&'static str, u32>, u32> = Ok(Ok("hello"));
1255 /// assert_eq!(Ok("hello"), x.flatten());
1256 ///
1257 /// let x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));
1258 /// assert_eq!(Err(6), x.flatten());
1259 ///
1260 /// let x: Result<Result<&'static str, u32>, u32> = Err(6);
1261 /// assert_eq!(Err(6), x.flatten());
1262 /// ```
1263 ///
1264 /// Flattening only removes one level of nesting at a time:
1265 ///
1266 /// ```
1267 /// #![feature(result_flattening)]
1268 /// let x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok("hello")));
1269 /// assert_eq!(Ok(Ok("hello")), x.flatten());
1270 /// assert_eq!(Ok("hello"), x.flatten().flatten());
1271 /// ```
1272 #[inline]
1273 #[unstable(feature = "result_flattening", issue = "70142")]
1274 pub fn flatten(self) -> Result<T, E> {
1275 self.and_then(convert::identity)
1276 }
1277 }
1278
1279 // This is a separate function to reduce the code size of the methods
1280 #[inline(never)]
1281 #[cold]
1282 #[track_caller]
1283 fn unwrap_failed(msg: &str, error: &dyn fmt::Debug) -> ! {
1284 panic!("{}: {:?}", msg, error)
1285 }
1286
1287 /////////////////////////////////////////////////////////////////////////////
1288 // Trait implementations
1289 /////////////////////////////////////////////////////////////////////////////
1290
1291 #[stable(feature = "rust1", since = "1.0.0")]
1292 impl<T: Clone, E: Clone> Clone for Result<T, E> {
1293 #[inline]
1294 fn clone(&self) -> Self {
1295 match self {
1296 Ok(x) => Ok(x.clone()),
1297 Err(x) => Err(x.clone()),
1298 }
1299 }
1300
1301 #[inline]
1302 fn clone_from(&mut self, source: &Self) {
1303 match (self, source) {
1304 (Ok(to), Ok(from)) => to.clone_from(from),
1305 (Err(to), Err(from)) => to.clone_from(from),
1306 (to, from) => *to = from.clone(),
1307 }
1308 }
1309 }
1310
1311 #[stable(feature = "rust1", since = "1.0.0")]
1312 impl<T, E> IntoIterator for Result<T, E> {
1313 type Item = T;
1314 type IntoIter = IntoIter<T>;
1315
1316 /// Returns a consuming iterator over the possibly contained value.
1317 ///
1318 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
1319 ///
1320 /// # Examples
1321 ///
1322 /// Basic usage:
1323 ///
1324 /// ```
1325 /// let x: Result<u32, &str> = Ok(5);
1326 /// let v: Vec<u32> = x.into_iter().collect();
1327 /// assert_eq!(v, [5]);
1328 ///
1329 /// let x: Result<u32, &str> = Err("nothing!");
1330 /// let v: Vec<u32> = x.into_iter().collect();
1331 /// assert_eq!(v, []);
1332 /// ```
1333 #[inline]
1334 fn into_iter(self) -> IntoIter<T> {
1335 IntoIter { inner: self.ok() }
1336 }
1337 }
1338
1339 #[stable(since = "1.4.0", feature = "result_iter")]
1340 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
1341 type Item = &'a T;
1342 type IntoIter = Iter<'a, T>;
1343
1344 fn into_iter(self) -> Iter<'a, T> {
1345 self.iter()
1346 }
1347 }
1348
1349 #[stable(since = "1.4.0", feature = "result_iter")]
1350 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
1351 type Item = &'a mut T;
1352 type IntoIter = IterMut<'a, T>;
1353
1354 fn into_iter(self) -> IterMut<'a, T> {
1355 self.iter_mut()
1356 }
1357 }
1358
1359 /////////////////////////////////////////////////////////////////////////////
1360 // The Result Iterators
1361 /////////////////////////////////////////////////////////////////////////////
1362
1363 /// An iterator over a reference to the [`Ok`] variant of a [`Result`].
1364 ///
1365 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1366 ///
1367 /// Created by [`Result::iter`].
1368 #[derive(Debug)]
1369 #[stable(feature = "rust1", since = "1.0.0")]
1370 pub struct Iter<'a, T: 'a> {
1371 inner: Option<&'a T>,
1372 }
1373
1374 #[stable(feature = "rust1", since = "1.0.0")]
1375 impl<'a, T> Iterator for Iter<'a, T> {
1376 type Item = &'a T;
1377
1378 #[inline]
1379 fn next(&mut self) -> Option<&'a T> {
1380 self.inner.take()
1381 }
1382 #[inline]
1383 fn size_hint(&self) -> (usize, Option<usize>) {
1384 let n = if self.inner.is_some() { 1 } else { 0 };
1385 (n, Some(n))
1386 }
1387 }
1388
1389 #[stable(feature = "rust1", since = "1.0.0")]
1390 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1391 #[inline]
1392 fn next_back(&mut self) -> Option<&'a T> {
1393 self.inner.take()
1394 }
1395 }
1396
1397 #[stable(feature = "rust1", since = "1.0.0")]
1398 impl<T> ExactSizeIterator for Iter<'_, T> {}
1399
1400 #[stable(feature = "fused", since = "1.26.0")]
1401 impl<T> FusedIterator for Iter<'_, T> {}
1402
1403 #[unstable(feature = "trusted_len", issue = "37572")]
1404 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1405
1406 #[stable(feature = "rust1", since = "1.0.0")]
1407 impl<T> Clone for Iter<'_, T> {
1408 #[inline]
1409 fn clone(&self) -> Self {
1410 Iter { inner: self.inner }
1411 }
1412 }
1413
1414 /// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
1415 ///
1416 /// Created by [`Result::iter_mut`].
1417 #[derive(Debug)]
1418 #[stable(feature = "rust1", since = "1.0.0")]
1419 pub struct IterMut<'a, T: 'a> {
1420 inner: Option<&'a mut T>,
1421 }
1422
1423 #[stable(feature = "rust1", since = "1.0.0")]
1424 impl<'a, T> Iterator for IterMut<'a, T> {
1425 type Item = &'a mut T;
1426
1427 #[inline]
1428 fn next(&mut self) -> Option<&'a mut T> {
1429 self.inner.take()
1430 }
1431 #[inline]
1432 fn size_hint(&self) -> (usize, Option<usize>) {
1433 let n = if self.inner.is_some() { 1 } else { 0 };
1434 (n, Some(n))
1435 }
1436 }
1437
1438 #[stable(feature = "rust1", since = "1.0.0")]
1439 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1440 #[inline]
1441 fn next_back(&mut self) -> Option<&'a mut T> {
1442 self.inner.take()
1443 }
1444 }
1445
1446 #[stable(feature = "rust1", since = "1.0.0")]
1447 impl<T> ExactSizeIterator for IterMut<'_, T> {}
1448
1449 #[stable(feature = "fused", since = "1.26.0")]
1450 impl<T> FusedIterator for IterMut<'_, T> {}
1451
1452 #[unstable(feature = "trusted_len", issue = "37572")]
1453 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1454
1455 /// An iterator over the value in a [`Ok`] variant of a [`Result`].
1456 ///
1457 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1458 ///
1459 /// This struct is created by the [`into_iter`] method on
1460 /// [`Result`] (provided by the [`IntoIterator`] trait).
1461 ///
1462 /// [`into_iter`]: IntoIterator::into_iter
1463 #[derive(Clone, Debug)]
1464 #[stable(feature = "rust1", since = "1.0.0")]
1465 pub struct IntoIter<T> {
1466 inner: Option<T>,
1467 }
1468
1469 #[stable(feature = "rust1", since = "1.0.0")]
1470 impl<T> Iterator for IntoIter<T> {
1471 type Item = T;
1472
1473 #[inline]
1474 fn next(&mut self) -> Option<T> {
1475 self.inner.take()
1476 }
1477 #[inline]
1478 fn size_hint(&self) -> (usize, Option<usize>) {
1479 let n = if self.inner.is_some() { 1 } else { 0 };
1480 (n, Some(n))
1481 }
1482 }
1483
1484 #[stable(feature = "rust1", since = "1.0.0")]
1485 impl<T> DoubleEndedIterator for IntoIter<T> {
1486 #[inline]
1487 fn next_back(&mut self) -> Option<T> {
1488 self.inner.take()
1489 }
1490 }
1491
1492 #[stable(feature = "rust1", since = "1.0.0")]
1493 impl<T> ExactSizeIterator for IntoIter<T> {}
1494
1495 #[stable(feature = "fused", since = "1.26.0")]
1496 impl<T> FusedIterator for IntoIter<T> {}
1497
1498 #[unstable(feature = "trusted_len", issue = "37572")]
1499 unsafe impl<A> TrustedLen for IntoIter<A> {}
1500
1501 /////////////////////////////////////////////////////////////////////////////
1502 // FromIterator
1503 /////////////////////////////////////////////////////////////////////////////
1504
1505 #[stable(feature = "rust1", since = "1.0.0")]
1506 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
1507 /// Takes each element in the `Iterator`: if it is an `Err`, no further
1508 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
1509 /// container with the values of each `Result` is returned.
1510 ///
1511 /// Here is an example which increments every integer in a vector,
1512 /// checking for overflow:
1513 ///
1514 /// ```
1515 /// let v = vec![1, 2];
1516 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1517 /// x.checked_add(1).ok_or("Overflow!")
1518 /// ).collect();
1519 /// assert_eq!(res, Ok(vec![2, 3]));
1520 /// ```
1521 ///
1522 /// Here is another example that tries to subtract one from another list
1523 /// of integers, this time checking for underflow:
1524 ///
1525 /// ```
1526 /// let v = vec![1, 2, 0];
1527 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1528 /// x.checked_sub(1).ok_or("Underflow!")
1529 /// ).collect();
1530 /// assert_eq!(res, Err("Underflow!"));
1531 /// ```
1532 ///
1533 /// Here is a variation on the previous example, showing that no
1534 /// further elements are taken from `iter` after the first `Err`.
1535 ///
1536 /// ```
1537 /// let v = vec![3, 2, 1, 10];
1538 /// let mut shared = 0;
1539 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {
1540 /// shared += x;
1541 /// x.checked_sub(2).ok_or("Underflow!")
1542 /// }).collect();
1543 /// assert_eq!(res, Err("Underflow!"));
1544 /// assert_eq!(shared, 6);
1545 /// ```
1546 ///
1547 /// Since the third element caused an underflow, no further elements were taken,
1548 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1549 #[inline]
1550 fn from_iter<I: IntoIterator<Item = Result<A, E>>>(iter: I) -> Result<V, E> {
1551 // FIXME(#11084): This could be replaced with Iterator::scan when this
1552 // performance bug is closed.
1553
1554 iter::process_results(iter.into_iter(), |i| i.collect())
1555 }
1556 }
1557
1558 #[unstable(feature = "try_trait", issue = "42327")]
1559 impl<T, E> ops::Try for Result<T, E> {
1560 type Ok = T;
1561 type Error = E;
1562
1563 #[inline]
1564 fn into_result(self) -> Self {
1565 self
1566 }
1567
1568 #[inline]
1569 fn from_ok(v: T) -> Self {
1570 Ok(v)
1571 }
1572
1573 #[inline]
1574 fn from_error(v: E) -> Self {
1575 Err(v)
1576 }
1577 }