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