]> git.proxmox.com Git - rustc.git/blob - src/libcore/result.rs
e909946ece40221ffa548666aed832ce44b2e9fd
[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 //! enum Result<T, E> {
20 //! Ok(T),
21 //! Err(E)
22 //! }
23 //! ```
24 //!
25 //! Functions return `Result` whenever errors are expected and
26 //! recoverable. In the `std` crate `Result` is most prominently used
27 //! for [I/O](../../std/io/index.html).
28 //!
29 //! A simple function returning `Result` might be
30 //! defined and used like so:
31 //!
32 //! ```
33 //! #[derive(Debug)]
34 //! enum Version { Version1, Version2 }
35 //!
36 //! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
37 //! match header.get(0) {
38 //! None => Err("invalid header length"),
39 //! Some(&1) => Ok(Version::Version1),
40 //! Some(&2) => Ok(Version::Version2),
41 //! Some(_) => Err("invalid version")
42 //! }
43 //! }
44 //!
45 //! let version = parse_version(&[1, 2, 3, 4]);
46 //! match version {
47 //! Ok(v) => println!("working with version: {:?}", v),
48 //! Err(e) => println!("error parsing header: {:?}", e),
49 //! }
50 //! ```
51 //!
52 //! Pattern matching on `Result`s is clear and straightforward for
53 //! simple cases, but `Result` comes with some convenience methods
54 //! that make working with it more succinct.
55 //!
56 //! ```
57 //! let good_result: Result<i32, i32> = Ok(10);
58 //! let bad_result: Result<i32, i32> = Err(10);
59 //!
60 //! // The `is_ok` and `is_err` methods do what they say.
61 //! assert!(good_result.is_ok() && !good_result.is_err());
62 //! assert!(bad_result.is_err() && !bad_result.is_ok());
63 //!
64 //! // `map` consumes the `Result` and produces another.
65 //! let good_result: Result<i32, i32> = good_result.map(|i| i + 1);
66 //! let bad_result: Result<i32, i32> = bad_result.map(|i| i - 1);
67 //!
68 //! // Use `and_then` to continue the computation.
69 //! let good_result: Result<bool, i32> = good_result.and_then(|i| Ok(i == 11));
70 //!
71 //! // Use `or_else` to handle the error.
72 //! let bad_result: Result<i32, i32> = bad_result.or_else(|i| Ok(i + 20));
73 //!
74 //! // Consume the result and return the contents with `unwrap`.
75 //! let final_awesome_result = good_result.unwrap();
76 //! ```
77 //!
78 //! # Results must be used
79 //!
80 //! A common problem with using return values to indicate errors is
81 //! that it is easy to ignore the return value, thus failing to handle
82 //! the error. Result is annotated with the #[must_use] attribute,
83 //! which will cause the compiler to issue a warning when a Result
84 //! value is ignored. This makes `Result` especially useful with
85 //! functions that may encounter errors but don't otherwise return a
86 //! useful value.
87 //!
88 //! Consider the `write_all` method defined for I/O types
89 //! by the [`Write`](../../std/io/trait.Write.html) trait:
90 //!
91 //! ```
92 //! use std::io;
93 //!
94 //! trait Write {
95 //! fn write_all(&mut self, bytes: &[u8]) -> Result<(), io::Error>;
96 //! }
97 //! ```
98 //!
99 //! *Note: The actual definition of `Write` uses `io::Result`, which
100 //! is just a synonym for `Result<T, io::Error>`.*
101 //!
102 //! This method doesn't produce a value, but the write may
103 //! fail. It's crucial to handle the error case, and *not* write
104 //! something like this:
105 //!
106 //! ```no_run
107 //! use std::fs::File;
108 //! use std::io::prelude::*;
109 //!
110 //! let mut file = File::create("valuable_data.txt").unwrap();
111 //! // If `write_all` errors, then we'll never know, because the return
112 //! // value is ignored.
113 //! file.write_all(b"important message");
114 //! ```
115 //!
116 //! If you *do* write that in Rust, the compiler will give you a
117 //! warning (by default, controlled by the `unused_must_use` lint).
118 //!
119 //! You might instead, if you don't want to handle the error, simply
120 //! panic, by converting to an `Option` with `ok`, then asserting
121 //! success with `expect`. This will panic if the write fails, proving
122 //! a marginally useful message indicating why:
123 //!
124 //! ```{.no_run}
125 //! use std::fs::File;
126 //! use std::io::prelude::*;
127 //!
128 //! let mut file = File::create("valuable_data.txt").unwrap();
129 //! file.write_all(b"important message").ok().expect("failed to write message");
130 //! ```
131 //!
132 //! You might also simply assert success:
133 //!
134 //! ```{.no_run}
135 //! # use std::fs::File;
136 //! # use std::io::prelude::*;
137 //! # let mut file = File::create("valuable_data.txt").unwrap();
138 //! assert!(file.write_all(b"important message").is_ok());
139 //! ```
140 //!
141 //! Or propagate the error up the call stack with `try!`:
142 //!
143 //! ```
144 //! # use std::fs::File;
145 //! # use std::io::prelude::*;
146 //! # use std::io;
147 //! fn write_message() -> io::Result<()> {
148 //! let mut file = try!(File::create("valuable_data.txt"));
149 //! try!(file.write_all(b"important message"));
150 //! Ok(())
151 //! }
152 //! ```
153 //!
154 //! # The `try!` macro
155 //!
156 //! When writing code that calls many functions that return the
157 //! `Result` type, the error handling can be tedious. The `try!`
158 //! macro hides some of the boilerplate of propagating errors up the
159 //! call stack.
160 //!
161 //! It replaces this:
162 //!
163 //! ```
164 //! use std::fs::File;
165 //! use std::io::prelude::*;
166 //! use std::io;
167 //!
168 //! struct Info {
169 //! name: String,
170 //! age: i32,
171 //! rating: i32,
172 //! }
173 //!
174 //! fn write_info(info: &Info) -> io::Result<()> {
175 //! let mut file = try!(File::create("my_best_friends.txt"));
176 //! // Early return on error
177 //! if let Err(e) = file.write_all(format!("name: {}\n", info.name).as_bytes()) {
178 //! return Err(e)
179 //! }
180 //! if let Err(e) = file.write_all(format!("age: {}\n", info.age).as_bytes()) {
181 //! return Err(e)
182 //! }
183 //! if let Err(e) = file.write_all(format!("rating: {}\n", info.rating).as_bytes()) {
184 //! return Err(e)
185 //! }
186 //! Ok(())
187 //! }
188 //! ```
189 //!
190 //! With this:
191 //!
192 //! ```
193 //! use std::fs::File;
194 //! use std::io::prelude::*;
195 //! use std::io;
196 //!
197 //! struct Info {
198 //! name: String,
199 //! age: i32,
200 //! rating: i32,
201 //! }
202 //!
203 //! fn write_info(info: &Info) -> io::Result<()> {
204 //! let mut file = try!(File::create("my_best_friends.txt"));
205 //! // Early return on error
206 //! try!(file.write_all(format!("name: {}\n", info.name).as_bytes()));
207 //! try!(file.write_all(format!("age: {}\n", info.age).as_bytes()));
208 //! try!(file.write_all(format!("rating: {}\n", info.rating).as_bytes()));
209 //! Ok(())
210 //! }
211 //! ```
212 //!
213 //! *It's much nicer!*
214 //!
215 //! Wrapping an expression in `try!` will result in the unwrapped
216 //! success (`Ok`) value, unless the result is `Err`, in which case
217 //! `Err` is returned early from the enclosing function. Its simple definition
218 //! makes it clear:
219 //!
220 //! ```
221 //! macro_rules! try {
222 //! ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
223 //! }
224 //! ```
225 //!
226 //! `try!` is imported by the prelude, and is available everywhere.
227
228 #![stable(feature = "rust1", since = "1.0.0")]
229
230 use self::Result::{Ok, Err};
231
232 use clone::Clone;
233 use fmt;
234 use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSizeIterator, IntoIterator};
235 use ops::{FnMut, FnOnce};
236 use option::Option::{self, None, Some};
237 use slice;
238
239 /// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
240 ///
241 /// See the [`std::result`](index.html) module documentation for details.
242 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
243 #[must_use]
244 #[stable(feature = "rust1", since = "1.0.0")]
245 pub enum Result<T, E> {
246 /// Contains the success value
247 #[stable(feature = "rust1", since = "1.0.0")]
248 Ok(T),
249
250 /// Contains the error value
251 #[stable(feature = "rust1", since = "1.0.0")]
252 Err(E)
253 }
254
255 /////////////////////////////////////////////////////////////////////////////
256 // Type implementation
257 /////////////////////////////////////////////////////////////////////////////
258
259 #[stable(feature = "rust1", since = "1.0.0")]
260 impl<T, E> Result<T, E> {
261 /////////////////////////////////////////////////////////////////////////
262 // Querying the contained values
263 /////////////////////////////////////////////////////////////////////////
264
265 /// Returns true if the result is `Ok`
266 ///
267 /// # Examples
268 ///
269 /// ```
270 /// let x: Result<i32, &str> = Ok(-3);
271 /// assert_eq!(x.is_ok(), true);
272 ///
273 /// let x: Result<i32, &str> = Err("Some error message");
274 /// assert_eq!(x.is_ok(), false);
275 /// ```
276 #[inline]
277 #[stable(feature = "rust1", since = "1.0.0")]
278 pub fn is_ok(&self) -> bool {
279 match *self {
280 Ok(_) => true,
281 Err(_) => false
282 }
283 }
284
285 /// Returns true if the result is `Err`
286 ///
287 /// # Examples
288 ///
289 /// ```
290 /// let x: Result<i32, &str> = Ok(-3);
291 /// assert_eq!(x.is_err(), false);
292 ///
293 /// let x: Result<i32, &str> = Err("Some error message");
294 /// assert_eq!(x.is_err(), true);
295 /// ```
296 #[inline]
297 #[stable(feature = "rust1", since = "1.0.0")]
298 pub fn is_err(&self) -> bool {
299 !self.is_ok()
300 }
301
302 /////////////////////////////////////////////////////////////////////////
303 // Adapter for each variant
304 /////////////////////////////////////////////////////////////////////////
305
306 /// Converts from `Result<T, E>` to `Option<T>`
307 ///
308 /// Converts `self` into an `Option<T>`, consuming `self`,
309 /// and discarding the error, if any.
310 ///
311 /// # Examples
312 ///
313 /// ```
314 /// let x: Result<u32, &str> = Ok(2);
315 /// assert_eq!(x.ok(), Some(2));
316 ///
317 /// let x: Result<u32, &str> = Err("Nothing here");
318 /// assert_eq!(x.ok(), None);
319 /// ```
320 #[inline]
321 #[stable(feature = "rust1", since = "1.0.0")]
322 pub fn ok(self) -> Option<T> {
323 match self {
324 Ok(x) => Some(x),
325 Err(_) => None,
326 }
327 }
328
329 /// Converts from `Result<T, E>` to `Option<E>`
330 ///
331 /// Converts `self` into an `Option<E>`, consuming `self`,
332 /// and discarding the success value, if any.
333 ///
334 /// # Examples
335 ///
336 /// ```
337 /// let x: Result<u32, &str> = Ok(2);
338 /// assert_eq!(x.err(), None);
339 ///
340 /// let x: Result<u32, &str> = Err("Nothing here");
341 /// assert_eq!(x.err(), Some("Nothing here"));
342 /// ```
343 #[inline]
344 #[stable(feature = "rust1", since = "1.0.0")]
345 pub fn err(self) -> Option<E> {
346 match self {
347 Ok(_) => None,
348 Err(x) => Some(x),
349 }
350 }
351
352 /////////////////////////////////////////////////////////////////////////
353 // Adapter for working with references
354 /////////////////////////////////////////////////////////////////////////
355
356 /// Converts from `Result<T, E>` to `Result<&T, &E>`
357 ///
358 /// Produces a new `Result`, containing a reference
359 /// into the original, leaving the original in place.
360 ///
361 /// ```
362 /// let x: Result<u32, &str> = Ok(2);
363 /// assert_eq!(x.as_ref(), Ok(&2));
364 ///
365 /// let x: Result<u32, &str> = Err("Error");
366 /// assert_eq!(x.as_ref(), Err(&"Error"));
367 /// ```
368 #[inline]
369 #[stable(feature = "rust1", since = "1.0.0")]
370 pub fn as_ref(&self) -> Result<&T, &E> {
371 match *self {
372 Ok(ref x) => Ok(x),
373 Err(ref x) => Err(x),
374 }
375 }
376
377 /// Converts from `Result<T, E>` to `Result<&mut T, &mut E>`
378 ///
379 /// ```
380 /// fn mutate(r: &mut Result<i32, i32>) {
381 /// match r.as_mut() {
382 /// Ok(&mut ref mut v) => *v = 42,
383 /// Err(&mut ref mut e) => *e = 0,
384 /// }
385 /// }
386 ///
387 /// let mut x: Result<i32, i32> = Ok(2);
388 /// mutate(&mut x);
389 /// assert_eq!(x.unwrap(), 42);
390 ///
391 /// let mut x: Result<i32, i32> = Err(13);
392 /// mutate(&mut x);
393 /// assert_eq!(x.unwrap_err(), 0);
394 /// ```
395 #[inline]
396 #[stable(feature = "rust1", since = "1.0.0")]
397 pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
398 match *self {
399 Ok(ref mut x) => Ok(x),
400 Err(ref mut x) => Err(x),
401 }
402 }
403
404 /// Converts from `Result<T, E>` to `&[T]` (without copying)
405 #[inline]
406 #[unstable(feature = "as_slice", since = "unsure of the utility here")]
407 pub fn as_slice(&self) -> &[T] {
408 match *self {
409 Ok(ref x) => slice::ref_slice(x),
410 Err(_) => {
411 // work around lack of implicit coercion from fixed-size array to slice
412 let emp: &[_] = &[];
413 emp
414 }
415 }
416 }
417
418 /// Converts from `Result<T, E>` to `&mut [T]` (without copying)
419 ///
420 /// ```
421 /// # #![feature(core)]
422 /// let mut x: Result<&str, u32> = Ok("Gold");
423 /// {
424 /// let v = x.as_mut_slice();
425 /// assert!(v == ["Gold"]);
426 /// v[0] = "Silver";
427 /// assert!(v == ["Silver"]);
428 /// }
429 /// assert_eq!(x, Ok("Silver"));
430 ///
431 /// let mut x: Result<&str, u32> = Err(45);
432 /// assert!(x.as_mut_slice().is_empty());
433 /// ```
434 #[inline]
435 #[unstable(feature = "core",
436 reason = "waiting for mut conventions")]
437 pub fn as_mut_slice(&mut self) -> &mut [T] {
438 match *self {
439 Ok(ref mut x) => slice::mut_ref_slice(x),
440 Err(_) => {
441 // work around lack of implicit coercion from fixed-size array to slice
442 let emp: &mut [_] = &mut [];
443 emp
444 }
445 }
446 }
447
448 /////////////////////////////////////////////////////////////////////////
449 // Transforming contained values
450 /////////////////////////////////////////////////////////////////////////
451
452 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to an
453 /// contained `Ok` value, leaving an `Err` value untouched.
454 ///
455 /// This function can be used to compose the results of two functions.
456 ///
457 /// # Examples
458 ///
459 /// Print the numbers on each line of a string multiplied by two.
460 ///
461 /// ```
462 /// let line = "1\n2\n3\n4\n";
463 ///
464 /// for num in line.lines() {
465 /// match num.parse::<i32>().map(|i| i * 2) {
466 /// Ok(n) => println!("{}", n),
467 /// Err(..) => {}
468 /// }
469 /// }
470 /// ```
471 #[inline]
472 #[stable(feature = "rust1", since = "1.0.0")]
473 pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
474 match self {
475 Ok(t) => Ok(op(t)),
476 Err(e) => Err(e)
477 }
478 }
479
480 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to an
481 /// contained `Err` value, leaving an `Ok` value untouched.
482 ///
483 /// This function can be used to pass through a successful result while handling
484 /// an error.
485 ///
486 /// # Examples
487 ///
488 /// ```
489 /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
490 ///
491 /// let x: Result<u32, u32> = Ok(2);
492 /// assert_eq!(x.map_err(stringify), Ok(2));
493 ///
494 /// let x: Result<u32, u32> = Err(13);
495 /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
496 /// ```
497 #[inline]
498 #[stable(feature = "rust1", since = "1.0.0")]
499 pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> {
500 match self {
501 Ok(t) => Ok(t),
502 Err(e) => Err(op(e))
503 }
504 }
505
506 /////////////////////////////////////////////////////////////////////////
507 // Iterator constructors
508 /////////////////////////////////////////////////////////////////////////
509
510 /// Returns an iterator over the possibly contained value.
511 ///
512 /// # Examples
513 ///
514 /// ```
515 /// let x: Result<u32, &str> = Ok(7);
516 /// assert_eq!(x.iter().next(), Some(&7));
517 ///
518 /// let x: Result<u32, &str> = Err("nothing!");
519 /// assert_eq!(x.iter().next(), None);
520 /// ```
521 #[inline]
522 #[stable(feature = "rust1", since = "1.0.0")]
523 pub fn iter(&self) -> Iter<T> {
524 Iter { inner: self.as_ref().ok() }
525 }
526
527 /// Returns a mutable iterator over the possibly contained value.
528 ///
529 /// # Examples
530 ///
531 /// ```
532 /// let mut x: Result<u32, &str> = Ok(7);
533 /// match x.iter_mut().next() {
534 /// Some(&mut ref mut x) => *x = 40,
535 /// None => {},
536 /// }
537 /// assert_eq!(x, Ok(40));
538 ///
539 /// let mut x: Result<u32, &str> = Err("nothing!");
540 /// assert_eq!(x.iter_mut().next(), None);
541 /// ```
542 #[inline]
543 #[stable(feature = "rust1", since = "1.0.0")]
544 pub fn iter_mut(&mut self) -> IterMut<T> {
545 IterMut { inner: self.as_mut().ok() }
546 }
547
548 ////////////////////////////////////////////////////////////////////////
549 // Boolean operations on the values, eager and lazy
550 /////////////////////////////////////////////////////////////////////////
551
552 /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
553 ///
554 /// # Examples
555 ///
556 /// ```
557 /// let x: Result<u32, &str> = Ok(2);
558 /// let y: Result<&str, &str> = Err("late error");
559 /// assert_eq!(x.and(y), Err("late error"));
560 ///
561 /// let x: Result<u32, &str> = Err("early error");
562 /// let y: Result<&str, &str> = Ok("foo");
563 /// assert_eq!(x.and(y), Err("early error"));
564 ///
565 /// let x: Result<u32, &str> = Err("not a 2");
566 /// let y: Result<&str, &str> = Err("late error");
567 /// assert_eq!(x.and(y), Err("not a 2"));
568 ///
569 /// let x: Result<u32, &str> = Ok(2);
570 /// let y: Result<&str, &str> = Ok("different result type");
571 /// assert_eq!(x.and(y), Ok("different result type"));
572 /// ```
573 #[inline]
574 #[stable(feature = "rust1", since = "1.0.0")]
575 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
576 match self {
577 Ok(_) => res,
578 Err(e) => Err(e),
579 }
580 }
581
582 /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
583 ///
584 /// This function can be used for control flow based on result values.
585 ///
586 /// # Examples
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 /// ```
611 /// let x: Result<u32, &str> = Ok(2);
612 /// let y: Result<u32, &str> = Err("late error");
613 /// assert_eq!(x.or(y), Ok(2));
614 ///
615 /// let x: Result<u32, &str> = Err("early error");
616 /// let y: Result<u32, &str> = Ok(2);
617 /// assert_eq!(x.or(y), Ok(2));
618 ///
619 /// let x: Result<u32, &str> = Err("not a 2");
620 /// let y: Result<u32, &str> = Err("late error");
621 /// assert_eq!(x.or(y), Err("late error"));
622 ///
623 /// let x: Result<u32, &str> = Ok(2);
624 /// let y: Result<u32, &str> = Ok(100);
625 /// assert_eq!(x.or(y), Ok(2));
626 /// ```
627 #[inline]
628 #[stable(feature = "rust1", since = "1.0.0")]
629 pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
630 match self {
631 Ok(v) => Ok(v),
632 Err(_) => res,
633 }
634 }
635
636 /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
637 ///
638 /// This function can be used for control flow based on result values.
639 ///
640 /// # Examples
641 ///
642 /// ```
643 /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
644 /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
645 ///
646 /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
647 /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
648 /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
649 /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
650 /// ```
651 #[inline]
652 #[stable(feature = "rust1", since = "1.0.0")]
653 pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
654 match self {
655 Ok(t) => Ok(t),
656 Err(e) => op(e),
657 }
658 }
659
660 /// Unwraps a result, yielding the content of an `Ok`.
661 /// Else it returns `optb`.
662 ///
663 /// # Examples
664 ///
665 /// ```
666 /// let optb = 2;
667 /// let x: Result<u32, &str> = Ok(9);
668 /// assert_eq!(x.unwrap_or(optb), 9);
669 ///
670 /// let x: Result<u32, &str> = Err("error");
671 /// assert_eq!(x.unwrap_or(optb), optb);
672 /// ```
673 #[inline]
674 #[stable(feature = "rust1", since = "1.0.0")]
675 pub fn unwrap_or(self, optb: T) -> T {
676 match self {
677 Ok(t) => t,
678 Err(_) => optb
679 }
680 }
681
682 /// Unwraps a result, yielding the content of an `Ok`.
683 /// If the value is an `Err` then it calls `op` with its value.
684 ///
685 /// # Examples
686 ///
687 /// ```
688 /// fn count(x: &str) -> usize { x.len() }
689 ///
690 /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
691 /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
692 /// ```
693 #[inline]
694 #[stable(feature = "rust1", since = "1.0.0")]
695 pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
696 match self {
697 Ok(t) => t,
698 Err(e) => op(e)
699 }
700 }
701 }
702
703 #[stable(feature = "rust1", since = "1.0.0")]
704 impl<T, E: fmt::Debug> Result<T, E> {
705 /// Unwraps a result, yielding the content of an `Ok`.
706 ///
707 /// # Panics
708 ///
709 /// Panics if the value is an `Err`, with a panic message provided by the
710 /// `Err`'s value.
711 ///
712 /// # Examples
713 ///
714 /// ```
715 /// let x: Result<u32, &str> = Ok(2);
716 /// assert_eq!(x.unwrap(), 2);
717 /// ```
718 ///
719 /// ```{.should_panic}
720 /// let x: Result<u32, &str> = Err("emergency failure");
721 /// x.unwrap(); // panics with `emergency failure`
722 /// ```
723 #[inline]
724 #[stable(feature = "rust1", since = "1.0.0")]
725 pub fn unwrap(self) -> T {
726 match self {
727 Ok(t) => t,
728 Err(e) =>
729 panic!("called `Result::unwrap()` on an `Err` value: {:?}", e)
730 }
731 }
732 }
733
734 #[stable(feature = "rust1", since = "1.0.0")]
735 impl<T: fmt::Debug, E> Result<T, E> {
736 /// Unwraps a result, yielding the content of an `Err`.
737 ///
738 /// # Panics
739 ///
740 /// Panics if the value is an `Ok`, with a custom panic message provided
741 /// by the `Ok`'s value.
742 ///
743 /// # Examples
744 ///
745 /// ```{.should_panic}
746 /// let x: Result<u32, &str> = Ok(2);
747 /// x.unwrap_err(); // panics with `2`
748 /// ```
749 ///
750 /// ```
751 /// let x: Result<u32, &str> = Err("emergency failure");
752 /// assert_eq!(x.unwrap_err(), "emergency failure");
753 /// ```
754 #[inline]
755 #[stable(feature = "rust1", since = "1.0.0")]
756 pub fn unwrap_err(self) -> E {
757 match self {
758 Ok(t) =>
759 panic!("called `Result::unwrap_err()` on an `Ok` value: {:?}", t),
760 Err(e) => e
761 }
762 }
763 }
764
765 /////////////////////////////////////////////////////////////////////////////
766 // Trait implementations
767 /////////////////////////////////////////////////////////////////////////////
768
769 #[stable(feature = "rust1", since = "1.0.0")]
770 impl<T, E> IntoIterator for Result<T, E> {
771 type Item = T;
772 type IntoIter = IntoIter<T>;
773
774 /// Returns a consuming iterator over the possibly contained value.
775 ///
776 /// # Examples
777 ///
778 /// ```
779 /// let x: Result<u32, &str> = Ok(5);
780 /// let v: Vec<u32> = x.into_iter().collect();
781 /// assert_eq!(v, [5]);
782 ///
783 /// let x: Result<u32, &str> = Err("nothing!");
784 /// let v: Vec<u32> = x.into_iter().collect();
785 /// assert_eq!(v, []);
786 /// ```
787 #[inline]
788 fn into_iter(self) -> IntoIter<T> {
789 IntoIter { inner: self.ok() }
790 }
791 }
792
793 /////////////////////////////////////////////////////////////////////////////
794 // The Result Iterators
795 /////////////////////////////////////////////////////////////////////////////
796
797 /// An iterator over a reference to the `Ok` variant of a `Result`.
798 #[stable(feature = "rust1", since = "1.0.0")]
799 pub struct Iter<'a, T: 'a> { inner: Option<&'a T> }
800
801 #[stable(feature = "rust1", since = "1.0.0")]
802 impl<'a, T> Iterator for Iter<'a, T> {
803 type Item = &'a T;
804
805 #[inline]
806 fn next(&mut self) -> Option<&'a T> { self.inner.take() }
807 #[inline]
808 fn size_hint(&self) -> (usize, Option<usize>) {
809 let n = if self.inner.is_some() {1} else {0};
810 (n, Some(n))
811 }
812 }
813
814 #[stable(feature = "rust1", since = "1.0.0")]
815 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
816 #[inline]
817 fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
818 }
819
820 #[stable(feature = "rust1", since = "1.0.0")]
821 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
822
823 impl<'a, T> Clone for Iter<'a, T> {
824 fn clone(&self) -> Iter<'a, T> { Iter { inner: self.inner } }
825 }
826
827 /// An iterator over a mutable reference to the `Ok` variant of a `Result`.
828 #[stable(feature = "rust1", since = "1.0.0")]
829 pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
830
831 #[stable(feature = "rust1", since = "1.0.0")]
832 impl<'a, T> Iterator for IterMut<'a, T> {
833 type Item = &'a mut T;
834
835 #[inline]
836 fn next(&mut self) -> Option<&'a mut T> { self.inner.take() }
837 #[inline]
838 fn size_hint(&self) -> (usize, Option<usize>) {
839 let n = if self.inner.is_some() {1} else {0};
840 (n, Some(n))
841 }
842 }
843
844 #[stable(feature = "rust1", since = "1.0.0")]
845 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
846 #[inline]
847 fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
848 }
849
850 #[stable(feature = "rust1", since = "1.0.0")]
851 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
852
853 /// An iterator over the value in a `Ok` variant of a `Result`.
854 #[stable(feature = "rust1", since = "1.0.0")]
855 pub struct IntoIter<T> { inner: Option<T> }
856
857 #[stable(feature = "rust1", since = "1.0.0")]
858 impl<T> Iterator for IntoIter<T> {
859 type Item = T;
860
861 #[inline]
862 fn next(&mut self) -> Option<T> { self.inner.take() }
863 #[inline]
864 fn size_hint(&self) -> (usize, Option<usize>) {
865 let n = if self.inner.is_some() {1} else {0};
866 (n, Some(n))
867 }
868 }
869
870 #[stable(feature = "rust1", since = "1.0.0")]
871 impl<T> DoubleEndedIterator for IntoIter<T> {
872 #[inline]
873 fn next_back(&mut self) -> Option<T> { self.inner.take() }
874 }
875
876 #[stable(feature = "rust1", since = "1.0.0")]
877 impl<T> ExactSizeIterator for IntoIter<T> {}
878
879 /////////////////////////////////////////////////////////////////////////////
880 // FromIterator
881 /////////////////////////////////////////////////////////////////////////////
882
883 #[stable(feature = "rust1", since = "1.0.0")]
884 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
885 /// Takes each element in the `Iterator`: if it is an `Err`, no further
886 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
887 /// container with the values of each `Result` is returned.
888 ///
889 /// Here is an example which increments every integer in a vector,
890 /// checking for overflow:
891 ///
892 /// ```
893 /// use std::u32;
894 ///
895 /// let v = vec!(1, 2);
896 /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|&x: &u32|
897 /// if x == u32::MAX { Err("Overflow!") }
898 /// else { Ok(x + 1) }
899 /// ).collect();
900 /// assert!(res == Ok(vec!(2, 3)));
901 /// ```
902 #[inline]
903 fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
904 // FIXME(#11084): This could be replaced with Iterator::scan when this
905 // performance bug is closed.
906
907 struct Adapter<Iter, E> {
908 iter: Iter,
909 err: Option<E>,
910 }
911
912 impl<T, E, Iter: Iterator<Item=Result<T, E>>> Iterator for Adapter<Iter, E> {
913 type Item = T;
914
915 #[inline]
916 fn next(&mut self) -> Option<T> {
917 match self.iter.next() {
918 Some(Ok(value)) => Some(value),
919 Some(Err(err)) => {
920 self.err = Some(err);
921 None
922 }
923 None => None,
924 }
925 }
926 }
927
928 let mut adapter = Adapter { iter: iter.into_iter(), err: None };
929 let v: V = FromIterator::from_iter(adapter.by_ref());
930
931 match adapter.err {
932 Some(err) => Err(err),
933 None => Ok(v),
934 }
935 }
936 }
937
938 /////////////////////////////////////////////////////////////////////////////
939 // FromIterator
940 /////////////////////////////////////////////////////////////////////////////
941
942 /// Performs a fold operation over the result values from an iterator.
943 ///
944 /// If an `Err` is encountered, it is immediately returned.
945 /// Otherwise, the folded value is returned.
946 #[inline]
947 #[unstable(feature = "core")]
948 pub fn fold<T,
949 V,
950 E,
951 F: FnMut(V, T) -> V,
952 Iter: Iterator<Item=Result<T, E>>>(
953 iterator: Iter,
954 mut init: V,
955 mut f: F)
956 -> Result<V, E> {
957 for t in iterator {
958 match t {
959 Ok(v) => init = f(init, v),
960 Err(u) => return Err(u)
961 }
962 }
963 Ok(init)
964 }