]> git.lizzy.rs Git - rust.git/blob - src/libcore/result.rs
Rollup merge of #40521 - TimNN:panic-free-shift, r=alexcrichton
[rust.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 `?` syntax
157 //!
158 //! When writing code that calls many functions that return the
159 //! [`Result`] type, the error handling can be tedious. The [`?`]
160 //! syntax hides some of the boilerplate of propagating errors up the
161 //! 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
246 /// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
247 ///
248 /// See the [`std::result`](index.html) module documentation for details.
249 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
250 #[must_use]
251 #[stable(feature = "rust1", since = "1.0.0")]
252 pub enum Result<T, E> {
253     /// Contains the success value
254     #[stable(feature = "rust1", since = "1.0.0")]
255     Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
256
257     /// Contains the error value
258     #[stable(feature = "rust1", since = "1.0.0")]
259     Err(#[stable(feature = "rust1", since = "1.0.0")] E),
260 }
261
262 /////////////////////////////////////////////////////////////////////////////
263 // Type implementation
264 /////////////////////////////////////////////////////////////////////////////
265
266 impl<T, E> Result<T, E> {
267     /////////////////////////////////////////////////////////////////////////
268     // Querying the contained values
269     /////////////////////////////////////////////////////////////////////////
270
271     /// Returns true if the result is `Ok`.
272     ///
273     /// # Examples
274     ///
275     /// Basic usage:
276     ///
277     /// ```
278     /// let x: Result<i32, &str> = Ok(-3);
279     /// assert_eq!(x.is_ok(), true);
280     ///
281     /// let x: Result<i32, &str> = Err("Some error message");
282     /// assert_eq!(x.is_ok(), false);
283     /// ```
284     #[inline]
285     #[stable(feature = "rust1", since = "1.0.0")]
286     pub fn is_ok(&self) -> bool {
287         match *self {
288             Ok(_) => true,
289             Err(_) => false
290         }
291     }
292
293     /// Returns true if the result is `Err`.
294     ///
295     /// # Examples
296     ///
297     /// Basic usage:
298     ///
299     /// ```
300     /// let x: Result<i32, &str> = Ok(-3);
301     /// assert_eq!(x.is_err(), false);
302     ///
303     /// let x: Result<i32, &str> = Err("Some error message");
304     /// assert_eq!(x.is_err(), true);
305     /// ```
306     #[inline]
307     #[stable(feature = "rust1", since = "1.0.0")]
308     pub fn is_err(&self) -> bool {
309         !self.is_ok()
310     }
311
312     /////////////////////////////////////////////////////////////////////////
313     // Adapter for each variant
314     /////////////////////////////////////////////////////////////////////////
315
316     /// Converts from `Result<T, E>` to [`Option<T>`].
317     ///
318     /// Converts `self` into an [`Option<T>`], consuming `self`,
319     /// and discarding the error, if any.
320     ///
321     /// [`Option<T>`]: ../../std/option/enum.Option.html
322     ///
323     /// # Examples
324     ///
325     /// Basic usage:
326     ///
327     /// ```
328     /// let x: Result<u32, &str> = Ok(2);
329     /// assert_eq!(x.ok(), Some(2));
330     ///
331     /// let x: Result<u32, &str> = Err("Nothing here");
332     /// assert_eq!(x.ok(), None);
333     /// ```
334     #[inline]
335     #[stable(feature = "rust1", since = "1.0.0")]
336     pub fn ok(self) -> Option<T> {
337         match self {
338             Ok(x)  => Some(x),
339             Err(_) => None,
340         }
341     }
342
343     /// Converts from `Result<T, E>` to [`Option<E>`].
344     ///
345     /// Converts `self` into an [`Option<E>`], consuming `self`,
346     /// and discarding the success value, if any.
347     ///
348     /// [`Option<E>`]: ../../std/option/enum.Option.html
349     ///
350     /// # Examples
351     ///
352     /// Basic usage:
353     ///
354     /// ```
355     /// let x: Result<u32, &str> = Ok(2);
356     /// assert_eq!(x.err(), None);
357     ///
358     /// let x: Result<u32, &str> = Err("Nothing here");
359     /// assert_eq!(x.err(), Some("Nothing here"));
360     /// ```
361     #[inline]
362     #[stable(feature = "rust1", since = "1.0.0")]
363     pub fn err(self) -> Option<E> {
364         match self {
365             Ok(_)  => None,
366             Err(x) => Some(x),
367         }
368     }
369
370     /////////////////////////////////////////////////////////////////////////
371     // Adapter for working with references
372     /////////////////////////////////////////////////////////////////////////
373
374     /// Converts from `Result<T, E>` to `Result<&T, &E>`.
375     ///
376     /// Produces a new `Result`, containing a reference
377     /// into the original, leaving the original in place.
378     ///
379     /// # Examples
380     ///
381     /// Basic usage:
382     ///
383     /// ```
384     /// let x: Result<u32, &str> = Ok(2);
385     /// assert_eq!(x.as_ref(), Ok(&2));
386     ///
387     /// let x: Result<u32, &str> = Err("Error");
388     /// assert_eq!(x.as_ref(), Err(&"Error"));
389     /// ```
390     #[inline]
391     #[stable(feature = "rust1", since = "1.0.0")]
392     pub fn as_ref(&self) -> Result<&T, &E> {
393         match *self {
394             Ok(ref x) => Ok(x),
395             Err(ref x) => Err(x),
396         }
397     }
398
399     /// Converts from `Result<T, E>` to `Result<&mut T, &mut E>`.
400     ///
401     /// # Examples
402     ///
403     /// Basic usage:
404     ///
405     /// ```
406     /// fn mutate(r: &mut Result<i32, i32>) {
407     ///     match r.as_mut() {
408     ///         Ok(v) => *v = 42,
409     ///         Err(e) => *e = 0,
410     ///     }
411     /// }
412     ///
413     /// let mut x: Result<i32, i32> = Ok(2);
414     /// mutate(&mut x);
415     /// assert_eq!(x.unwrap(), 42);
416     ///
417     /// let mut x: Result<i32, i32> = Err(13);
418     /// mutate(&mut x);
419     /// assert_eq!(x.unwrap_err(), 0);
420     /// ```
421     #[inline]
422     #[stable(feature = "rust1", since = "1.0.0")]
423     pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
424         match *self {
425             Ok(ref mut x) => Ok(x),
426             Err(ref mut x) => Err(x),
427         }
428     }
429
430     /////////////////////////////////////////////////////////////////////////
431     // Transforming contained values
432     /////////////////////////////////////////////////////////////////////////
433
434     /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
435     /// contained `Ok` value, leaving an `Err` value untouched.
436     ///
437     /// This function can be used to compose the results of two functions.
438     ///
439     /// # Examples
440     ///
441     /// Print the numbers on each line of a string multiplied by two.
442     ///
443     /// ```
444     /// let line = "1\n2\n3\n4\n";
445     ///
446     /// for num in line.lines() {
447     ///     match num.parse::<i32>().map(|i| i * 2) {
448     ///         Ok(n) => println!("{}", n),
449     ///         Err(..) => {}
450     ///     }
451     /// }
452     /// ```
453     #[inline]
454     #[stable(feature = "rust1", since = "1.0.0")]
455     pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
456         match self {
457             Ok(t) => Ok(op(t)),
458             Err(e) => Err(e)
459         }
460     }
461
462     /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
463     /// contained `Err` value, leaving an `Ok` value untouched.
464     ///
465     /// This function can be used to pass through a successful result while handling
466     /// an error.
467     ///
468     /// # Examples
469     ///
470     /// Basic usage:
471     ///
472     /// ```
473     /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
474     ///
475     /// let x: Result<u32, u32> = Ok(2);
476     /// assert_eq!(x.map_err(stringify), Ok(2));
477     ///
478     /// let x: Result<u32, u32> = Err(13);
479     /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
480     /// ```
481     #[inline]
482     #[stable(feature = "rust1", since = "1.0.0")]
483     pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> {
484         match self {
485             Ok(t) => Ok(t),
486             Err(e) => Err(op(e))
487         }
488     }
489
490     /////////////////////////////////////////////////////////////////////////
491     // Iterator constructors
492     /////////////////////////////////////////////////////////////////////////
493
494     /// Returns an iterator over the possibly contained value.
495     ///
496     /// The iterator yields one value if the result is [`Ok`], otherwise none.
497     ///
498     /// # Examples
499     ///
500     /// Basic usage:
501     ///
502     /// ```
503     /// let x: Result<u32, &str> = Ok(7);
504     /// assert_eq!(x.iter().next(), Some(&7));
505     ///
506     /// let x: Result<u32, &str> = Err("nothing!");
507     /// assert_eq!(x.iter().next(), None);
508     /// ```
509     ///
510     /// [`Ok`]: enum.Result.html#variant.Ok
511     #[inline]
512     #[stable(feature = "rust1", since = "1.0.0")]
513     pub fn iter(&self) -> Iter<T> {
514         Iter { inner: self.as_ref().ok() }
515     }
516
517     /// Returns a mutable iterator over the possibly contained value.
518     ///
519     /// The iterator yields one value if the result is [`Ok`], otherwise none.
520     ///
521     /// # Examples
522     ///
523     /// Basic usage:
524     ///
525     /// ```
526     /// let mut x: Result<u32, &str> = Ok(7);
527     /// match x.iter_mut().next() {
528     ///     Some(v) => *v = 40,
529     ///     None => {},
530     /// }
531     /// assert_eq!(x, Ok(40));
532     ///
533     /// let mut x: Result<u32, &str> = Err("nothing!");
534     /// assert_eq!(x.iter_mut().next(), None);
535     /// ```
536     ///
537     /// [`Ok`]: enum.Result.html#variant.Ok
538     #[inline]
539     #[stable(feature = "rust1", since = "1.0.0")]
540     pub fn iter_mut(&mut self) -> IterMut<T> {
541         IterMut { inner: self.as_mut().ok() }
542     }
543
544     ////////////////////////////////////////////////////////////////////////
545     // Boolean operations on the values, eager and lazy
546     /////////////////////////////////////////////////////////////////////////
547
548     /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
549     ///
550     /// # Examples
551     ///
552     /// Basic usage:
553     ///
554     /// ```
555     /// let x: Result<u32, &str> = Ok(2);
556     /// let y: Result<&str, &str> = Err("late error");
557     /// assert_eq!(x.and(y), Err("late error"));
558     ///
559     /// let x: Result<u32, &str> = Err("early error");
560     /// let y: Result<&str, &str> = Ok("foo");
561     /// assert_eq!(x.and(y), Err("early error"));
562     ///
563     /// let x: Result<u32, &str> = Err("not a 2");
564     /// let y: Result<&str, &str> = Err("late error");
565     /// assert_eq!(x.and(y), Err("not a 2"));
566     ///
567     /// let x: Result<u32, &str> = Ok(2);
568     /// let y: Result<&str, &str> = Ok("different result type");
569     /// assert_eq!(x.and(y), Ok("different result type"));
570     /// ```
571     #[inline]
572     #[stable(feature = "rust1", since = "1.0.0")]
573     pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
574         match self {
575             Ok(_) => res,
576             Err(e) => Err(e),
577         }
578     }
579
580     /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
581     ///
582     /// This function can be used for control flow based on `Result` values.
583     ///
584     /// # Examples
585     ///
586     /// Basic usage:
587     ///
588     /// ```
589     /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
590     /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
591     ///
592     /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
593     /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
594     /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
595     /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
596     /// ```
597     #[inline]
598     #[stable(feature = "rust1", since = "1.0.0")]
599     pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
600         match self {
601             Ok(t) => op(t),
602             Err(e) => Err(e),
603         }
604     }
605
606     /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
607     ///
608     /// # Examples
609     ///
610     /// Basic usage:
611     ///
612     /// ```
613     /// let x: Result<u32, &str> = Ok(2);
614     /// let y: Result<u32, &str> = Err("late error");
615     /// assert_eq!(x.or(y), Ok(2));
616     ///
617     /// let x: Result<u32, &str> = Err("early error");
618     /// let y: Result<u32, &str> = Ok(2);
619     /// assert_eq!(x.or(y), Ok(2));
620     ///
621     /// let x: Result<u32, &str> = Err("not a 2");
622     /// let y: Result<u32, &str> = Err("late error");
623     /// assert_eq!(x.or(y), Err("late error"));
624     ///
625     /// let x: Result<u32, &str> = Ok(2);
626     /// let y: Result<u32, &str> = Ok(100);
627     /// assert_eq!(x.or(y), Ok(2));
628     /// ```
629     #[inline]
630     #[stable(feature = "rust1", since = "1.0.0")]
631     pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
632         match self {
633             Ok(v) => Ok(v),
634             Err(_) => res,
635         }
636     }
637
638     /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
639     ///
640     /// This function can be used for control flow based on result values.
641     ///
642     /// # Examples
643     ///
644     /// Basic usage:
645     ///
646     /// ```
647     /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
648     /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
649     ///
650     /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
651     /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
652     /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
653     /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
654     /// ```
655     #[inline]
656     #[stable(feature = "rust1", since = "1.0.0")]
657     pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
658         match self {
659             Ok(t) => Ok(t),
660             Err(e) => op(e),
661         }
662     }
663
664     /// Unwraps a result, yielding the content of an `Ok`.
665     /// Else, it returns `optb`.
666     ///
667     /// # Examples
668     ///
669     /// Basic usage:
670     ///
671     /// ```
672     /// let optb = 2;
673     /// let x: Result<u32, &str> = Ok(9);
674     /// assert_eq!(x.unwrap_or(optb), 9);
675     ///
676     /// let x: Result<u32, &str> = Err("error");
677     /// assert_eq!(x.unwrap_or(optb), optb);
678     /// ```
679     #[inline]
680     #[stable(feature = "rust1", since = "1.0.0")]
681     pub fn unwrap_or(self, optb: T) -> T {
682         match self {
683             Ok(t) => t,
684             Err(_) => optb
685         }
686     }
687
688     /// Unwraps a result, yielding the content of an `Ok`.
689     /// If the value is an `Err` then it calls `op` with its value.
690     ///
691     /// # Examples
692     ///
693     /// Basic usage:
694     ///
695     /// ```
696     /// fn count(x: &str) -> usize { x.len() }
697     ///
698     /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
699     /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
700     /// ```
701     #[inline]
702     #[stable(feature = "rust1", since = "1.0.0")]
703     pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
704         match self {
705             Ok(t) => t,
706             Err(e) => op(e)
707         }
708     }
709 }
710
711 impl<T, E: fmt::Debug> Result<T, E> {
712     /// Unwraps a result, yielding the content of an `Ok`.
713     ///
714     /// # Panics
715     ///
716     /// Panics if the value is an `Err`, with a panic message provided by the
717     /// `Err`'s value.
718     ///
719     /// # Examples
720     ///
721     /// Basic usage:
722     ///
723     /// ```
724     /// let x: Result<u32, &str> = Ok(2);
725     /// assert_eq!(x.unwrap(), 2);
726     /// ```
727     ///
728     /// ```{.should_panic}
729     /// let x: Result<u32, &str> = Err("emergency failure");
730     /// x.unwrap(); // panics with `emergency failure`
731     /// ```
732     #[inline]
733     #[stable(feature = "rust1", since = "1.0.0")]
734     pub fn unwrap(self) -> T {
735         match self {
736             Ok(t) => t,
737             Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", e),
738         }
739     }
740
741     /// Unwraps a result, yielding the content of an `Ok`.
742     ///
743     /// # Panics
744     ///
745     /// Panics if the value is an `Err`, with a panic message including the
746     /// passed message, and the content of the `Err`.
747     ///
748     /// # Examples
749     ///
750     /// Basic usage:
751     ///
752     /// ```{.should_panic}
753     /// let x: Result<u32, &str> = Err("emergency failure");
754     /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
755     /// ```
756     #[inline]
757     #[stable(feature = "result_expect", since = "1.4.0")]
758     pub fn expect(self, msg: &str) -> T {
759         match self {
760             Ok(t) => t,
761             Err(e) => unwrap_failed(msg, e),
762         }
763     }
764 }
765
766 impl<T: fmt::Debug, E> Result<T, E> {
767     /// Unwraps a result, yielding the content of an `Err`.
768     ///
769     /// # Panics
770     ///
771     /// Panics if the value is an `Ok`, with a custom panic message provided
772     /// by the `Ok`'s value.
773     ///
774     /// # Examples
775     ///
776     /// ```{.should_panic}
777     /// let x: Result<u32, &str> = Ok(2);
778     /// x.unwrap_err(); // panics with `2`
779     /// ```
780     ///
781     /// ```
782     /// let x: Result<u32, &str> = Err("emergency failure");
783     /// assert_eq!(x.unwrap_err(), "emergency failure");
784     /// ```
785     #[inline]
786     #[stable(feature = "rust1", since = "1.0.0")]
787     pub fn unwrap_err(self) -> E {
788         match self {
789             Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", t),
790             Err(e) => e,
791         }
792     }
793
794     /// Unwraps a result, yielding the content of an `Err`.
795     ///
796     /// # Panics
797     ///
798     /// Panics if the value is an `Ok`, with a panic message including the
799     /// passed message, and the content of the `Ok`.
800     ///
801     /// # Examples
802     ///
803     /// Basic usage:
804     ///
805     /// ```{.should_panic}
806     /// let x: Result<u32, &str> = Ok(10);
807     /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
808     /// ```
809     #[inline]
810     #[stable(feature = "result_expect_err", since = "1.17.0")]
811     pub fn expect_err(self, msg: &str) -> E {
812         match self {
813             Ok(t) => unwrap_failed(msg, t),
814             Err(e) => e,
815         }
816     }
817 }
818
819 impl<T: Default, E> Result<T, E> {
820     /// Returns the contained value or a default
821     ///
822     /// Consumes the `self` argument then, if `Ok`, returns the contained
823     /// value, otherwise if `Err`, returns the default value for that
824     /// type.
825     ///
826     /// # Examples
827     ///
828     /// Convert a string to an integer, turning poorly-formed strings
829     /// into 0 (the default value for integers). [`parse`] converts
830     /// a string to any other type that implements [`FromStr`], returning an
831     /// `Err` on error.
832     ///
833     /// ```
834     /// let good_year_from_input = "1909";
835     /// let bad_year_from_input = "190blarg";
836     /// let good_year = good_year_from_input.parse().unwrap_or_default();
837     /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
838     ///
839     /// assert_eq!(1909, good_year);
840     /// assert_eq!(0, bad_year);
841     ///
842     /// [`parse`]: ../../std/primitive.str.html#method.parse
843     /// [`FromStr`]: ../../std/str/trait.FromStr.html
844     /// ```
845     #[inline]
846     #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
847     pub fn unwrap_or_default(self) -> T {
848         match self {
849             Ok(x) => x,
850             Err(_) => Default::default(),
851         }
852     }
853 }
854
855 // This is a separate function to reduce the code size of the methods
856 #[inline(never)]
857 #[cold]
858 fn unwrap_failed<E: fmt::Debug>(msg: &str, error: E) -> ! {
859     panic!("{}: {:?}", msg, error)
860 }
861
862 /////////////////////////////////////////////////////////////////////////////
863 // Trait implementations
864 /////////////////////////////////////////////////////////////////////////////
865
866 #[stable(feature = "rust1", since = "1.0.0")]
867 impl<T, E> IntoIterator for Result<T, E> {
868     type Item = T;
869     type IntoIter = IntoIter<T>;
870
871     /// Returns a consuming iterator over the possibly contained value.
872     ///
873     /// The iterator yields one value if the result is [`Ok`], otherwise none.
874     ///
875     /// # Examples
876     ///
877     /// Basic usage:
878     ///
879     /// ```
880     /// let x: Result<u32, &str> = Ok(5);
881     /// let v: Vec<u32> = x.into_iter().collect();
882     /// assert_eq!(v, [5]);
883     ///
884     /// let x: Result<u32, &str> = Err("nothing!");
885     /// let v: Vec<u32> = x.into_iter().collect();
886     /// assert_eq!(v, []);
887     /// ```
888     ///
889     /// [`Ok`]: enum.Result.html#variant.Ok
890     #[inline]
891     fn into_iter(self) -> IntoIter<T> {
892         IntoIter { inner: self.ok() }
893     }
894 }
895
896 #[stable(since = "1.4.0", feature = "result_iter")]
897 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
898     type Item = &'a T;
899     type IntoIter = Iter<'a, T>;
900
901     fn into_iter(self) -> Iter<'a, T> {
902         self.iter()
903     }
904 }
905
906 #[stable(since = "1.4.0", feature = "result_iter")]
907 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
908     type Item = &'a mut T;
909     type IntoIter = IterMut<'a, T>;
910
911     fn into_iter(mut self) -> IterMut<'a, T> {
912         self.iter_mut()
913     }
914 }
915
916 /////////////////////////////////////////////////////////////////////////////
917 // The Result Iterators
918 /////////////////////////////////////////////////////////////////////////////
919
920 /// An iterator over a reference to the [`Ok`] variant of a [`Result`].
921 ///
922 /// The iterator yields one value if the result is [`Ok`], otherwise none.
923 ///
924 /// Created by [`Result::iter`].
925 ///
926 /// [`Ok`]: enum.Result.html#variant.Ok
927 /// [`Result`]: enum.Result.html
928 /// [`Result::iter`]: enum.Result.html#method.iter
929 #[derive(Debug)]
930 #[stable(feature = "rust1", since = "1.0.0")]
931 pub struct Iter<'a, T: 'a> { inner: Option<&'a T> }
932
933 #[stable(feature = "rust1", since = "1.0.0")]
934 impl<'a, T> Iterator for Iter<'a, T> {
935     type Item = &'a T;
936
937     #[inline]
938     fn next(&mut self) -> Option<&'a T> { self.inner.take() }
939     #[inline]
940     fn size_hint(&self) -> (usize, Option<usize>) {
941         let n = if self.inner.is_some() {1} else {0};
942         (n, Some(n))
943     }
944 }
945
946 #[stable(feature = "rust1", since = "1.0.0")]
947 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
948     #[inline]
949     fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
950 }
951
952 #[stable(feature = "rust1", since = "1.0.0")]
953 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
954
955 #[unstable(feature = "fused", issue = "35602")]
956 impl<'a, T> FusedIterator for Iter<'a, T> {}
957
958 #[unstable(feature = "trusted_len", issue = "37572")]
959 unsafe impl<'a, A> TrustedLen for Iter<'a, A> {}
960
961 #[stable(feature = "rust1", since = "1.0.0")]
962 impl<'a, T> Clone for Iter<'a, T> {
963     fn clone(&self) -> Iter<'a, T> { Iter { inner: self.inner } }
964 }
965
966 /// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
967 ///
968 /// Created by [`Result::iter_mut`].
969 ///
970 /// [`Ok`]: enum.Result.html#variant.Ok
971 /// [`Result`]: enum.Result.html
972 /// [`Result::iter_mut`]: enum.Result.html#method.iter_mut
973 #[derive(Debug)]
974 #[stable(feature = "rust1", since = "1.0.0")]
975 pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
976
977 #[stable(feature = "rust1", since = "1.0.0")]
978 impl<'a, T> Iterator for IterMut<'a, T> {
979     type Item = &'a mut T;
980
981     #[inline]
982     fn next(&mut self) -> Option<&'a mut T> { self.inner.take() }
983     #[inline]
984     fn size_hint(&self) -> (usize, Option<usize>) {
985         let n = if self.inner.is_some() {1} else {0};
986         (n, Some(n))
987     }
988 }
989
990 #[stable(feature = "rust1", since = "1.0.0")]
991 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
992     #[inline]
993     fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
994 }
995
996 #[stable(feature = "rust1", since = "1.0.0")]
997 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
998
999 #[unstable(feature = "fused", issue = "35602")]
1000 impl<'a, T> FusedIterator for IterMut<'a, T> {}
1001
1002 #[unstable(feature = "trusted_len", issue = "37572")]
1003 unsafe impl<'a, A> TrustedLen for IterMut<'a, A> {}
1004
1005 /// An iterator over the value in a [`Ok`] variant of a [`Result`].
1006 ///
1007 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1008 ///
1009 /// This struct is created by the [`into_iter`] method on
1010 /// [`Result`][`Result`] (provided by the [`IntoIterator`] trait).
1011 ///
1012 /// [`Ok`]: enum.Result.html#variant.Ok
1013 /// [`Result`]: enum.Result.html
1014 /// [`into_iter`]: ../iter/trait.IntoIterator.html#tymethod.into_iter
1015 /// [`IntoIterator`]: ../iter/trait.IntoIterator.html
1016 #[derive(Debug)]
1017 #[stable(feature = "rust1", since = "1.0.0")]
1018 pub struct IntoIter<T> { inner: Option<T> }
1019
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 impl<T> Iterator for IntoIter<T> {
1022     type Item = T;
1023
1024     #[inline]
1025     fn next(&mut self) -> Option<T> { self.inner.take() }
1026     #[inline]
1027     fn size_hint(&self) -> (usize, Option<usize>) {
1028         let n = if self.inner.is_some() {1} else {0};
1029         (n, Some(n))
1030     }
1031 }
1032
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 impl<T> DoubleEndedIterator for IntoIter<T> {
1035     #[inline]
1036     fn next_back(&mut self) -> Option<T> { self.inner.take() }
1037 }
1038
1039 #[stable(feature = "rust1", since = "1.0.0")]
1040 impl<T> ExactSizeIterator for IntoIter<T> {}
1041
1042 #[unstable(feature = "fused", issue = "35602")]
1043 impl<T> FusedIterator for IntoIter<T> {}
1044
1045 #[unstable(feature = "trusted_len", issue = "37572")]
1046 unsafe impl<A> TrustedLen for IntoIter<A> {}
1047
1048 /////////////////////////////////////////////////////////////////////////////
1049 // FromIterator
1050 /////////////////////////////////////////////////////////////////////////////
1051
1052 #[stable(feature = "rust1", since = "1.0.0")]
1053 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
1054     /// Takes each element in the `Iterator`: if it is an `Err`, no further
1055     /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
1056     /// container with the values of each `Result` is returned.
1057     ///
1058     /// Here is an example which increments every integer in a vector,
1059     /// checking for overflow:
1060     ///
1061     /// ```
1062     /// use std::u32;
1063     ///
1064     /// let v = vec![1, 2];
1065     /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|&x: &u32|
1066     ///     if x == u32::MAX { Err("Overflow!") }
1067     ///     else { Ok(x + 1) }
1068     /// ).collect();
1069     /// assert!(res == Ok(vec![2, 3]));
1070     /// ```
1071     #[inline]
1072     fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
1073         // FIXME(#11084): This could be replaced with Iterator::scan when this
1074         // performance bug is closed.
1075
1076         struct Adapter<Iter, E> {
1077             iter: Iter,
1078             err: Option<E>,
1079         }
1080
1081         impl<T, E, Iter: Iterator<Item=Result<T, E>>> Iterator for Adapter<Iter, E> {
1082             type Item = T;
1083
1084             #[inline]
1085             fn next(&mut self) -> Option<T> {
1086                 match self.iter.next() {
1087                     Some(Ok(value)) => Some(value),
1088                     Some(Err(err)) => {
1089                         self.err = Some(err);
1090                         None
1091                     }
1092                     None => None,
1093                 }
1094             }
1095
1096             fn size_hint(&self) -> (usize, Option<usize>) {
1097                 let (_min, max) = self.iter.size_hint();
1098                 (0, max)
1099             }
1100         }
1101
1102         let mut adapter = Adapter { iter: iter.into_iter(), err: None };
1103         let v: V = FromIterator::from_iter(adapter.by_ref());
1104
1105         match adapter.err {
1106             Some(err) => Err(err),
1107             None => Ok(v),
1108         }
1109     }
1110 }