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