]>
Commit | Line | Data |
---|---|---|
1a4d82fc JJ |
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 | ||
54a0048b | 11 | //! Error handling with the `Result` type. |
1a4d82fc JJ |
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 | //! ``` | |
92a42be0 | 19 | //! # #[allow(dead_code)] |
1a4d82fc JJ |
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 | //! ``` | |
85aaf69f | 34 | //! #[derive(Debug)] |
1a4d82fc JJ |
35 | //! enum Version { Version1, Version2 } |
36 | //! | |
37 | //! fn parse_version(header: &[u8]) -> Result<Version, &'static str> { | |
9346a6ac AL |
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") | |
1a4d82fc JJ |
43 | //! } |
44 | //! } | |
45 | //! | |
46 | //! let version = parse_version(&[1, 2, 3, 4]); | |
47 | //! match version { | |
9346a6ac AL |
48 | //! Ok(v) => println!("working with version: {:?}", v), |
49 | //! Err(e) => println!("error parsing header: {:?}", e), | |
1a4d82fc JJ |
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 | //! ``` | |
c34b1796 AL |
58 | //! let good_result: Result<i32, i32> = Ok(10); |
59 | //! let bad_result: Result<i32, i32> = Err(10); | |
1a4d82fc JJ |
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. | |
c34b1796 AL |
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); | |
1a4d82fc JJ |
68 | //! |
69 | //! // Use `and_then` to continue the computation. | |
c34b1796 | 70 | //! let good_result: Result<bool, i32> = good_result.and_then(|i| Ok(i == 11)); |
1a4d82fc JJ |
71 | //! |
72 | //! // Use `or_else` to handle the error. | |
9346a6ac | 73 | //! let bad_result: Result<i32, i32> = bad_result.or_else(|i| Ok(i + 20)); |
1a4d82fc JJ |
74 | //! |
75 | //! // Consume the result and return the contents with `unwrap`. | |
c34b1796 | 76 | //! let final_awesome_result = good_result.unwrap(); |
1a4d82fc JJ |
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 | //! | |
9346a6ac AL |
89 | //! Consider the `write_all` method defined for I/O types |
90 | //! by the [`Write`](../../std/io/trait.Write.html) trait: | |
1a4d82fc JJ |
91 | //! |
92 | //! ``` | |
9346a6ac | 93 | //! use std::io; |
1a4d82fc | 94 | //! |
9346a6ac AL |
95 | //! trait Write { |
96 | //! fn write_all(&mut self, bytes: &[u8]) -> Result<(), io::Error>; | |
1a4d82fc JJ |
97 | //! } |
98 | //! ``` | |
99 | //! | |
9346a6ac AL |
100 | //! *Note: The actual definition of `Write` uses `io::Result`, which |
101 | //! is just a synonym for `Result<T, io::Error>`.* | |
1a4d82fc JJ |
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 | //! | |
9346a6ac | 107 | //! ```no_run |
92a42be0 | 108 | //! # #![allow(unused_must_use)] // \o/ |
9346a6ac AL |
109 | //! use std::fs::File; |
110 | //! use std::io::prelude::*; | |
1a4d82fc | 111 | //! |
9346a6ac AL |
112 | //! let mut file = File::create("valuable_data.txt").unwrap(); |
113 | //! // If `write_all` errors, then we'll never know, because the return | |
1a4d82fc | 114 | //! // value is ignored. |
9346a6ac | 115 | //! file.write_all(b"important message"); |
1a4d82fc JJ |
116 | //! ``` |
117 | //! | |
85aaf69f | 118 | //! If you *do* write that in Rust, the compiler will give you a |
1a4d82fc JJ |
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 | |
92a42be0 SL |
122 | //! assert success with `expect`. This will panic if the |
123 | //! write fails, providing a marginally useful message indicating why: | |
1a4d82fc JJ |
124 | //! |
125 | //! ```{.no_run} | |
9346a6ac AL |
126 | //! use std::fs::File; |
127 | //! use std::io::prelude::*; | |
1a4d82fc | 128 | //! |
9346a6ac | 129 | //! let mut file = File::create("valuable_data.txt").unwrap(); |
92a42be0 | 130 | //! file.write_all(b"important message").expect("failed to write message"); |
1a4d82fc JJ |
131 | //! ``` |
132 | //! | |
133 | //! You might also simply assert success: | |
134 | //! | |
135 | //! ```{.no_run} | |
9346a6ac AL |
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()); | |
1a4d82fc JJ |
140 | //! ``` |
141 | //! | |
142 | //! Or propagate the error up the call stack with `try!`: | |
143 | //! | |
144 | //! ``` | |
9346a6ac AL |
145 | //! # use std::fs::File; |
146 | //! # use std::io::prelude::*; | |
147 | //! # use std::io; | |
92a42be0 | 148 | //! # #[allow(dead_code)] |
9346a6ac AL |
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(()) | |
1a4d82fc JJ |
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 | //! ``` | |
92a42be0 | 166 | //! # #![allow(dead_code)] |
9346a6ac AL |
167 | //! use std::fs::File; |
168 | //! use std::io::prelude::*; | |
169 | //! use std::io; | |
1a4d82fc JJ |
170 | //! |
171 | //! struct Info { | |
172 | //! name: String, | |
c34b1796 AL |
173 | //! age: i32, |
174 | //! rating: i32, | |
1a4d82fc JJ |
175 | //! } |
176 | //! | |
9346a6ac AL |
177 | //! fn write_info(info: &Info) -> io::Result<()> { |
178 | //! let mut file = try!(File::create("my_best_friends.txt")); | |
1a4d82fc | 179 | //! // Early return on error |
9346a6ac | 180 | //! if let Err(e) = file.write_all(format!("name: {}\n", info.name).as_bytes()) { |
85aaf69f | 181 | //! return Err(e) |
1a4d82fc | 182 | //! } |
9346a6ac | 183 | //! if let Err(e) = file.write_all(format!("age: {}\n", info.age).as_bytes()) { |
85aaf69f | 184 | //! return Err(e) |
1a4d82fc | 185 | //! } |
9346a6ac AL |
186 | //! if let Err(e) = file.write_all(format!("rating: {}\n", info.rating).as_bytes()) { |
187 | //! return Err(e) | |
188 | //! } | |
189 | //! Ok(()) | |
1a4d82fc JJ |
190 | //! } |
191 | //! ``` | |
192 | //! | |
193 | //! With this: | |
194 | //! | |
195 | //! ``` | |
92a42be0 | 196 | //! # #![allow(dead_code)] |
9346a6ac AL |
197 | //! use std::fs::File; |
198 | //! use std::io::prelude::*; | |
199 | //! use std::io; | |
1a4d82fc JJ |
200 | //! |
201 | //! struct Info { | |
202 | //! name: String, | |
c34b1796 AL |
203 | //! age: i32, |
204 | //! rating: i32, | |
1a4d82fc JJ |
205 | //! } |
206 | //! | |
9346a6ac AL |
207 | //! fn write_info(info: &Info) -> io::Result<()> { |
208 | //! let mut file = try!(File::create("my_best_friends.txt")); | |
1a4d82fc | 209 | //! // Early return on error |
9346a6ac AL |
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(()) | |
1a4d82fc JJ |
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 | //! ``` | |
1a4d82fc JJ |
225 | //! macro_rules! try { |
226 | //! ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) }) | |
227 | //! } | |
1a4d82fc JJ |
228 | //! ``` |
229 | //! | |
62682a34 SL |
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. | |
1a4d82fc | 233 | |
85aaf69f | 234 | #![stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
235 | |
236 | use self::Result::{Ok, Err}; | |
237 | ||
238 | use clone::Clone; | |
85aaf69f | 239 | use fmt; |
c34b1796 | 240 | use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSizeIterator, IntoIterator}; |
e9174d1e | 241 | use ops::FnOnce; |
1a4d82fc | 242 | use option::Option::{self, None, Some}; |
1a4d82fc JJ |
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. | |
85aaf69f | 247 | #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] |
1a4d82fc | 248 | #[must_use] |
85aaf69f | 249 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
250 | pub enum Result<T, E> { |
251 | /// Contains the success value | |
85aaf69f | 252 | #[stable(feature = "rust1", since = "1.0.0")] |
7453a54e | 253 | Ok(#[stable(feature = "rust1", since = "1.0.0")] T), |
1a4d82fc JJ |
254 | |
255 | /// Contains the error value | |
85aaf69f | 256 | #[stable(feature = "rust1", since = "1.0.0")] |
7453a54e | 257 | Err(#[stable(feature = "rust1", since = "1.0.0")] E) |
1a4d82fc JJ |
258 | } |
259 | ||
260 | ///////////////////////////////////////////////////////////////////////////// | |
261 | // Type implementation | |
262 | ///////////////////////////////////////////////////////////////////////////// | |
263 | ||
1a4d82fc JJ |
264 | impl<T, E> Result<T, E> { |
265 | ///////////////////////////////////////////////////////////////////////// | |
266 | // Querying the contained values | |
267 | ///////////////////////////////////////////////////////////////////////// | |
268 | ||
269 | /// Returns true if the result is `Ok` | |
270 | /// | |
c34b1796 | 271 | /// # Examples |
1a4d82fc JJ |
272 | /// |
273 | /// ``` | |
c34b1796 | 274 | /// let x: Result<i32, &str> = Ok(-3); |
1a4d82fc JJ |
275 | /// assert_eq!(x.is_ok(), true); |
276 | /// | |
c34b1796 | 277 | /// let x: Result<i32, &str> = Err("Some error message"); |
1a4d82fc JJ |
278 | /// assert_eq!(x.is_ok(), false); |
279 | /// ``` | |
280 | #[inline] | |
85aaf69f | 281 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
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 | /// | |
c34b1796 | 291 | /// # Examples |
1a4d82fc JJ |
292 | /// |
293 | /// ``` | |
c34b1796 | 294 | /// let x: Result<i32, &str> = Ok(-3); |
1a4d82fc JJ |
295 | /// assert_eq!(x.is_err(), false); |
296 | /// | |
c34b1796 | 297 | /// let x: Result<i32, &str> = Err("Some error message"); |
1a4d82fc JJ |
298 | /// assert_eq!(x.is_err(), true); |
299 | /// ``` | |
300 | #[inline] | |
85aaf69f | 301 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
302 | pub fn is_err(&self) -> bool { |
303 | !self.is_ok() | |
304 | } | |
305 | ||
306 | ///////////////////////////////////////////////////////////////////////// | |
307 | // Adapter for each variant | |
308 | ///////////////////////////////////////////////////////////////////////// | |
309 | ||
9346a6ac | 310 | /// Converts from `Result<T, E>` to `Option<T>` |
1a4d82fc JJ |
311 | /// |
312 | /// Converts `self` into an `Option<T>`, consuming `self`, | |
313 | /// and discarding the error, if any. | |
314 | /// | |
c34b1796 | 315 | /// # Examples |
1a4d82fc JJ |
316 | /// |
317 | /// ``` | |
85aaf69f | 318 | /// let x: Result<u32, &str> = Ok(2); |
1a4d82fc JJ |
319 | /// assert_eq!(x.ok(), Some(2)); |
320 | /// | |
85aaf69f | 321 | /// let x: Result<u32, &str> = Err("Nothing here"); |
1a4d82fc JJ |
322 | /// assert_eq!(x.ok(), None); |
323 | /// ``` | |
324 | #[inline] | |
85aaf69f | 325 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
326 | pub fn ok(self) -> Option<T> { |
327 | match self { | |
328 | Ok(x) => Some(x), | |
329 | Err(_) => None, | |
330 | } | |
331 | } | |
332 | ||
9346a6ac | 333 | /// Converts from `Result<T, E>` to `Option<E>` |
1a4d82fc JJ |
334 | /// |
335 | /// Converts `self` into an `Option<E>`, consuming `self`, | |
c34b1796 | 336 | /// and discarding the success value, if any. |
1a4d82fc | 337 | /// |
c34b1796 | 338 | /// # Examples |
1a4d82fc JJ |
339 | /// |
340 | /// ``` | |
85aaf69f | 341 | /// let x: Result<u32, &str> = Ok(2); |
1a4d82fc JJ |
342 | /// assert_eq!(x.err(), None); |
343 | /// | |
85aaf69f | 344 | /// let x: Result<u32, &str> = Err("Nothing here"); |
1a4d82fc JJ |
345 | /// assert_eq!(x.err(), Some("Nothing here")); |
346 | /// ``` | |
347 | #[inline] | |
85aaf69f | 348 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
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 | ||
9346a6ac | 360 | /// Converts from `Result<T, E>` to `Result<&T, &E>` |
1a4d82fc JJ |
361 | /// |
362 | /// Produces a new `Result`, containing a reference | |
363 | /// into the original, leaving the original in place. | |
364 | /// | |
365 | /// ``` | |
85aaf69f | 366 | /// let x: Result<u32, &str> = Ok(2); |
1a4d82fc JJ |
367 | /// assert_eq!(x.as_ref(), Ok(&2)); |
368 | /// | |
85aaf69f | 369 | /// let x: Result<u32, &str> = Err("Error"); |
1a4d82fc JJ |
370 | /// assert_eq!(x.as_ref(), Err(&"Error")); |
371 | /// ``` | |
372 | #[inline] | |
85aaf69f | 373 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
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 | ||
9346a6ac | 381 | /// Converts from `Result<T, E>` to `Result<&mut T, &mut E>` |
1a4d82fc JJ |
382 | /// |
383 | /// ``` | |
c34b1796 | 384 | /// fn mutate(r: &mut Result<i32, i32>) { |
1a4d82fc JJ |
385 | /// match r.as_mut() { |
386 | /// Ok(&mut ref mut v) => *v = 42, | |
387 | /// Err(&mut ref mut e) => *e = 0, | |
388 | /// } | |
389 | /// } | |
390 | /// | |
c34b1796 | 391 | /// let mut x: Result<i32, i32> = Ok(2); |
1a4d82fc JJ |
392 | /// mutate(&mut x); |
393 | /// assert_eq!(x.unwrap(), 42); | |
394 | /// | |
c34b1796 | 395 | /// let mut x: Result<i32, i32> = Err(13); |
1a4d82fc JJ |
396 | /// mutate(&mut x); |
397 | /// assert_eq!(x.unwrap_err(), 0); | |
398 | /// ``` | |
399 | #[inline] | |
85aaf69f | 400 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
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 | ||
1a4d82fc JJ |
408 | ///////////////////////////////////////////////////////////////////////// |
409 | // Transforming contained values | |
410 | ///////////////////////////////////////////////////////////////////////// | |
411 | ||
92a42be0 | 412 | /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a |
1a4d82fc JJ |
413 | /// contained `Ok` value, leaving an `Err` value untouched. |
414 | /// | |
415 | /// This function can be used to compose the results of two functions. | |
416 | /// | |
c34b1796 | 417 | /// # Examples |
1a4d82fc | 418 | /// |
9346a6ac | 419 | /// Print the numbers on each line of a string multiplied by two. |
1a4d82fc JJ |
420 | /// |
421 | /// ``` | |
9346a6ac | 422 | /// let line = "1\n2\n3\n4\n"; |
1a4d82fc | 423 | /// |
9346a6ac AL |
424 | /// for num in line.lines() { |
425 | /// match num.parse::<i32>().map(|i| i * 2) { | |
426 | /// Ok(n) => println!("{}", n), | |
427 | /// Err(..) => {} | |
428 | /// } | |
1a4d82fc | 429 | /// } |
1a4d82fc JJ |
430 | /// ``` |
431 | #[inline] | |
85aaf69f | 432 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
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 | ||
92a42be0 | 440 | /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a |
1a4d82fc JJ |
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 | /// | |
c34b1796 | 446 | /// # Examples |
1a4d82fc JJ |
447 | /// |
448 | /// ``` | |
85aaf69f | 449 | /// fn stringify(x: u32) -> String { format!("error code: {}", x) } |
1a4d82fc | 450 | /// |
85aaf69f SL |
451 | /// let x: Result<u32, u32> = Ok(2); |
452 | /// assert_eq!(x.map_err(stringify), Ok(2)); | |
1a4d82fc | 453 | /// |
85aaf69f | 454 | /// let x: Result<u32, u32> = Err(13); |
1a4d82fc JJ |
455 | /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string())); |
456 | /// ``` | |
457 | #[inline] | |
85aaf69f | 458 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
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 | /// | |
c34b1796 | 472 | /// # Examples |
1a4d82fc JJ |
473 | /// |
474 | /// ``` | |
85aaf69f | 475 | /// let x: Result<u32, &str> = Ok(7); |
1a4d82fc JJ |
476 | /// assert_eq!(x.iter().next(), Some(&7)); |
477 | /// | |
85aaf69f | 478 | /// let x: Result<u32, &str> = Err("nothing!"); |
1a4d82fc JJ |
479 | /// assert_eq!(x.iter().next(), None); |
480 | /// ``` | |
481 | #[inline] | |
85aaf69f | 482 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
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 | /// | |
c34b1796 | 489 | /// # Examples |
1a4d82fc JJ |
490 | /// |
491 | /// ``` | |
85aaf69f | 492 | /// let mut x: Result<u32, &str> = Ok(7); |
1a4d82fc | 493 | /// match x.iter_mut().next() { |
b039eaaf | 494 | /// Some(v) => *v = 40, |
1a4d82fc JJ |
495 | /// None => {}, |
496 | /// } | |
497 | /// assert_eq!(x, Ok(40)); | |
498 | /// | |
85aaf69f | 499 | /// let mut x: Result<u32, &str> = Err("nothing!"); |
1a4d82fc JJ |
500 | /// assert_eq!(x.iter_mut().next(), None); |
501 | /// ``` | |
502 | #[inline] | |
85aaf69f | 503 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
504 | pub fn iter_mut(&mut self) -> IterMut<T> { |
505 | IterMut { inner: self.as_mut().ok() } | |
506 | } | |
507 | ||
1a4d82fc JJ |
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 | /// | |
c34b1796 | 514 | /// # Examples |
1a4d82fc JJ |
515 | /// |
516 | /// ``` | |
85aaf69f | 517 | /// let x: Result<u32, &str> = Ok(2); |
1a4d82fc JJ |
518 | /// let y: Result<&str, &str> = Err("late error"); |
519 | /// assert_eq!(x.and(y), Err("late error")); | |
520 | /// | |
85aaf69f | 521 | /// let x: Result<u32, &str> = Err("early error"); |
1a4d82fc JJ |
522 | /// let y: Result<&str, &str> = Ok("foo"); |
523 | /// assert_eq!(x.and(y), Err("early error")); | |
524 | /// | |
85aaf69f | 525 | /// let x: Result<u32, &str> = Err("not a 2"); |
1a4d82fc JJ |
526 | /// let y: Result<&str, &str> = Err("late error"); |
527 | /// assert_eq!(x.and(y), Err("not a 2")); | |
528 | /// | |
85aaf69f | 529 | /// let x: Result<u32, &str> = Ok(2); |
1a4d82fc JJ |
530 | /// let y: Result<&str, &str> = Ok("different result type"); |
531 | /// assert_eq!(x.and(y), Ok("different result type")); | |
532 | /// ``` | |
533 | #[inline] | |
85aaf69f | 534 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
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 | /// | |
c34b1796 | 546 | /// # Examples |
1a4d82fc JJ |
547 | /// |
548 | /// ``` | |
85aaf69f SL |
549 | /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) } |
550 | /// fn err(x: u32) -> Result<u32, u32> { Err(x) } | |
1a4d82fc JJ |
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] | |
85aaf69f | 558 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
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 | /// | |
c34b1796 | 568 | /// # Examples |
1a4d82fc JJ |
569 | /// |
570 | /// ``` | |
85aaf69f SL |
571 | /// let x: Result<u32, &str> = Ok(2); |
572 | /// let y: Result<u32, &str> = Err("late error"); | |
1a4d82fc JJ |
573 | /// assert_eq!(x.or(y), Ok(2)); |
574 | /// | |
85aaf69f SL |
575 | /// let x: Result<u32, &str> = Err("early error"); |
576 | /// let y: Result<u32, &str> = Ok(2); | |
1a4d82fc JJ |
577 | /// assert_eq!(x.or(y), Ok(2)); |
578 | /// | |
85aaf69f SL |
579 | /// let x: Result<u32, &str> = Err("not a 2"); |
580 | /// let y: Result<u32, &str> = Err("late error"); | |
1a4d82fc JJ |
581 | /// assert_eq!(x.or(y), Err("late error")); |
582 | /// | |
85aaf69f SL |
583 | /// let x: Result<u32, &str> = Ok(2); |
584 | /// let y: Result<u32, &str> = Ok(100); | |
1a4d82fc JJ |
585 | /// assert_eq!(x.or(y), Ok(2)); |
586 | /// ``` | |
587 | #[inline] | |
85aaf69f | 588 | #[stable(feature = "rust1", since = "1.0.0")] |
c34b1796 | 589 | pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> { |
1a4d82fc | 590 | match self { |
c34b1796 | 591 | Ok(v) => Ok(v), |
1a4d82fc JJ |
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 | /// | |
c34b1796 | 600 | /// # Examples |
1a4d82fc JJ |
601 | /// |
602 | /// ``` | |
85aaf69f SL |
603 | /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) } |
604 | /// fn err(x: u32) -> Result<u32, u32> { Err(x) } | |
1a4d82fc JJ |
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] | |
85aaf69f | 612 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
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 | /// | |
c34b1796 | 623 | /// # Examples |
1a4d82fc JJ |
624 | /// |
625 | /// ``` | |
85aaf69f SL |
626 | /// let optb = 2; |
627 | /// let x: Result<u32, &str> = Ok(9); | |
628 | /// assert_eq!(x.unwrap_or(optb), 9); | |
1a4d82fc | 629 | /// |
85aaf69f | 630 | /// let x: Result<u32, &str> = Err("error"); |
1a4d82fc JJ |
631 | /// assert_eq!(x.unwrap_or(optb), optb); |
632 | /// ``` | |
633 | #[inline] | |
85aaf69f | 634 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
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 | /// | |
c34b1796 | 645 | /// # Examples |
1a4d82fc JJ |
646 | /// |
647 | /// ``` | |
85aaf69f | 648 | /// fn count(x: &str) -> usize { x.len() } |
1a4d82fc | 649 | /// |
85aaf69f SL |
650 | /// assert_eq!(Ok(2).unwrap_or_else(count), 2); |
651 | /// assert_eq!(Err("foo").unwrap_or_else(count), 3); | |
1a4d82fc JJ |
652 | /// ``` |
653 | #[inline] | |
85aaf69f | 654 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
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 | ||
85aaf69f | 663 | impl<T, E: fmt::Debug> Result<T, E> { |
1a4d82fc JJ |
664 | /// Unwraps a result, yielding the content of an `Ok`. |
665 | /// | |
666 | /// # Panics | |
667 | /// | |
9346a6ac AL |
668 | /// Panics if the value is an `Err`, with a panic message provided by the |
669 | /// `Err`'s value. | |
1a4d82fc | 670 | /// |
c34b1796 | 671 | /// # Examples |
1a4d82fc JJ |
672 | /// |
673 | /// ``` | |
85aaf69f SL |
674 | /// let x: Result<u32, &str> = Ok(2); |
675 | /// assert_eq!(x.unwrap(), 2); | |
1a4d82fc JJ |
676 | /// ``` |
677 | /// | |
c34b1796 | 678 | /// ```{.should_panic} |
85aaf69f | 679 | /// let x: Result<u32, &str> = Err("emergency failure"); |
1a4d82fc JJ |
680 | /// x.unwrap(); // panics with `emergency failure` |
681 | /// ``` | |
682 | #[inline] | |
85aaf69f | 683 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
684 | pub fn unwrap(self) -> T { |
685 | match self { | |
686 | Ok(t) => t, | |
7453a54e | 687 | Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", e), |
1a4d82fc JJ |
688 | } |
689 | } | |
62682a34 SL |
690 | |
691 | /// Unwraps a result, yielding the content of an `Ok`. | |
692 | /// | |
9cc50fc6 SL |
693 | /// # Panics |
694 | /// | |
62682a34 SL |
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} | |
62682a34 SL |
700 | /// let x: Result<u32, &str> = Err("emergency failure"); |
701 | /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure` | |
702 | /// ``` | |
703 | #[inline] | |
e9174d1e | 704 | #[stable(feature = "result_expect", since = "1.4.0")] |
62682a34 SL |
705 | pub fn expect(self, msg: &str) -> T { |
706 | match self { | |
707 | Ok(t) => t, | |
7453a54e | 708 | Err(e) => unwrap_failed(msg, e), |
62682a34 SL |
709 | } |
710 | } | |
1a4d82fc JJ |
711 | } |
712 | ||
85aaf69f | 713 | impl<T: fmt::Debug, E> Result<T, E> { |
1a4d82fc JJ |
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 | /// | |
c34b1796 | 721 | /// # Examples |
1a4d82fc | 722 | /// |
c34b1796 | 723 | /// ```{.should_panic} |
85aaf69f | 724 | /// let x: Result<u32, &str> = Ok(2); |
1a4d82fc JJ |
725 | /// x.unwrap_err(); // panics with `2` |
726 | /// ``` | |
727 | /// | |
728 | /// ``` | |
85aaf69f | 729 | /// let x: Result<u32, &str> = Err("emergency failure"); |
1a4d82fc JJ |
730 | /// assert_eq!(x.unwrap_err(), "emergency failure"); |
731 | /// ``` | |
732 | #[inline] | |
85aaf69f | 733 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
734 | pub fn unwrap_err(self) -> E { |
735 | match self { | |
7453a54e SL |
736 | Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", t), |
737 | Err(e) => e, | |
1a4d82fc JJ |
738 | } |
739 | } | |
740 | } | |
741 | ||
7453a54e SL |
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 | ||
1a4d82fc JJ |
749 | ///////////////////////////////////////////////////////////////////////////// |
750 | // Trait implementations | |
751 | ///////////////////////////////////////////////////////////////////////////// | |
752 | ||
9346a6ac AL |
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 | /// ``` | |
1a4d82fc | 771 | #[inline] |
9346a6ac AL |
772 | fn into_iter(self) -> IntoIter<T> { |
773 | IntoIter { inner: self.ok() } | |
1a4d82fc JJ |
774 | } |
775 | } | |
776 | ||
e9174d1e SL |
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 | ||
1a4d82fc JJ |
797 | ///////////////////////////////////////////////////////////////////////////// |
798 | // The Result Iterators | |
799 | ///////////////////////////////////////////////////////////////////////////// | |
800 | ||
801 | /// An iterator over a reference to the `Ok` variant of a `Result`. | |
54a0048b | 802 | #[derive(Debug)] |
85aaf69f | 803 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
804 | pub struct Iter<'a, T: 'a> { inner: Option<&'a T> } |
805 | ||
85aaf69f | 806 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
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] | |
85aaf69f | 813 | fn size_hint(&self) -> (usize, Option<usize>) { |
1a4d82fc JJ |
814 | let n = if self.inner.is_some() {1} else {0}; |
815 | (n, Some(n)) | |
816 | } | |
817 | } | |
818 | ||
85aaf69f | 819 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
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 | ||
85aaf69f | 825 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
826 | impl<'a, T> ExactSizeIterator for Iter<'a, T> {} |
827 | ||
92a42be0 | 828 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
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`. | |
54a0048b | 834 | #[derive(Debug)] |
85aaf69f | 835 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
836 | pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> } |
837 | ||
85aaf69f | 838 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
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] | |
85aaf69f | 845 | fn size_hint(&self) -> (usize, Option<usize>) { |
1a4d82fc JJ |
846 | let n = if self.inner.is_some() {1} else {0}; |
847 | (n, Some(n)) | |
848 | } | |
849 | } | |
850 | ||
85aaf69f | 851 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
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 | ||
85aaf69f | 857 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
858 | impl<'a, T> ExactSizeIterator for IterMut<'a, T> {} |
859 | ||
860 | /// An iterator over the value in a `Ok` variant of a `Result`. | |
54a0048b | 861 | #[derive(Debug)] |
85aaf69f | 862 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
863 | pub struct IntoIter<T> { inner: Option<T> } |
864 | ||
85aaf69f | 865 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
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] | |
85aaf69f | 872 | fn size_hint(&self) -> (usize, Option<usize>) { |
1a4d82fc JJ |
873 | let n = if self.inner.is_some() {1} else {0}; |
874 | (n, Some(n)) | |
875 | } | |
876 | } | |
877 | ||
85aaf69f | 878 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
879 | impl<T> DoubleEndedIterator for IntoIter<T> { |
880 | #[inline] | |
881 | fn next_back(&mut self) -> Option<T> { self.inner.take() } | |
882 | } | |
883 | ||
85aaf69f | 884 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
885 | impl<T> ExactSizeIterator for IntoIter<T> {} |
886 | ||
887 | ///////////////////////////////////////////////////////////////////////////// | |
888 | // FromIterator | |
889 | ///////////////////////////////////////////////////////////////////////////// | |
890 | ||
85aaf69f | 891 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
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 | /// | |
c34b1796 | 900 | /// ``` |
85aaf69f | 901 | /// use std::u32; |
1a4d82fc | 902 | /// |
85aaf69f SL |
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!") } | |
1a4d82fc JJ |
906 | /// else { Ok(x + 1) } |
907 | /// ).collect(); | |
85aaf69f | 908 | /// assert!(res == Ok(vec!(2, 3))); |
1a4d82fc JJ |
909 | /// ``` |
910 | #[inline] | |
85aaf69f | 911 | fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> { |
1a4d82fc JJ |
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 | ||
85aaf69f | 936 | let mut adapter = Adapter { iter: iter.into_iter(), err: None }; |
1a4d82fc JJ |
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 | } |