]> git.proxmox.com Git - rustc.git/blob - src/libcore/result.rs
Imported Upstream version 1.9.0+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>` 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`](../../std/io/trait.Write.html) 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 `try!`:
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 = try!(File::create("valuable_data.txt"));
151 //! try!(file.write_all(b"important message"));
152 //! Ok(())
153 //! }
154 //! ```
155 //!
156 //! # The `try!` macro
157 //!
158 //! When writing code that calls many functions that return the
159 //! `Result` type, the error handling can be tedious. The `try!`
160 //! macro 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 //! let mut file = try!(File::create("my_best_friends.txt"));
179 //! // Early return on error
180 //! if let Err(e) = file.write_all(format!("name: {}\n", info.name).as_bytes()) {
181 //! return Err(e)
182 //! }
183 //! if let Err(e) = file.write_all(format!("age: {}\n", info.age).as_bytes()) {
184 //! return Err(e)
185 //! }
186 //! if let Err(e) = file.write_all(format!("rating: {}\n", info.rating).as_bytes()) {
187 //! return Err(e)
188 //! }
189 //! Ok(())
190 //! }
191 //! ```
192 //!
193 //! With this:
194 //!
195 //! ```
196 //! # #![allow(dead_code)]
197 //! use std::fs::File;
198 //! use std::io::prelude::*;
199 //! use std::io;
200 //!
201 //! struct Info {
202 //! name: String,
203 //! age: i32,
204 //! rating: i32,
205 //! }
206 //!
207 //! fn write_info(info: &Info) -> io::Result<()> {
208 //! let mut file = try!(File::create("my_best_friends.txt"));
209 //! // Early return on error
210 //! try!(file.write_all(format!("name: {}\n", info.name).as_bytes()));
211 //! try!(file.write_all(format!("age: {}\n", info.age).as_bytes()));
212 //! try!(file.write_all(format!("rating: {}\n", info.rating).as_bytes()));
213 //! Ok(())
214 //! }
215 //! ```
216 //!
217 //! *It's much nicer!*
218 //!
219 //! Wrapping an expression in `try!` will result in the unwrapped
220 //! success (`Ok`) value, unless the result is `Err`, in which case
221 //! `Err` is returned early from the enclosing function. Its simple definition
222 //! makes it clear:
223 //!
224 //! ```
225 //! macro_rules! try {
226 //! ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
227 //! }
228 //! ```
229 //!
230 //! `try!` is imported by the prelude and is available everywhere, but it can only
231 //! be used in functions that return `Result` because of the early return of
232 //! `Err` that it provides.
233
234 #![stable(feature = "rust1", since = "1.0.0")]
235
236 use self::Result::{Ok, Err};
237
238 use clone::Clone;
239 use fmt;
240 use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSizeIterator, IntoIterator};
241 use ops::FnOnce;
242 use option::Option::{self, None, Some};
243
244 /// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
245 ///
246 /// See the [`std::result`](index.html) module documentation for details.
247 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
248 #[must_use]
249 #[stable(feature = "rust1", since = "1.0.0")]
250 pub enum Result<T, E> {
251 /// Contains the success value
252 #[stable(feature = "rust1", since = "1.0.0")]
253 Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
254
255 /// Contains the error value
256 #[stable(feature = "rust1", since = "1.0.0")]
257 Err(#[stable(feature = "rust1", since = "1.0.0")] E)
258 }
259
260 /////////////////////////////////////////////////////////////////////////////
261 // Type implementation
262 /////////////////////////////////////////////////////////////////////////////
263
264 impl<T, E> Result<T, E> {
265 /////////////////////////////////////////////////////////////////////////
266 // Querying the contained values
267 /////////////////////////////////////////////////////////////////////////
268
269 /// Returns true if the result is `Ok`
270 ///
271 /// # Examples
272 ///
273 /// ```
274 /// let x: Result<i32, &str> = Ok(-3);
275 /// assert_eq!(x.is_ok(), true);
276 ///
277 /// let x: Result<i32, &str> = Err("Some error message");
278 /// assert_eq!(x.is_ok(), false);
279 /// ```
280 #[inline]
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub fn is_ok(&self) -> bool {
283 match *self {
284 Ok(_) => true,
285 Err(_) => false
286 }
287 }
288
289 /// Returns true if the result is `Err`
290 ///
291 /// # Examples
292 ///
293 /// ```
294 /// let x: Result<i32, &str> = Ok(-3);
295 /// assert_eq!(x.is_err(), false);
296 ///
297 /// let x: Result<i32, &str> = Err("Some error message");
298 /// assert_eq!(x.is_err(), true);
299 /// ```
300 #[inline]
301 #[stable(feature = "rust1", since = "1.0.0")]
302 pub fn is_err(&self) -> bool {
303 !self.is_ok()
304 }
305
306 /////////////////////////////////////////////////////////////////////////
307 // Adapter for each variant
308 /////////////////////////////////////////////////////////////////////////
309
310 /// Converts from `Result<T, E>` to `Option<T>`
311 ///
312 /// Converts `self` into an `Option<T>`, consuming `self`,
313 /// and discarding the error, if any.
314 ///
315 /// # Examples
316 ///
317 /// ```
318 /// let x: Result<u32, &str> = Ok(2);
319 /// assert_eq!(x.ok(), Some(2));
320 ///
321 /// let x: Result<u32, &str> = Err("Nothing here");
322 /// assert_eq!(x.ok(), None);
323 /// ```
324 #[inline]
325 #[stable(feature = "rust1", since = "1.0.0")]
326 pub fn ok(self) -> Option<T> {
327 match self {
328 Ok(x) => Some(x),
329 Err(_) => None,
330 }
331 }
332
333 /// Converts from `Result<T, E>` to `Option<E>`
334 ///
335 /// Converts `self` into an `Option<E>`, consuming `self`,
336 /// and discarding the success value, if any.
337 ///
338 /// # Examples
339 ///
340 /// ```
341 /// let x: Result<u32, &str> = Ok(2);
342 /// assert_eq!(x.err(), None);
343 ///
344 /// let x: Result<u32, &str> = Err("Nothing here");
345 /// assert_eq!(x.err(), Some("Nothing here"));
346 /// ```
347 #[inline]
348 #[stable(feature = "rust1", since = "1.0.0")]
349 pub fn err(self) -> Option<E> {
350 match self {
351 Ok(_) => None,
352 Err(x) => Some(x),
353 }
354 }
355
356 /////////////////////////////////////////////////////////////////////////
357 // Adapter for working with references
358 /////////////////////////////////////////////////////////////////////////
359
360 /// Converts from `Result<T, E>` to `Result<&T, &E>`
361 ///
362 /// Produces a new `Result`, containing a reference
363 /// into the original, leaving the original in place.
364 ///
365 /// ```
366 /// let x: Result<u32, &str> = Ok(2);
367 /// assert_eq!(x.as_ref(), Ok(&2));
368 ///
369 /// let x: Result<u32, &str> = Err("Error");
370 /// assert_eq!(x.as_ref(), Err(&"Error"));
371 /// ```
372 #[inline]
373 #[stable(feature = "rust1", since = "1.0.0")]
374 pub fn as_ref(&self) -> Result<&T, &E> {
375 match *self {
376 Ok(ref x) => Ok(x),
377 Err(ref x) => Err(x),
378 }
379 }
380
381 /// Converts from `Result<T, E>` to `Result<&mut T, &mut E>`
382 ///
383 /// ```
384 /// fn mutate(r: &mut Result<i32, i32>) {
385 /// match r.as_mut() {
386 /// Ok(&mut ref mut v) => *v = 42,
387 /// Err(&mut ref mut e) => *e = 0,
388 /// }
389 /// }
390 ///
391 /// let mut x: Result<i32, i32> = Ok(2);
392 /// mutate(&mut x);
393 /// assert_eq!(x.unwrap(), 42);
394 ///
395 /// let mut x: Result<i32, i32> = Err(13);
396 /// mutate(&mut x);
397 /// assert_eq!(x.unwrap_err(), 0);
398 /// ```
399 #[inline]
400 #[stable(feature = "rust1", since = "1.0.0")]
401 pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
402 match *self {
403 Ok(ref mut x) => Ok(x),
404 Err(ref mut x) => Err(x),
405 }
406 }
407
408 /////////////////////////////////////////////////////////////////////////
409 // Transforming contained values
410 /////////////////////////////////////////////////////////////////////////
411
412 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
413 /// contained `Ok` value, leaving an `Err` value untouched.
414 ///
415 /// This function can be used to compose the results of two functions.
416 ///
417 /// # Examples
418 ///
419 /// Print the numbers on each line of a string multiplied by two.
420 ///
421 /// ```
422 /// let line = "1\n2\n3\n4\n";
423 ///
424 /// for num in line.lines() {
425 /// match num.parse::<i32>().map(|i| i * 2) {
426 /// Ok(n) => println!("{}", n),
427 /// Err(..) => {}
428 /// }
429 /// }
430 /// ```
431 #[inline]
432 #[stable(feature = "rust1", since = "1.0.0")]
433 pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
434 match self {
435 Ok(t) => Ok(op(t)),
436 Err(e) => Err(e)
437 }
438 }
439
440 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
441 /// contained `Err` value, leaving an `Ok` value untouched.
442 ///
443 /// This function can be used to pass through a successful result while handling
444 /// an error.
445 ///
446 /// # Examples
447 ///
448 /// ```
449 /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
450 ///
451 /// let x: Result<u32, u32> = Ok(2);
452 /// assert_eq!(x.map_err(stringify), Ok(2));
453 ///
454 /// let x: Result<u32, u32> = Err(13);
455 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
456 /// ```
457 #[inline]
458 #[stable(feature = "rust1", since = "1.0.0")]
459 pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> {
460 match self {
461 Ok(t) => Ok(t),
462 Err(e) => Err(op(e))
463 }
464 }
465
466 /////////////////////////////////////////////////////////////////////////
467 // Iterator constructors
468 /////////////////////////////////////////////////////////////////////////
469
470 /// Returns an iterator over the possibly contained value.
471 ///
472 /// # Examples
473 ///
474 /// ```
475 /// let x: Result<u32, &str> = Ok(7);
476 /// assert_eq!(x.iter().next(), Some(&7));
477 ///
478 /// let x: Result<u32, &str> = Err("nothing!");
479 /// assert_eq!(x.iter().next(), None);
480 /// ```
481 #[inline]
482 #[stable(feature = "rust1", since = "1.0.0")]
483 pub fn iter(&self) -> Iter<T> {
484 Iter { inner: self.as_ref().ok() }
485 }
486
487 /// Returns a mutable iterator over the possibly contained value.
488 ///
489 /// # Examples
490 ///
491 /// ```
492 /// let mut x: Result<u32, &str> = Ok(7);
493 /// match x.iter_mut().next() {
494 /// Some(v) => *v = 40,
495 /// None => {},
496 /// }
497 /// assert_eq!(x, Ok(40));
498 ///
499 /// let mut x: Result<u32, &str> = Err("nothing!");
500 /// assert_eq!(x.iter_mut().next(), None);
501 /// ```
502 #[inline]
503 #[stable(feature = "rust1", since = "1.0.0")]
504 pub fn iter_mut(&mut self) -> IterMut<T> {
505 IterMut { inner: self.as_mut().ok() }
506 }
507
508 ////////////////////////////////////////////////////////////////////////
509 // Boolean operations on the values, eager and lazy
510 /////////////////////////////////////////////////////////////////////////
511
512 /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
513 ///
514 /// # Examples
515 ///
516 /// ```
517 /// let x: Result<u32, &str> = Ok(2);
518 /// let y: Result<&str, &str> = Err("late error");
519 /// assert_eq!(x.and(y), Err("late error"));
520 ///
521 /// let x: Result<u32, &str> = Err("early error");
522 /// let y: Result<&str, &str> = Ok("foo");
523 /// assert_eq!(x.and(y), Err("early error"));
524 ///
525 /// let x: Result<u32, &str> = Err("not a 2");
526 /// let y: Result<&str, &str> = Err("late error");
527 /// assert_eq!(x.and(y), Err("not a 2"));
528 ///
529 /// let x: Result<u32, &str> = Ok(2);
530 /// let y: Result<&str, &str> = Ok("different result type");
531 /// assert_eq!(x.and(y), Ok("different result type"));
532 /// ```
533 #[inline]
534 #[stable(feature = "rust1", since = "1.0.0")]
535 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
536 match self {
537 Ok(_) => res,
538 Err(e) => Err(e),
539 }
540 }
541
542 /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
543 ///
544 /// This function can be used for control flow based on result values.
545 ///
546 /// # Examples
547 ///
548 /// ```
549 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
550 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
551 ///
552 /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
553 /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
554 /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
555 /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
556 /// ```
557 #[inline]
558 #[stable(feature = "rust1", since = "1.0.0")]
559 pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
560 match self {
561 Ok(t) => op(t),
562 Err(e) => Err(e),
563 }
564 }
565
566 /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
567 ///
568 /// # Examples
569 ///
570 /// ```
571 /// let x: Result<u32, &str> = Ok(2);
572 /// let y: Result<u32, &str> = Err("late error");
573 /// assert_eq!(x.or(y), Ok(2));
574 ///
575 /// let x: Result<u32, &str> = Err("early error");
576 /// let y: Result<u32, &str> = Ok(2);
577 /// assert_eq!(x.or(y), Ok(2));
578 ///
579 /// let x: Result<u32, &str> = Err("not a 2");
580 /// let y: Result<u32, &str> = Err("late error");
581 /// assert_eq!(x.or(y), Err("late error"));
582 ///
583 /// let x: Result<u32, &str> = Ok(2);
584 /// let y: Result<u32, &str> = Ok(100);
585 /// assert_eq!(x.or(y), Ok(2));
586 /// ```
587 #[inline]
588 #[stable(feature = "rust1", since = "1.0.0")]
589 pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
590 match self {
591 Ok(v) => Ok(v),
592 Err(_) => res,
593 }
594 }
595
596 /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
597 ///
598 /// This function can be used for control flow based on result values.
599 ///
600 /// # Examples
601 ///
602 /// ```
603 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
604 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
605 ///
606 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
607 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
608 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
609 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
610 /// ```
611 #[inline]
612 #[stable(feature = "rust1", since = "1.0.0")]
613 pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
614 match self {
615 Ok(t) => Ok(t),
616 Err(e) => op(e),
617 }
618 }
619
620 /// Unwraps a result, yielding the content of an `Ok`.
621 /// Else it returns `optb`.
622 ///
623 /// # Examples
624 ///
625 /// ```
626 /// let optb = 2;
627 /// let x: Result<u32, &str> = Ok(9);
628 /// assert_eq!(x.unwrap_or(optb), 9);
629 ///
630 /// let x: Result<u32, &str> = Err("error");
631 /// assert_eq!(x.unwrap_or(optb), optb);
632 /// ```
633 #[inline]
634 #[stable(feature = "rust1", since = "1.0.0")]
635 pub fn unwrap_or(self, optb: T) -> T {
636 match self {
637 Ok(t) => t,
638 Err(_) => optb
639 }
640 }
641
642 /// Unwraps a result, yielding the content of an `Ok`.
643 /// If the value is an `Err` then it calls `op` with its value.
644 ///
645 /// # Examples
646 ///
647 /// ```
648 /// fn count(x: &str) -> usize { x.len() }
649 ///
650 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
651 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
652 /// ```
653 #[inline]
654 #[stable(feature = "rust1", since = "1.0.0")]
655 pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
656 match self {
657 Ok(t) => t,
658 Err(e) => op(e)
659 }
660 }
661 }
662
663 impl<T, E: fmt::Debug> Result<T, E> {
664 /// Unwraps a result, yielding the content of an `Ok`.
665 ///
666 /// # Panics
667 ///
668 /// Panics if the value is an `Err`, with a panic message provided by the
669 /// `Err`'s value.
670 ///
671 /// # Examples
672 ///
673 /// ```
674 /// let x: Result<u32, &str> = Ok(2);
675 /// assert_eq!(x.unwrap(), 2);
676 /// ```
677 ///
678 /// ```{.should_panic}
679 /// let x: Result<u32, &str> = Err("emergency failure");
680 /// x.unwrap(); // panics with `emergency failure`
681 /// ```
682 #[inline]
683 #[stable(feature = "rust1", since = "1.0.0")]
684 pub fn unwrap(self) -> T {
685 match self {
686 Ok(t) => t,
687 Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", e),
688 }
689 }
690
691 /// Unwraps a result, yielding the content of an `Ok`.
692 ///
693 /// # Panics
694 ///
695 /// Panics if the value is an `Err`, with a panic message including the
696 /// passed message, and the content of the `Err`.
697 ///
698 /// # Examples
699 /// ```{.should_panic}
700 /// let x: Result<u32, &str> = Err("emergency failure");
701 /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
702 /// ```
703 #[inline]
704 #[stable(feature = "result_expect", since = "1.4.0")]
705 pub fn expect(self, msg: &str) -> T {
706 match self {
707 Ok(t) => t,
708 Err(e) => unwrap_failed(msg, e),
709 }
710 }
711 }
712
713 impl<T: fmt::Debug, E> Result<T, E> {
714 /// Unwraps a result, yielding the content of an `Err`.
715 ///
716 /// # Panics
717 ///
718 /// Panics if the value is an `Ok`, with a custom panic message provided
719 /// by the `Ok`'s value.
720 ///
721 /// # Examples
722 ///
723 /// ```{.should_panic}
724 /// let x: Result<u32, &str> = Ok(2);
725 /// x.unwrap_err(); // panics with `2`
726 /// ```
727 ///
728 /// ```
729 /// let x: Result<u32, &str> = Err("emergency failure");
730 /// assert_eq!(x.unwrap_err(), "emergency failure");
731 /// ```
732 #[inline]
733 #[stable(feature = "rust1", since = "1.0.0")]
734 pub fn unwrap_err(self) -> E {
735 match self {
736 Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", t),
737 Err(e) => e,
738 }
739 }
740 }
741
742 // This is a separate function to reduce the code size of the methods
743 #[inline(never)]
744 #[cold]
745 fn unwrap_failed<E: fmt::Debug>(msg: &str, error: E) -> ! {
746 panic!("{}: {:?}", msg, error)
747 }
748
749 /////////////////////////////////////////////////////////////////////////////
750 // Trait implementations
751 /////////////////////////////////////////////////////////////////////////////
752
753 #[stable(feature = "rust1", since = "1.0.0")]
754 impl<T, E> IntoIterator for Result<T, E> {
755 type Item = T;
756 type IntoIter = IntoIter<T>;
757
758 /// Returns a consuming iterator over the possibly contained value.
759 ///
760 /// # Examples
761 ///
762 /// ```
763 /// let x: Result<u32, &str> = Ok(5);
764 /// let v: Vec<u32> = x.into_iter().collect();
765 /// assert_eq!(v, [5]);
766 ///
767 /// let x: Result<u32, &str> = Err("nothing!");
768 /// let v: Vec<u32> = x.into_iter().collect();
769 /// assert_eq!(v, []);
770 /// ```
771 #[inline]
772 fn into_iter(self) -> IntoIter<T> {
773 IntoIter { inner: self.ok() }
774 }
775 }
776
777 #[stable(since = "1.4.0", feature = "result_iter")]
778 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
779 type Item = &'a T;
780 type IntoIter = Iter<'a, T>;
781
782 fn into_iter(self) -> Iter<'a, T> {
783 self.iter()
784 }
785 }
786
787 #[stable(since = "1.4.0", feature = "result_iter")]
788 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
789 type Item = &'a mut T;
790 type IntoIter = IterMut<'a, T>;
791
792 fn into_iter(mut self) -> IterMut<'a, T> {
793 self.iter_mut()
794 }
795 }
796
797 /////////////////////////////////////////////////////////////////////////////
798 // The Result Iterators
799 /////////////////////////////////////////////////////////////////////////////
800
801 /// An iterator over a reference to the `Ok` variant of a `Result`.
802 #[derive(Debug)]
803 #[stable(feature = "rust1", since = "1.0.0")]
804 pub struct Iter<'a, T: 'a> { inner: Option<&'a T> }
805
806 #[stable(feature = "rust1", since = "1.0.0")]
807 impl<'a, T> Iterator for Iter<'a, T> {
808 type Item = &'a T;
809
810 #[inline]
811 fn next(&mut self) -> Option<&'a T> { self.inner.take() }
812 #[inline]
813 fn size_hint(&self) -> (usize, Option<usize>) {
814 let n = if self.inner.is_some() {1} else {0};
815 (n, Some(n))
816 }
817 }
818
819 #[stable(feature = "rust1", since = "1.0.0")]
820 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
821 #[inline]
822 fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
823 }
824
825 #[stable(feature = "rust1", since = "1.0.0")]
826 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
827
828 #[stable(feature = "rust1", since = "1.0.0")]
829 impl<'a, T> Clone for Iter<'a, T> {
830 fn clone(&self) -> Iter<'a, T> { Iter { inner: self.inner } }
831 }
832
833 /// An iterator over a mutable reference to the `Ok` variant of a `Result`.
834 #[derive(Debug)]
835 #[stable(feature = "rust1", since = "1.0.0")]
836 pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
837
838 #[stable(feature = "rust1", since = "1.0.0")]
839 impl<'a, T> Iterator for IterMut<'a, T> {
840 type Item = &'a mut T;
841
842 #[inline]
843 fn next(&mut self) -> Option<&'a mut T> { self.inner.take() }
844 #[inline]
845 fn size_hint(&self) -> (usize, Option<usize>) {
846 let n = if self.inner.is_some() {1} else {0};
847 (n, Some(n))
848 }
849 }
850
851 #[stable(feature = "rust1", since = "1.0.0")]
852 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
853 #[inline]
854 fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
855 }
856
857 #[stable(feature = "rust1", since = "1.0.0")]
858 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
859
860 /// An iterator over the value in a `Ok` variant of a `Result`.
861 #[derive(Debug)]
862 #[stable(feature = "rust1", since = "1.0.0")]
863 pub struct IntoIter<T> { inner: Option<T> }
864
865 #[stable(feature = "rust1", since = "1.0.0")]
866 impl<T> Iterator for IntoIter<T> {
867 type Item = T;
868
869 #[inline]
870 fn next(&mut self) -> Option<T> { self.inner.take() }
871 #[inline]
872 fn size_hint(&self) -> (usize, Option<usize>) {
873 let n = if self.inner.is_some() {1} else {0};
874 (n, Some(n))
875 }
876 }
877
878 #[stable(feature = "rust1", since = "1.0.0")]
879 impl<T> DoubleEndedIterator for IntoIter<T> {
880 #[inline]
881 fn next_back(&mut self) -> Option<T> { self.inner.take() }
882 }
883
884 #[stable(feature = "rust1", since = "1.0.0")]
885 impl<T> ExactSizeIterator for IntoIter<T> {}
886
887 /////////////////////////////////////////////////////////////////////////////
888 // FromIterator
889 /////////////////////////////////////////////////////////////////////////////
890
891 #[stable(feature = "rust1", since = "1.0.0")]
892 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
893 /// Takes each element in the `Iterator`: if it is an `Err`, no further
894 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
895 /// container with the values of each `Result` is returned.
896 ///
897 /// Here is an example which increments every integer in a vector,
898 /// checking for overflow:
899 ///
900 /// ```
901 /// use std::u32;
902 ///
903 /// let v = vec!(1, 2);
904 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|&x: &u32|
905 /// if x == u32::MAX { Err("Overflow!") }
906 /// else { Ok(x + 1) }
907 /// ).collect();
908 /// assert!(res == Ok(vec!(2, 3)));
909 /// ```
910 #[inline]
911 fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
912 // FIXME(#11084): This could be replaced with Iterator::scan when this
913 // performance bug is closed.
914
915 struct Adapter<Iter, E> {
916 iter: Iter,
917 err: Option<E>,
918 }
919
920 impl<T, E, Iter: Iterator<Item=Result<T, E>>> Iterator for Adapter<Iter, E> {
921 type Item = T;
922
923 #[inline]
924 fn next(&mut self) -> Option<T> {
925 match self.iter.next() {
926 Some(Ok(value)) => Some(value),
927 Some(Err(err)) => {
928 self.err = Some(err);
929 None
930 }
931 None => None,
932 }
933 }
934 }
935
936 let mut adapter = Adapter { iter: iter.into_iter(), err: None };
937 let v: V = FromIterator::from_iter(adapter.by_ref());
938
939 match adapter.err {
940 Some(err) => Err(err),
941 None => Ok(v),
942 }
943 }
944 }