]> git.proxmox.com Git - rustc.git/blob - src/libcore/result.rs
New upstream version 1.31.0~beta.4+dfsg1
[rustc.git] / src / libcore / result.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Error handling with the `Result` type.
12 //!
13 //! [`Result<T, E>`][`Result`] is the type used for returning and propagating
14 //! errors. It is an enum with the variants, [`Ok(T)`], representing
15 //! success and containing a value, and [`Err(E)`], representing error
16 //! and containing an error value.
17 //!
18 //! ```
19 //! # #[allow(dead_code)]
20 //! enum Result<T, E> {
21 //! Ok(T),
22 //! Err(E),
23 //! }
24 //! ```
25 //!
26 //! Functions return [`Result`] whenever errors are expected and
27 //! recoverable. In the `std` crate, [`Result`] is most prominently used
28 //! for [I/O](../../std/io/index.html).
29 //!
30 //! A simple function returning [`Result`] might be
31 //! defined and used like so:
32 //!
33 //! ```
34 //! #[derive(Debug)]
35 //! enum Version { Version1, Version2 }
36 //!
37 //! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
38 //! match header.get(0) {
39 //! None => Err("invalid header length"),
40 //! Some(&1) => Ok(Version::Version1),
41 //! Some(&2) => Ok(Version::Version2),
42 //! Some(_) => Err("invalid version"),
43 //! }
44 //! }
45 //!
46 //! let version = parse_version(&[1, 2, 3, 4]);
47 //! match version {
48 //! Ok(v) => println!("working with version: {:?}", v),
49 //! Err(e) => println!("error parsing header: {:?}", e),
50 //! }
51 //! ```
52 //!
53 //! Pattern matching on [`Result`]s is clear and straightforward for
54 //! simple cases, but [`Result`] comes with some convenience methods
55 //! that make working with it more succinct.
56 //!
57 //! ```
58 //! let good_result: Result<i32, i32> = Ok(10);
59 //! let bad_result: Result<i32, i32> = Err(10);
60 //!
61 //! // The `is_ok` and `is_err` methods do what they say.
62 //! assert!(good_result.is_ok() && !good_result.is_err());
63 //! assert!(bad_result.is_err() && !bad_result.is_ok());
64 //!
65 //! // `map` consumes the `Result` and produces another.
66 //! let good_result: Result<i32, i32> = good_result.map(|i| i + 1);
67 //! let bad_result: Result<i32, i32> = bad_result.map(|i| i - 1);
68 //!
69 //! // Use `and_then` to continue the computation.
70 //! let good_result: Result<bool, i32> = good_result.and_then(|i| Ok(i == 11));
71 //!
72 //! // Use `or_else` to handle the error.
73 //! let bad_result: Result<i32, i32> = bad_result.or_else(|i| Ok(i + 20));
74 //!
75 //! // Consume the result and return the contents with `unwrap`.
76 //! let final_awesome_result = good_result.unwrap();
77 //! ```
78 //!
79 //! # Results must be used
80 //!
81 //! A common problem with using return values to indicate errors is
82 //! that it is easy to ignore the return value, thus failing to handle
83 //! the error. [`Result`] is annotated with the `#[must_use]` attribute,
84 //! which will cause the compiler to issue a warning when a Result
85 //! value is ignored. This makes [`Result`] especially useful with
86 //! functions that may encounter errors but don't otherwise return a
87 //! useful value.
88 //!
89 //! Consider the [`write_all`] method defined for I/O types
90 //! by the [`Write`] trait:
91 //!
92 //! ```
93 //! use std::io;
94 //!
95 //! trait Write {
96 //! fn write_all(&mut self, bytes: &[u8]) -> Result<(), io::Error>;
97 //! }
98 //! ```
99 //!
100 //! *Note: The actual definition of [`Write`] uses [`io::Result`], which
101 //! is just a synonym for [`Result`]`<T, `[`io::Error`]`>`.*
102 //!
103 //! This method doesn't produce a value, but the write may
104 //! fail. It's crucial to handle the error case, and *not* write
105 //! something like this:
106 //!
107 //! ```no_run
108 //! # #![allow(unused_must_use)] // \o/
109 //! use std::fs::File;
110 //! use std::io::prelude::*;
111 //!
112 //! let mut file = File::create("valuable_data.txt").unwrap();
113 //! // If `write_all` errors, then we'll never know, because the return
114 //! // value is ignored.
115 //! file.write_all(b"important message");
116 //! ```
117 //!
118 //! If you *do* write that in Rust, the compiler will give you a
119 //! warning (by default, controlled by the `unused_must_use` lint).
120 //!
121 //! You might instead, if you don't want to handle the error, simply
122 //! assert success with [`expect`]. This will panic if the
123 //! write fails, providing a marginally useful message indicating why:
124 //!
125 //! ```{.no_run}
126 //! use std::fs::File;
127 //! use std::io::prelude::*;
128 //!
129 //! let mut file = File::create("valuable_data.txt").unwrap();
130 //! file.write_all(b"important message").expect("failed to write message");
131 //! ```
132 //!
133 //! You might also simply assert success:
134 //!
135 //! ```{.no_run}
136 //! # use std::fs::File;
137 //! # use std::io::prelude::*;
138 //! # let mut file = File::create("valuable_data.txt").unwrap();
139 //! assert!(file.write_all(b"important message").is_ok());
140 //! ```
141 //!
142 //! Or propagate the error up the call stack with [`?`]:
143 //!
144 //! ```
145 //! # use std::fs::File;
146 //! # use std::io::prelude::*;
147 //! # use std::io;
148 //! # #[allow(dead_code)]
149 //! fn write_message() -> io::Result<()> {
150 //! let mut file = File::create("valuable_data.txt")?;
151 //! file.write_all(b"important message")?;
152 //! Ok(())
153 //! }
154 //! ```
155 //!
156 //! # The question mark operator, `?`
157 //!
158 //! When writing code that calls many functions that return the
159 //! [`Result`] type, the error handling can be tedious. The question mark
160 //! operator, [`?`], hides some of the boilerplate of propagating errors
161 //! up the call stack.
162 //!
163 //! It replaces this:
164 //!
165 //! ```
166 //! # #![allow(dead_code)]
167 //! use std::fs::File;
168 //! use std::io::prelude::*;
169 //! use std::io;
170 //!
171 //! struct Info {
172 //! name: String,
173 //! age: i32,
174 //! rating: i32,
175 //! }
176 //!
177 //! fn write_info(info: &Info) -> io::Result<()> {
178 //! // Early return on error
179 //! let mut file = match File::create("my_best_friends.txt") {
180 //! Err(e) => return Err(e),
181 //! Ok(f) => f,
182 //! };
183 //! if let Err(e) = file.write_all(format!("name: {}\n", info.name).as_bytes()) {
184 //! return Err(e)
185 //! }
186 //! if let Err(e) = file.write_all(format!("age: {}\n", info.age).as_bytes()) {
187 //! return Err(e)
188 //! }
189 //! if let Err(e) = file.write_all(format!("rating: {}\n", info.rating).as_bytes()) {
190 //! return Err(e)
191 //! }
192 //! Ok(())
193 //! }
194 //! ```
195 //!
196 //! With this:
197 //!
198 //! ```
199 //! # #![allow(dead_code)]
200 //! use std::fs::File;
201 //! use std::io::prelude::*;
202 //! use std::io;
203 //!
204 //! struct Info {
205 //! name: String,
206 //! age: i32,
207 //! rating: i32,
208 //! }
209 //!
210 //! fn write_info(info: &Info) -> io::Result<()> {
211 //! let mut file = File::create("my_best_friends.txt")?;
212 //! // Early return on error
213 //! file.write_all(format!("name: {}\n", info.name).as_bytes())?;
214 //! file.write_all(format!("age: {}\n", info.age).as_bytes())?;
215 //! file.write_all(format!("rating: {}\n", info.rating).as_bytes())?;
216 //! Ok(())
217 //! }
218 //! ```
219 //!
220 //! *It's much nicer!*
221 //!
222 //! Ending the expression with [`?`] will result in the unwrapped
223 //! success ([`Ok`]) value, unless the result is [`Err`], in which case
224 //! [`Err`] is returned early from the enclosing function.
225 //!
226 //! [`?`] can only be used in functions that return [`Result`] because of the
227 //! early return of [`Err`] that it provides.
228 //!
229 //! [`expect`]: enum.Result.html#method.expect
230 //! [`Write`]: ../../std/io/trait.Write.html
231 //! [`write_all`]: ../../std/io/trait.Write.html#method.write_all
232 //! [`io::Result`]: ../../std/io/type.Result.html
233 //! [`?`]: ../../std/macro.try.html
234 //! [`Result`]: enum.Result.html
235 //! [`Ok(T)`]: enum.Result.html#variant.Ok
236 //! [`Err(E)`]: enum.Result.html#variant.Err
237 //! [`io::Error`]: ../../std/io/struct.Error.html
238 //! [`Ok`]: enum.Result.html#variant.Ok
239 //! [`Err`]: enum.Result.html#variant.Err
240
241 #![stable(feature = "rust1", since = "1.0.0")]
242
243 use fmt;
244 use iter::{FromIterator, FusedIterator, TrustedLen};
245 use ops::{self, Deref};
246
247 /// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]).
248 ///
249 /// See the [`std::result`](index.html) module documentation for details.
250 ///
251 /// [`Ok`]: enum.Result.html#variant.Ok
252 /// [`Err`]: enum.Result.html#variant.Err
253 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
254 #[must_use = "this `Result` may be an `Err` variant, which should be handled"]
255 #[stable(feature = "rust1", since = "1.0.0")]
256 pub enum Result<T, E> {
257 /// Contains the success value
258 #[stable(feature = "rust1", since = "1.0.0")]
259 Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
260
261 /// Contains the error value
262 #[stable(feature = "rust1", since = "1.0.0")]
263 Err(#[stable(feature = "rust1", since = "1.0.0")] E),
264 }
265
266 /////////////////////////////////////////////////////////////////////////////
267 // Type implementation
268 /////////////////////////////////////////////////////////////////////////////
269
270 impl<T, E> Result<T, E> {
271 /////////////////////////////////////////////////////////////////////////
272 // Querying the contained values
273 /////////////////////////////////////////////////////////////////////////
274
275 /// Returns `true` if the result is [`Ok`].
276 ///
277 /// [`Ok`]: enum.Result.html#variant.Ok
278 ///
279 /// # Examples
280 ///
281 /// Basic usage:
282 ///
283 /// ```
284 /// let x: Result<i32, &str> = Ok(-3);
285 /// assert_eq!(x.is_ok(), true);
286 ///
287 /// let x: Result<i32, &str> = Err("Some error message");
288 /// assert_eq!(x.is_ok(), false);
289 /// ```
290 #[inline]
291 #[stable(feature = "rust1", since = "1.0.0")]
292 pub fn is_ok(&self) -> bool {
293 match *self {
294 Ok(_) => true,
295 Err(_) => false
296 }
297 }
298
299 /// Returns `true` if the result is [`Err`].
300 ///
301 /// [`Err`]: enum.Result.html#variant.Err
302 ///
303 /// # Examples
304 ///
305 /// Basic usage:
306 ///
307 /// ```
308 /// let x: Result<i32, &str> = Ok(-3);
309 /// assert_eq!(x.is_err(), false);
310 ///
311 /// let x: Result<i32, &str> = Err("Some error message");
312 /// assert_eq!(x.is_err(), true);
313 /// ```
314 #[inline]
315 #[stable(feature = "rust1", since = "1.0.0")]
316 pub fn is_err(&self) -> bool {
317 !self.is_ok()
318 }
319
320 /////////////////////////////////////////////////////////////////////////
321 // Adapter for each variant
322 /////////////////////////////////////////////////////////////////////////
323
324 /// Converts from `Result<T, E>` to [`Option<T>`].
325 ///
326 /// Converts `self` into an [`Option<T>`], consuming `self`,
327 /// and discarding the error, if any.
328 ///
329 /// [`Option<T>`]: ../../std/option/enum.Option.html
330 ///
331 /// # Examples
332 ///
333 /// Basic usage:
334 ///
335 /// ```
336 /// let x: Result<u32, &str> = Ok(2);
337 /// assert_eq!(x.ok(), Some(2));
338 ///
339 /// let x: Result<u32, &str> = Err("Nothing here");
340 /// assert_eq!(x.ok(), None);
341 /// ```
342 #[inline]
343 #[stable(feature = "rust1", since = "1.0.0")]
344 pub fn ok(self) -> Option<T> {
345 match self {
346 Ok(x) => Some(x),
347 Err(_) => None,
348 }
349 }
350
351 /// Converts from `Result<T, E>` to [`Option<E>`].
352 ///
353 /// Converts `self` into an [`Option<E>`], consuming `self`,
354 /// and discarding the success value, if any.
355 ///
356 /// [`Option<E>`]: ../../std/option/enum.Option.html
357 ///
358 /// # Examples
359 ///
360 /// Basic usage:
361 ///
362 /// ```
363 /// let x: Result<u32, &str> = Ok(2);
364 /// assert_eq!(x.err(), None);
365 ///
366 /// let x: Result<u32, &str> = Err("Nothing here");
367 /// assert_eq!(x.err(), Some("Nothing here"));
368 /// ```
369 #[inline]
370 #[stable(feature = "rust1", since = "1.0.0")]
371 pub fn err(self) -> Option<E> {
372 match self {
373 Ok(_) => None,
374 Err(x) => Some(x),
375 }
376 }
377
378 /////////////////////////////////////////////////////////////////////////
379 // Adapter for working with references
380 /////////////////////////////////////////////////////////////////////////
381
382 /// Converts from `Result<T, E>` to `Result<&T, &E>`.
383 ///
384 /// Produces a new `Result`, containing a reference
385 /// into the original, leaving the original in place.
386 ///
387 /// # Examples
388 ///
389 /// Basic usage:
390 ///
391 /// ```
392 /// let x: Result<u32, &str> = Ok(2);
393 /// assert_eq!(x.as_ref(), Ok(&2));
394 ///
395 /// let x: Result<u32, &str> = Err("Error");
396 /// assert_eq!(x.as_ref(), Err(&"Error"));
397 /// ```
398 #[inline]
399 #[stable(feature = "rust1", since = "1.0.0")]
400 pub fn as_ref(&self) -> Result<&T, &E> {
401 match *self {
402 Ok(ref x) => Ok(x),
403 Err(ref x) => Err(x),
404 }
405 }
406
407 /// Converts from `Result<T, E>` to `Result<&mut T, &mut E>`.
408 ///
409 /// # Examples
410 ///
411 /// Basic usage:
412 ///
413 /// ```
414 /// fn mutate(r: &mut Result<i32, i32>) {
415 /// match r.as_mut() {
416 /// Ok(v) => *v = 42,
417 /// Err(e) => *e = 0,
418 /// }
419 /// }
420 ///
421 /// let mut x: Result<i32, i32> = Ok(2);
422 /// mutate(&mut x);
423 /// assert_eq!(x.unwrap(), 42);
424 ///
425 /// let mut x: Result<i32, i32> = Err(13);
426 /// mutate(&mut x);
427 /// assert_eq!(x.unwrap_err(), 0);
428 /// ```
429 #[inline]
430 #[stable(feature = "rust1", since = "1.0.0")]
431 pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
432 match *self {
433 Ok(ref mut x) => Ok(x),
434 Err(ref mut x) => Err(x),
435 }
436 }
437
438 /////////////////////////////////////////////////////////////////////////
439 // Transforming contained values
440 /////////////////////////////////////////////////////////////////////////
441
442 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
443 /// contained [`Ok`] value, leaving an [`Err`] value untouched.
444 ///
445 /// This function can be used to compose the results of two functions.
446 ///
447 /// [`Ok`]: enum.Result.html#variant.Ok
448 /// [`Err`]: enum.Result.html#variant.Err
449 ///
450 /// # Examples
451 ///
452 /// Print the numbers on each line of a string multiplied by two.
453 ///
454 /// ```
455 /// let line = "1\n2\n3\n4\n";
456 ///
457 /// for num in line.lines() {
458 /// match num.parse::<i32>().map(|i| i * 2) {
459 /// Ok(n) => println!("{}", n),
460 /// Err(..) => {}
461 /// }
462 /// }
463 /// ```
464 #[inline]
465 #[stable(feature = "rust1", since = "1.0.0")]
466 pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
467 match self {
468 Ok(t) => Ok(op(t)),
469 Err(e) => Err(e)
470 }
471 }
472
473 /// Maps a `Result<T, E>` to `U` by applying a function to a
474 /// contained [`Ok`] value, or a fallback function to a
475 /// contained [`Err`] value.
476 ///
477 /// This function can be used to unpack a successful result
478 /// while handling an error.
479 ///
480 /// [`Ok`]: enum.Result.html#variant.Ok
481 /// [`Err`]: enum.Result.html#variant.Err
482 ///
483 /// # Examples
484 ///
485 /// Basic usage:
486 ///
487 /// ```
488 /// #![feature(result_map_or_else)]
489 /// let k = 21;
490 ///
491 /// let x : Result<_, &str> = Ok("foo");
492 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);
493 ///
494 /// let x : Result<&str, _> = Err("bar");
495 /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
496 /// ```
497 #[inline]
498 #[unstable(feature = "result_map_or_else", issue = "53268")]
499 pub fn map_or_else<U, M: FnOnce(T) -> U, F: FnOnce(E) -> U>(self, fallback: F, map: M) -> U {
500 self.map(map).unwrap_or_else(fallback)
501 }
502
503 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
504 /// contained [`Err`] value, leaving an [`Ok`] value untouched.
505 ///
506 /// This function can be used to pass through a successful result while handling
507 /// an error.
508 ///
509 /// [`Ok`]: enum.Result.html#variant.Ok
510 /// [`Err`]: enum.Result.html#variant.Err
511 ///
512 /// # Examples
513 ///
514 /// Basic usage:
515 ///
516 /// ```
517 /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
518 ///
519 /// let x: Result<u32, u32> = Ok(2);
520 /// assert_eq!(x.map_err(stringify), Ok(2));
521 ///
522 /// let x: Result<u32, u32> = Err(13);
523 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
524 /// ```
525 #[inline]
526 #[stable(feature = "rust1", since = "1.0.0")]
527 pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> {
528 match self {
529 Ok(t) => Ok(t),
530 Err(e) => Err(op(e))
531 }
532 }
533
534 /////////////////////////////////////////////////////////////////////////
535 // Iterator constructors
536 /////////////////////////////////////////////////////////////////////////
537
538 /// Returns an iterator over the possibly contained value.
539 ///
540 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
541 ///
542 /// # Examples
543 ///
544 /// Basic usage:
545 ///
546 /// ```
547 /// let x: Result<u32, &str> = Ok(7);
548 /// assert_eq!(x.iter().next(), Some(&7));
549 ///
550 /// let x: Result<u32, &str> = Err("nothing!");
551 /// assert_eq!(x.iter().next(), None);
552 /// ```
553 #[inline]
554 #[stable(feature = "rust1", since = "1.0.0")]
555 pub fn iter(&self) -> Iter<T> {
556 Iter { inner: self.as_ref().ok() }
557 }
558
559 /// Returns a mutable iterator over the possibly contained value.
560 ///
561 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
562 ///
563 /// # Examples
564 ///
565 /// Basic usage:
566 ///
567 /// ```
568 /// let mut x: Result<u32, &str> = Ok(7);
569 /// match x.iter_mut().next() {
570 /// Some(v) => *v = 40,
571 /// None => {},
572 /// }
573 /// assert_eq!(x, Ok(40));
574 ///
575 /// let mut x: Result<u32, &str> = Err("nothing!");
576 /// assert_eq!(x.iter_mut().next(), None);
577 /// ```
578 #[inline]
579 #[stable(feature = "rust1", since = "1.0.0")]
580 pub fn iter_mut(&mut self) -> IterMut<T> {
581 IterMut { inner: self.as_mut().ok() }
582 }
583
584 ////////////////////////////////////////////////////////////////////////
585 // Boolean operations on the values, eager and lazy
586 /////////////////////////////////////////////////////////////////////////
587
588 /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
589 ///
590 /// [`Ok`]: enum.Result.html#variant.Ok
591 /// [`Err`]: enum.Result.html#variant.Err
592 ///
593 /// # Examples
594 ///
595 /// Basic usage:
596 ///
597 /// ```
598 /// let x: Result<u32, &str> = Ok(2);
599 /// let y: Result<&str, &str> = Err("late error");
600 /// assert_eq!(x.and(y), Err("late error"));
601 ///
602 /// let x: Result<u32, &str> = Err("early error");
603 /// let y: Result<&str, &str> = Ok("foo");
604 /// assert_eq!(x.and(y), Err("early error"));
605 ///
606 /// let x: Result<u32, &str> = Err("not a 2");
607 /// let y: Result<&str, &str> = Err("late error");
608 /// assert_eq!(x.and(y), Err("not a 2"));
609 ///
610 /// let x: Result<u32, &str> = Ok(2);
611 /// let y: Result<&str, &str> = Ok("different result type");
612 /// assert_eq!(x.and(y), Ok("different result type"));
613 /// ```
614 #[inline]
615 #[stable(feature = "rust1", since = "1.0.0")]
616 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
617 match self {
618 Ok(_) => res,
619 Err(e) => Err(e),
620 }
621 }
622
623 /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
624 ///
625 /// [`Ok`]: enum.Result.html#variant.Ok
626 /// [`Err`]: enum.Result.html#variant.Err
627 ///
628 /// This function can be used for control flow based on `Result` values.
629 ///
630 /// # Examples
631 ///
632 /// Basic usage:
633 ///
634 /// ```
635 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
636 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
637 ///
638 /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
639 /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
640 /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
641 /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
642 /// ```
643 #[inline]
644 #[stable(feature = "rust1", since = "1.0.0")]
645 pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
646 match self {
647 Ok(t) => op(t),
648 Err(e) => Err(e),
649 }
650 }
651
652 /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
653 ///
654 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
655 /// result of a function call, it is recommended to use [`or_else`], which is
656 /// lazily evaluated.
657 ///
658 /// [`Ok`]: enum.Result.html#variant.Ok
659 /// [`Err`]: enum.Result.html#variant.Err
660 /// [`or_else`]: #method.or_else
661 ///
662 /// # Examples
663 ///
664 /// Basic usage:
665 ///
666 /// ```
667 /// let x: Result<u32, &str> = Ok(2);
668 /// let y: Result<u32, &str> = Err("late error");
669 /// assert_eq!(x.or(y), Ok(2));
670 ///
671 /// let x: Result<u32, &str> = Err("early error");
672 /// let y: Result<u32, &str> = Ok(2);
673 /// assert_eq!(x.or(y), Ok(2));
674 ///
675 /// let x: Result<u32, &str> = Err("not a 2");
676 /// let y: Result<u32, &str> = Err("late error");
677 /// assert_eq!(x.or(y), Err("late error"));
678 ///
679 /// let x: Result<u32, &str> = Ok(2);
680 /// let y: Result<u32, &str> = Ok(100);
681 /// assert_eq!(x.or(y), Ok(2));
682 /// ```
683 #[inline]
684 #[stable(feature = "rust1", since = "1.0.0")]
685 pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
686 match self {
687 Ok(v) => Ok(v),
688 Err(_) => res,
689 }
690 }
691
692 /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
693 ///
694 /// This function can be used for control flow based on result values.
695 ///
696 /// [`Ok`]: enum.Result.html#variant.Ok
697 /// [`Err`]: enum.Result.html#variant.Err
698 ///
699 /// # Examples
700 ///
701 /// Basic usage:
702 ///
703 /// ```
704 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
705 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
706 ///
707 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
708 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
709 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
710 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
711 /// ```
712 #[inline]
713 #[stable(feature = "rust1", since = "1.0.0")]
714 pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
715 match self {
716 Ok(t) => Ok(t),
717 Err(e) => op(e),
718 }
719 }
720
721 /// Unwraps a result, yielding the content of an [`Ok`].
722 /// Else, it returns `optb`.
723 ///
724 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
725 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
726 /// which is lazily evaluated.
727 ///
728 /// [`Ok`]: enum.Result.html#variant.Ok
729 /// [`Err`]: enum.Result.html#variant.Err
730 /// [`unwrap_or_else`]: #method.unwrap_or_else
731 ///
732 /// # Examples
733 ///
734 /// Basic usage:
735 ///
736 /// ```
737 /// let optb = 2;
738 /// let x: Result<u32, &str> = Ok(9);
739 /// assert_eq!(x.unwrap_or(optb), 9);
740 ///
741 /// let x: Result<u32, &str> = Err("error");
742 /// assert_eq!(x.unwrap_or(optb), optb);
743 /// ```
744 #[inline]
745 #[stable(feature = "rust1", since = "1.0.0")]
746 pub fn unwrap_or(self, optb: T) -> T {
747 match self {
748 Ok(t) => t,
749 Err(_) => optb
750 }
751 }
752
753 /// Unwraps a result, yielding the content of an [`Ok`].
754 /// If the value is an [`Err`] then it calls `op` with its value.
755 ///
756 /// [`Ok`]: enum.Result.html#variant.Ok
757 /// [`Err`]: enum.Result.html#variant.Err
758 ///
759 /// # Examples
760 ///
761 /// Basic usage:
762 ///
763 /// ```
764 /// fn count(x: &str) -> usize { x.len() }
765 ///
766 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
767 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
768 /// ```
769 #[inline]
770 #[stable(feature = "rust1", since = "1.0.0")]
771 pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
772 match self {
773 Ok(t) => t,
774 Err(e) => op(e)
775 }
776 }
777 }
778
779 impl<T, E: fmt::Debug> Result<T, E> {
780 /// Unwraps a result, yielding the content of an [`Ok`].
781 ///
782 /// # Panics
783 ///
784 /// Panics if the value is an [`Err`], with a panic message provided by the
785 /// [`Err`]'s value.
786 ///
787 /// [`Ok`]: enum.Result.html#variant.Ok
788 /// [`Err`]: enum.Result.html#variant.Err
789 ///
790 /// # Examples
791 ///
792 /// Basic usage:
793 ///
794 /// ```
795 /// let x: Result<u32, &str> = Ok(2);
796 /// assert_eq!(x.unwrap(), 2);
797 /// ```
798 ///
799 /// ```{.should_panic}
800 /// let x: Result<u32, &str> = Err("emergency failure");
801 /// x.unwrap(); // panics with `emergency failure`
802 /// ```
803 #[inline]
804 #[stable(feature = "rust1", since = "1.0.0")]
805 pub fn unwrap(self) -> T {
806 match self {
807 Ok(t) => t,
808 Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", e),
809 }
810 }
811
812 /// Unwraps a result, yielding the content of an [`Ok`].
813 ///
814 /// # Panics
815 ///
816 /// Panics if the value is an [`Err`], with a panic message including the
817 /// passed message, and the content of the [`Err`].
818 ///
819 /// [`Ok`]: enum.Result.html#variant.Ok
820 /// [`Err`]: enum.Result.html#variant.Err
821 ///
822 /// # Examples
823 ///
824 /// Basic usage:
825 ///
826 /// ```{.should_panic}
827 /// let x: Result<u32, &str> = Err("emergency failure");
828 /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
829 /// ```
830 #[inline]
831 #[stable(feature = "result_expect", since = "1.4.0")]
832 pub fn expect(self, msg: &str) -> T {
833 match self {
834 Ok(t) => t,
835 Err(e) => unwrap_failed(msg, e),
836 }
837 }
838 }
839
840 impl<T: fmt::Debug, E> Result<T, E> {
841 /// Unwraps a result, yielding the content of an [`Err`].
842 ///
843 /// # Panics
844 ///
845 /// Panics if the value is an [`Ok`], with a custom panic message provided
846 /// by the [`Ok`]'s value.
847 ///
848 /// [`Ok`]: enum.Result.html#variant.Ok
849 /// [`Err`]: enum.Result.html#variant.Err
850 ///
851 ///
852 /// # Examples
853 ///
854 /// ```{.should_panic}
855 /// let x: Result<u32, &str> = Ok(2);
856 /// x.unwrap_err(); // panics with `2`
857 /// ```
858 ///
859 /// ```
860 /// let x: Result<u32, &str> = Err("emergency failure");
861 /// assert_eq!(x.unwrap_err(), "emergency failure");
862 /// ```
863 #[inline]
864 #[stable(feature = "rust1", since = "1.0.0")]
865 pub fn unwrap_err(self) -> E {
866 match self {
867 Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", t),
868 Err(e) => e,
869 }
870 }
871
872 /// Unwraps a result, yielding the content of an [`Err`].
873 ///
874 /// # Panics
875 ///
876 /// Panics if the value is an [`Ok`], with a panic message including the
877 /// passed message, and the content of the [`Ok`].
878 ///
879 /// [`Ok`]: enum.Result.html#variant.Ok
880 /// [`Err`]: enum.Result.html#variant.Err
881 ///
882 /// # Examples
883 ///
884 /// Basic usage:
885 ///
886 /// ```{.should_panic}
887 /// let x: Result<u32, &str> = Ok(10);
888 /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
889 /// ```
890 #[inline]
891 #[stable(feature = "result_expect_err", since = "1.17.0")]
892 pub fn expect_err(self, msg: &str) -> E {
893 match self {
894 Ok(t) => unwrap_failed(msg, t),
895 Err(e) => e,
896 }
897 }
898 }
899
900 impl<T: Default, E> Result<T, E> {
901 /// Returns the contained value or a default
902 ///
903 /// Consumes the `self` argument then, if [`Ok`], returns the contained
904 /// value, otherwise if [`Err`], returns the default value for that
905 /// type.
906 ///
907 /// # Examples
908 ///
909 /// Convert a string to an integer, turning poorly-formed strings
910 /// into 0 (the default value for integers). [`parse`] converts
911 /// a string to any other type that implements [`FromStr`], returning an
912 /// [`Err`] on error.
913 ///
914 /// ```
915 /// let good_year_from_input = "1909";
916 /// let bad_year_from_input = "190blarg";
917 /// let good_year = good_year_from_input.parse().unwrap_or_default();
918 /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
919 ///
920 /// assert_eq!(1909, good_year);
921 /// assert_eq!(0, bad_year);
922 /// ```
923 ///
924 /// [`parse`]: ../../std/primitive.str.html#method.parse
925 /// [`FromStr`]: ../../std/str/trait.FromStr.html
926 /// [`Ok`]: enum.Result.html#variant.Ok
927 /// [`Err`]: enum.Result.html#variant.Err
928 #[inline]
929 #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
930 pub fn unwrap_or_default(self) -> T {
931 match self {
932 Ok(x) => x,
933 Err(_) => Default::default(),
934 }
935 }
936 }
937
938 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
939 impl<T: Deref, E> Result<T, E> {
940 /// Converts from `&Result<T, E>` to `Result<&T::Target, &E>`.
941 ///
942 /// Leaves the original Result in-place, creating a new one with a reference
943 /// to the original one, additionally coercing the `Ok` arm of the Result via
944 /// `Deref`.
945 pub fn deref_ok(&self) -> Result<&T::Target, &E> {
946 self.as_ref().map(|t| t.deref())
947 }
948 }
949
950 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
951 impl<T, E: Deref> Result<T, E> {
952 /// Converts from `&Result<T, E>` to `Result<&T, &E::Target>`.
953 ///
954 /// Leaves the original Result in-place, creating a new one with a reference
955 /// to the original one, additionally coercing the `Err` arm of the Result via
956 /// `Deref`.
957 pub fn deref_err(&self) -> Result<&T, &E::Target>
958 {
959 self.as_ref().map_err(|e| e.deref())
960 }
961 }
962
963 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
964 impl<T: Deref, E: Deref> Result<T, E> {
965 /// Converts from `&Result<T, E>` to `Result<&T::Target, &E::Target>`.
966 ///
967 /// Leaves the original Result in-place, creating a new one with a reference
968 /// to the original one, additionally coercing both the `Ok` and `Err` arms
969 /// of the Result via `Deref`.
970 pub fn deref(&self) -> Result<&T::Target, &E::Target>
971 {
972 self.as_ref().map(|t| t.deref()).map_err(|e| e.deref())
973 }
974 }
975
976 impl<T, E> Result<Option<T>, E> {
977 /// Transposes a `Result` of an `Option` into an `Option` of a `Result`.
978 ///
979 /// `Ok(None)` will be mapped to `None`.
980 /// `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`.
981 ///
982 /// # Examples
983 ///
984 /// ```
985 /// #![feature(transpose_result)]
986 ///
987 /// #[derive(Debug, Eq, PartialEq)]
988 /// struct SomeErr;
989 ///
990 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
991 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
992 /// assert_eq!(x.transpose(), y);
993 /// ```
994 #[inline]
995 #[unstable(feature = "transpose_result", issue = "47338")]
996 pub fn transpose(self) -> Option<Result<T, E>> {
997 match self {
998 Ok(Some(x)) => Some(Ok(x)),
999 Ok(None) => None,
1000 Err(e) => Some(Err(e)),
1001 }
1002 }
1003 }
1004
1005 // This is a separate function to reduce the code size of the methods
1006 #[inline(never)]
1007 #[cold]
1008 fn unwrap_failed<E: fmt::Debug>(msg: &str, error: E) -> ! {
1009 panic!("{}: {:?}", msg, error)
1010 }
1011
1012 /////////////////////////////////////////////////////////////////////////////
1013 // Trait implementations
1014 /////////////////////////////////////////////////////////////////////////////
1015
1016 #[stable(feature = "rust1", since = "1.0.0")]
1017 impl<T, E> IntoIterator for Result<T, E> {
1018 type Item = T;
1019 type IntoIter = IntoIter<T>;
1020
1021 /// Returns a consuming iterator over the possibly contained value.
1022 ///
1023 /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
1024 ///
1025 /// # Examples
1026 ///
1027 /// Basic usage:
1028 ///
1029 /// ```
1030 /// let x: Result<u32, &str> = Ok(5);
1031 /// let v: Vec<u32> = x.into_iter().collect();
1032 /// assert_eq!(v, [5]);
1033 ///
1034 /// let x: Result<u32, &str> = Err("nothing!");
1035 /// let v: Vec<u32> = x.into_iter().collect();
1036 /// assert_eq!(v, []);
1037 /// ```
1038 #[inline]
1039 fn into_iter(self) -> IntoIter<T> {
1040 IntoIter { inner: self.ok() }
1041 }
1042 }
1043
1044 #[stable(since = "1.4.0", feature = "result_iter")]
1045 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
1046 type Item = &'a T;
1047 type IntoIter = Iter<'a, T>;
1048
1049 fn into_iter(self) -> Iter<'a, T> {
1050 self.iter()
1051 }
1052 }
1053
1054 #[stable(since = "1.4.0", feature = "result_iter")]
1055 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
1056 type Item = &'a mut T;
1057 type IntoIter = IterMut<'a, T>;
1058
1059 fn into_iter(self) -> IterMut<'a, T> {
1060 self.iter_mut()
1061 }
1062 }
1063
1064 /////////////////////////////////////////////////////////////////////////////
1065 // The Result Iterators
1066 /////////////////////////////////////////////////////////////////////////////
1067
1068 /// An iterator over a reference to the [`Ok`] variant of a [`Result`].
1069 ///
1070 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1071 ///
1072 /// Created by [`Result::iter`].
1073 ///
1074 /// [`Ok`]: enum.Result.html#variant.Ok
1075 /// [`Result`]: enum.Result.html
1076 /// [`Result::iter`]: enum.Result.html#method.iter
1077 #[derive(Debug)]
1078 #[stable(feature = "rust1", since = "1.0.0")]
1079 pub struct Iter<'a, T: 'a> { inner: Option<&'a T> }
1080
1081 #[stable(feature = "rust1", since = "1.0.0")]
1082 impl<'a, T> Iterator for Iter<'a, T> {
1083 type Item = &'a T;
1084
1085 #[inline]
1086 fn next(&mut self) -> Option<&'a T> { self.inner.take() }
1087 #[inline]
1088 fn size_hint(&self) -> (usize, Option<usize>) {
1089 let n = if self.inner.is_some() {1} else {0};
1090 (n, Some(n))
1091 }
1092 }
1093
1094 #[stable(feature = "rust1", since = "1.0.0")]
1095 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1096 #[inline]
1097 fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
1098 }
1099
1100 #[stable(feature = "rust1", since = "1.0.0")]
1101 impl<T> ExactSizeIterator for Iter<'_, T> {}
1102
1103 #[stable(feature = "fused", since = "1.26.0")]
1104 impl<T> FusedIterator for Iter<'_, T> {}
1105
1106 #[unstable(feature = "trusted_len", issue = "37572")]
1107 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1108
1109 #[stable(feature = "rust1", since = "1.0.0")]
1110 impl<T> Clone for Iter<'_, T> {
1111 #[inline]
1112 fn clone(&self) -> Self { Iter { inner: self.inner } }
1113 }
1114
1115 /// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
1116 ///
1117 /// Created by [`Result::iter_mut`].
1118 ///
1119 /// [`Ok`]: enum.Result.html#variant.Ok
1120 /// [`Result`]: enum.Result.html
1121 /// [`Result::iter_mut`]: enum.Result.html#method.iter_mut
1122 #[derive(Debug)]
1123 #[stable(feature = "rust1", since = "1.0.0")]
1124 pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
1125
1126 #[stable(feature = "rust1", since = "1.0.0")]
1127 impl<'a, T> Iterator for IterMut<'a, T> {
1128 type Item = &'a mut T;
1129
1130 #[inline]
1131 fn next(&mut self) -> Option<&'a mut T> { self.inner.take() }
1132 #[inline]
1133 fn size_hint(&self) -> (usize, Option<usize>) {
1134 let n = if self.inner.is_some() {1} else {0};
1135 (n, Some(n))
1136 }
1137 }
1138
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1141 #[inline]
1142 fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
1143 }
1144
1145 #[stable(feature = "rust1", since = "1.0.0")]
1146 impl<T> ExactSizeIterator for IterMut<'_, T> {}
1147
1148 #[stable(feature = "fused", since = "1.26.0")]
1149 impl<T> FusedIterator for IterMut<'_, T> {}
1150
1151 #[unstable(feature = "trusted_len", issue = "37572")]
1152 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1153
1154 /// An iterator over the value in a [`Ok`] variant of a [`Result`].
1155 ///
1156 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1157 ///
1158 /// This struct is created by the [`into_iter`] method on
1159 /// [`Result`][`Result`] (provided by the [`IntoIterator`] trait).
1160 ///
1161 /// [`Ok`]: enum.Result.html#variant.Ok
1162 /// [`Result`]: enum.Result.html
1163 /// [`into_iter`]: ../iter/trait.IntoIterator.html#tymethod.into_iter
1164 /// [`IntoIterator`]: ../iter/trait.IntoIterator.html
1165 #[derive(Clone, Debug)]
1166 #[stable(feature = "rust1", since = "1.0.0")]
1167 pub struct IntoIter<T> { inner: Option<T> }
1168
1169 #[stable(feature = "rust1", since = "1.0.0")]
1170 impl<T> Iterator for IntoIter<T> {
1171 type Item = T;
1172
1173 #[inline]
1174 fn next(&mut self) -> Option<T> { self.inner.take() }
1175 #[inline]
1176 fn size_hint(&self) -> (usize, Option<usize>) {
1177 let n = if self.inner.is_some() {1} else {0};
1178 (n, Some(n))
1179 }
1180 }
1181
1182 #[stable(feature = "rust1", since = "1.0.0")]
1183 impl<T> DoubleEndedIterator for IntoIter<T> {
1184 #[inline]
1185 fn next_back(&mut self) -> Option<T> { self.inner.take() }
1186 }
1187
1188 #[stable(feature = "rust1", since = "1.0.0")]
1189 impl<T> ExactSizeIterator for IntoIter<T> {}
1190
1191 #[stable(feature = "fused", since = "1.26.0")]
1192 impl<T> FusedIterator for IntoIter<T> {}
1193
1194 #[unstable(feature = "trusted_len", issue = "37572")]
1195 unsafe impl<A> TrustedLen for IntoIter<A> {}
1196
1197 /////////////////////////////////////////////////////////////////////////////
1198 // FromIterator
1199 /////////////////////////////////////////////////////////////////////////////
1200
1201 #[stable(feature = "rust1", since = "1.0.0")]
1202 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
1203 /// Takes each element in the `Iterator`: if it is an `Err`, no further
1204 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
1205 /// container with the values of each `Result` is returned.
1206 ///
1207 /// Here is an example which increments every integer in a vector,
1208 /// checking for overflow:
1209 ///
1210 /// ```
1211 /// let v = vec![1, 2];
1212 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1213 /// x.checked_add(1).ok_or("Overflow!")
1214 /// ).collect();
1215 /// assert!(res == Ok(vec![2, 3]));
1216 /// ```
1217 #[inline]
1218 fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
1219 // FIXME(#11084): This could be replaced with Iterator::scan when this
1220 // performance bug is closed.
1221
1222 struct Adapter<Iter, E> {
1223 iter: Iter,
1224 err: Option<E>,
1225 }
1226
1227 impl<T, E, Iter: Iterator<Item=Result<T, E>>> Iterator for Adapter<Iter, E> {
1228 type Item = T;
1229
1230 #[inline]
1231 fn next(&mut self) -> Option<T> {
1232 match self.iter.next() {
1233 Some(Ok(value)) => Some(value),
1234 Some(Err(err)) => {
1235 self.err = Some(err);
1236 None
1237 }
1238 None => None,
1239 }
1240 }
1241
1242 fn size_hint(&self) -> (usize, Option<usize>) {
1243 let (_min, max) = self.iter.size_hint();
1244 (0, max)
1245 }
1246 }
1247
1248 let mut adapter = Adapter { iter: iter.into_iter(), err: None };
1249 let v: V = FromIterator::from_iter(adapter.by_ref());
1250
1251 match adapter.err {
1252 Some(err) => Err(err),
1253 None => Ok(v),
1254 }
1255 }
1256 }
1257
1258 #[unstable(feature = "try_trait", issue = "42327")]
1259 impl<T,E> ops::Try for Result<T, E> {
1260 type Ok = T;
1261 type Error = E;
1262
1263 #[inline]
1264 fn into_result(self) -> Self {
1265 self
1266 }
1267
1268 #[inline]
1269 fn from_ok(v: T) -> Self {
1270 Ok(v)
1271 }
1272
1273 #[inline]
1274 fn from_error(v: E) -> Self {
1275 Err(v)
1276 }
1277 }