]>
Commit | Line | Data |
---|---|---|
54a0048b | 1 | //! Error handling with the `Result` type. |
1a4d82fc | 2 | //! |
9e0c209e SL |
3 | //! [`Result<T, E>`][`Result`] is the type used for returning and propagating |
4 | //! errors. It is an enum with the variants, [`Ok(T)`], representing | |
5 | //! success and containing a value, and [`Err(E)`], representing error | |
1a4d82fc JJ |
6 | //! and containing an error value. |
7 | //! | |
8 | //! ``` | |
92a42be0 | 9 | //! # #[allow(dead_code)] |
1a4d82fc JJ |
10 | //! enum Result<T, E> { |
11 | //! Ok(T), | |
a7813a04 | 12 | //! Err(E), |
1a4d82fc JJ |
13 | //! } |
14 | //! ``` | |
15 | //! | |
9e0c209e SL |
16 | //! Functions return [`Result`] whenever errors are expected and |
17 | //! recoverable. In the `std` crate, [`Result`] is most prominently used | |
1a4d82fc JJ |
18 | //! for [I/O](../../std/io/index.html). |
19 | //! | |
9e0c209e | 20 | //! A simple function returning [`Result`] might be |
1a4d82fc JJ |
21 | //! defined and used like so: |
22 | //! | |
23 | //! ``` | |
85aaf69f | 24 | //! #[derive(Debug)] |
1a4d82fc JJ |
25 | //! enum Version { Version1, Version2 } |
26 | //! | |
27 | //! fn parse_version(header: &[u8]) -> Result<Version, &'static str> { | |
9346a6ac AL |
28 | //! match header.get(0) { |
29 | //! None => Err("invalid header length"), | |
30 | //! Some(&1) => Ok(Version::Version1), | |
31 | //! Some(&2) => Ok(Version::Version2), | |
a7813a04 | 32 | //! Some(_) => Err("invalid version"), |
1a4d82fc JJ |
33 | //! } |
34 | //! } | |
35 | //! | |
36 | //! let version = parse_version(&[1, 2, 3, 4]); | |
37 | //! match version { | |
9346a6ac AL |
38 | //! Ok(v) => println!("working with version: {:?}", v), |
39 | //! Err(e) => println!("error parsing header: {:?}", e), | |
1a4d82fc JJ |
40 | //! } |
41 | //! ``` | |
42 | //! | |
9e0c209e SL |
43 | //! Pattern matching on [`Result`]s is clear and straightforward for |
44 | //! simple cases, but [`Result`] comes with some convenience methods | |
1a4d82fc JJ |
45 | //! that make working with it more succinct. |
46 | //! | |
47 | //! ``` | |
c34b1796 AL |
48 | //! let good_result: Result<i32, i32> = Ok(10); |
49 | //! let bad_result: Result<i32, i32> = Err(10); | |
1a4d82fc JJ |
50 | //! |
51 | //! // The `is_ok` and `is_err` methods do what they say. | |
52 | //! assert!(good_result.is_ok() && !good_result.is_err()); | |
53 | //! assert!(bad_result.is_err() && !bad_result.is_ok()); | |
54 | //! | |
55 | //! // `map` consumes the `Result` and produces another. | |
c34b1796 AL |
56 | //! let good_result: Result<i32, i32> = good_result.map(|i| i + 1); |
57 | //! let bad_result: Result<i32, i32> = bad_result.map(|i| i - 1); | |
1a4d82fc JJ |
58 | //! |
59 | //! // Use `and_then` to continue the computation. | |
c34b1796 | 60 | //! let good_result: Result<bool, i32> = good_result.and_then(|i| Ok(i == 11)); |
1a4d82fc JJ |
61 | //! |
62 | //! // Use `or_else` to handle the error. | |
9346a6ac | 63 | //! let bad_result: Result<i32, i32> = bad_result.or_else(|i| Ok(i + 20)); |
1a4d82fc JJ |
64 | //! |
65 | //! // Consume the result and return the contents with `unwrap`. | |
c34b1796 | 66 | //! let final_awesome_result = good_result.unwrap(); |
1a4d82fc JJ |
67 | //! ``` |
68 | //! | |
69 | //! # Results must be used | |
70 | //! | |
71 | //! A common problem with using return values to indicate errors is | |
72 | //! that it is easy to ignore the return value, thus failing to handle | |
9e0c209e | 73 | //! the error. [`Result`] is annotated with the `#[must_use]` attribute, |
1a4d82fc | 74 | //! which will cause the compiler to issue a warning when a Result |
9e0c209e | 75 | //! value is ignored. This makes [`Result`] especially useful with |
1a4d82fc JJ |
76 | //! functions that may encounter errors but don't otherwise return a |
77 | //! useful value. | |
78 | //! | |
9e0c209e SL |
79 | //! Consider the [`write_all`] method defined for I/O types |
80 | //! by the [`Write`] trait: | |
1a4d82fc JJ |
81 | //! |
82 | //! ``` | |
9346a6ac | 83 | //! use std::io; |
1a4d82fc | 84 | //! |
9346a6ac AL |
85 | //! trait Write { |
86 | //! fn write_all(&mut self, bytes: &[u8]) -> Result<(), io::Error>; | |
1a4d82fc JJ |
87 | //! } |
88 | //! ``` | |
89 | //! | |
9e0c209e SL |
90 | //! *Note: The actual definition of [`Write`] uses [`io::Result`], which |
91 | //! is just a synonym for [`Result`]`<T, `[`io::Error`]`>`.* | |
1a4d82fc JJ |
92 | //! |
93 | //! This method doesn't produce a value, but the write may | |
94 | //! fail. It's crucial to handle the error case, and *not* write | |
95 | //! something like this: | |
96 | //! | |
9346a6ac | 97 | //! ```no_run |
92a42be0 | 98 | //! # #![allow(unused_must_use)] // \o/ |
9346a6ac AL |
99 | //! use std::fs::File; |
100 | //! use std::io::prelude::*; | |
1a4d82fc | 101 | //! |
9346a6ac AL |
102 | //! let mut file = File::create("valuable_data.txt").unwrap(); |
103 | //! // If `write_all` errors, then we'll never know, because the return | |
1a4d82fc | 104 | //! // value is ignored. |
9346a6ac | 105 | //! file.write_all(b"important message"); |
1a4d82fc JJ |
106 | //! ``` |
107 | //! | |
85aaf69f | 108 | //! If you *do* write that in Rust, the compiler will give you a |
1a4d82fc JJ |
109 | //! warning (by default, controlled by the `unused_must_use` lint). |
110 | //! | |
111 | //! You might instead, if you don't want to handle the error, simply | |
9e0c209e | 112 | //! assert success with [`expect`]. This will panic if the |
92a42be0 | 113 | //! write fails, providing a marginally useful message indicating why: |
1a4d82fc JJ |
114 | //! |
115 | //! ```{.no_run} | |
9346a6ac AL |
116 | //! use std::fs::File; |
117 | //! use std::io::prelude::*; | |
1a4d82fc | 118 | //! |
9346a6ac | 119 | //! let mut file = File::create("valuable_data.txt").unwrap(); |
92a42be0 | 120 | //! file.write_all(b"important message").expect("failed to write message"); |
1a4d82fc JJ |
121 | //! ``` |
122 | //! | |
123 | //! You might also simply assert success: | |
124 | //! | |
125 | //! ```{.no_run} | |
9346a6ac AL |
126 | //! # use std::fs::File; |
127 | //! # use std::io::prelude::*; | |
128 | //! # let mut file = File::create("valuable_data.txt").unwrap(); | |
129 | //! assert!(file.write_all(b"important message").is_ok()); | |
1a4d82fc JJ |
130 | //! ``` |
131 | //! | |
8bb4bdeb | 132 | //! Or propagate the error up the call stack with [`?`]: |
1a4d82fc JJ |
133 | //! |
134 | //! ``` | |
9346a6ac AL |
135 | //! # use std::fs::File; |
136 | //! # use std::io::prelude::*; | |
137 | //! # use std::io; | |
92a42be0 | 138 | //! # #[allow(dead_code)] |
9346a6ac | 139 | //! fn write_message() -> io::Result<()> { |
8bb4bdeb XL |
140 | //! let mut file = File::create("valuable_data.txt")?; |
141 | //! file.write_all(b"important message")?; | |
9346a6ac | 142 | //! Ok(()) |
1a4d82fc JJ |
143 | //! } |
144 | //! ``` | |
145 | //! | |
ff7c6d11 | 146 | //! # The question mark operator, `?` |
1a4d82fc JJ |
147 | //! |
148 | //! When writing code that calls many functions that return the | |
ff7c6d11 XL |
149 | //! [`Result`] type, the error handling can be tedious. The question mark |
150 | //! operator, [`?`], hides some of the boilerplate of propagating errors | |
151 | //! up the call stack. | |
1a4d82fc JJ |
152 | //! |
153 | //! It replaces this: | |
154 | //! | |
155 | //! ``` | |
92a42be0 | 156 | //! # #![allow(dead_code)] |
9346a6ac AL |
157 | //! use std::fs::File; |
158 | //! use std::io::prelude::*; | |
159 | //! use std::io; | |
1a4d82fc JJ |
160 | //! |
161 | //! struct Info { | |
162 | //! name: String, | |
c34b1796 AL |
163 | //! age: i32, |
164 | //! rating: i32, | |
1a4d82fc JJ |
165 | //! } |
166 | //! | |
9346a6ac | 167 | //! fn write_info(info: &Info) -> io::Result<()> { |
1a4d82fc | 168 | //! // Early return on error |
3157f602 XL |
169 | //! let mut file = match File::create("my_best_friends.txt") { |
170 | //! Err(e) => return Err(e), | |
171 | //! Ok(f) => f, | |
172 | //! }; | |
9346a6ac | 173 | //! if let Err(e) = file.write_all(format!("name: {}\n", info.name).as_bytes()) { |
85aaf69f | 174 | //! return Err(e) |
1a4d82fc | 175 | //! } |
9346a6ac | 176 | //! if let Err(e) = file.write_all(format!("age: {}\n", info.age).as_bytes()) { |
85aaf69f | 177 | //! return Err(e) |
1a4d82fc | 178 | //! } |
9346a6ac AL |
179 | //! if let Err(e) = file.write_all(format!("rating: {}\n", info.rating).as_bytes()) { |
180 | //! return Err(e) | |
181 | //! } | |
182 | //! Ok(()) | |
1a4d82fc JJ |
183 | //! } |
184 | //! ``` | |
185 | //! | |
186 | //! With this: | |
187 | //! | |
188 | //! ``` | |
92a42be0 | 189 | //! # #![allow(dead_code)] |
9346a6ac AL |
190 | //! use std::fs::File; |
191 | //! use std::io::prelude::*; | |
192 | //! use std::io; | |
1a4d82fc JJ |
193 | //! |
194 | //! struct Info { | |
195 | //! name: String, | |
c34b1796 AL |
196 | //! age: i32, |
197 | //! rating: i32, | |
1a4d82fc JJ |
198 | //! } |
199 | //! | |
9346a6ac | 200 | //! fn write_info(info: &Info) -> io::Result<()> { |
8bb4bdeb | 201 | //! let mut file = File::create("my_best_friends.txt")?; |
1a4d82fc | 202 | //! // Early return on error |
8bb4bdeb XL |
203 | //! file.write_all(format!("name: {}\n", info.name).as_bytes())?; |
204 | //! file.write_all(format!("age: {}\n", info.age).as_bytes())?; | |
205 | //! file.write_all(format!("rating: {}\n", info.rating).as_bytes())?; | |
9346a6ac | 206 | //! Ok(()) |
1a4d82fc JJ |
207 | //! } |
208 | //! ``` | |
209 | //! | |
210 | //! *It's much nicer!* | |
211 | //! | |
8bb4bdeb | 212 | //! Ending the expression with [`?`] will result in the unwrapped |
9e0c209e | 213 | //! success ([`Ok`]) value, unless the result is [`Err`], in which case |
8bb4bdeb | 214 | //! [`Err`] is returned early from the enclosing function. |
1a4d82fc | 215 | //! |
8bb4bdeb XL |
216 | //! [`?`] can only be used in functions that return [`Result`] because of the |
217 | //! early return of [`Err`] that it provides. | |
9e0c209e SL |
218 | //! |
219 | //! [`expect`]: enum.Result.html#method.expect | |
220 | //! [`Write`]: ../../std/io/trait.Write.html | |
221 | //! [`write_all`]: ../../std/io/trait.Write.html#method.write_all | |
222 | //! [`io::Result`]: ../../std/io/type.Result.html | |
8bb4bdeb | 223 | //! [`?`]: ../../std/macro.try.html |
9e0c209e SL |
224 | //! [`Result`]: enum.Result.html |
225 | //! [`Ok(T)`]: enum.Result.html#variant.Ok | |
226 | //! [`Err(E)`]: enum.Result.html#variant.Err | |
227 | //! [`io::Error`]: ../../std/io/struct.Error.html | |
228 | //! [`Ok`]: enum.Result.html#variant.Ok | |
229 | //! [`Err`]: enum.Result.html#variant.Err | |
1a4d82fc | 230 | |
85aaf69f | 231 | #![stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 232 | |
48663c56 XL |
233 | use crate::fmt; |
234 | use crate::iter::{FromIterator, FusedIterator, TrustedLen}; | |
235 | use crate::ops::{self, Deref}; | |
1a4d82fc | 236 | |
3b2f2976 | 237 | /// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]). |
1a4d82fc JJ |
238 | /// |
239 | /// See the [`std::result`](index.html) module documentation for details. | |
3b2f2976 XL |
240 | /// |
241 | /// [`Ok`]: enum.Result.html#variant.Ok | |
242 | /// [`Err`]: enum.Result.html#variant.Err | |
dc9dc135 | 243 | #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] |
94b46f34 | 244 | #[must_use = "this `Result` may be an `Err` variant, which should be handled"] |
85aaf69f | 245 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
246 | pub enum Result<T, E> { |
247 | /// Contains the success value | |
85aaf69f | 248 | #[stable(feature = "rust1", since = "1.0.0")] |
7453a54e | 249 | Ok(#[stable(feature = "rust1", since = "1.0.0")] T), |
1a4d82fc JJ |
250 | |
251 | /// Contains the error value | |
85aaf69f | 252 | #[stable(feature = "rust1", since = "1.0.0")] |
a7813a04 | 253 | Err(#[stable(feature = "rust1", since = "1.0.0")] E), |
1a4d82fc JJ |
254 | } |
255 | ||
256 | ///////////////////////////////////////////////////////////////////////////// | |
257 | // Type implementation | |
258 | ///////////////////////////////////////////////////////////////////////////// | |
259 | ||
1a4d82fc JJ |
260 | impl<T, E> Result<T, E> { |
261 | ///////////////////////////////////////////////////////////////////////// | |
262 | // Querying the contained values | |
263 | ///////////////////////////////////////////////////////////////////////// | |
264 | ||
3b2f2976 XL |
265 | /// Returns `true` if the result is [`Ok`]. |
266 | /// | |
267 | /// [`Ok`]: enum.Result.html#variant.Ok | |
1a4d82fc | 268 | /// |
c34b1796 | 269 | /// # Examples |
1a4d82fc | 270 | /// |
a7813a04 XL |
271 | /// Basic usage: |
272 | /// | |
1a4d82fc | 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 | /// ``` | |
48663c56 | 280 | #[must_use] |
1a4d82fc | 281 | #[inline] |
85aaf69f | 282 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
283 | pub fn is_ok(&self) -> bool { |
284 | match *self { | |
285 | Ok(_) => true, | |
286 | Err(_) => false | |
287 | } | |
288 | } | |
289 | ||
3b2f2976 XL |
290 | /// Returns `true` if the result is [`Err`]. |
291 | /// | |
292 | /// [`Err`]: enum.Result.html#variant.Err | |
1a4d82fc | 293 | /// |
c34b1796 | 294 | /// # Examples |
1a4d82fc | 295 | /// |
a7813a04 XL |
296 | /// Basic usage: |
297 | /// | |
1a4d82fc | 298 | /// ``` |
c34b1796 | 299 | /// let x: Result<i32, &str> = Ok(-3); |
1a4d82fc JJ |
300 | /// assert_eq!(x.is_err(), false); |
301 | /// | |
c34b1796 | 302 | /// let x: Result<i32, &str> = Err("Some error message"); |
1a4d82fc JJ |
303 | /// assert_eq!(x.is_err(), true); |
304 | /// ``` | |
48663c56 | 305 | #[must_use] |
1a4d82fc | 306 | #[inline] |
85aaf69f | 307 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
308 | pub fn is_err(&self) -> bool { |
309 | !self.is_ok() | |
310 | } | |
311 | ||
312 | ///////////////////////////////////////////////////////////////////////// | |
313 | // Adapter for each variant | |
314 | ///////////////////////////////////////////////////////////////////////// | |
315 | ||
9e0c209e | 316 | /// Converts from `Result<T, E>` to [`Option<T>`]. |
1a4d82fc | 317 | /// |
9e0c209e | 318 | /// Converts `self` into an [`Option<T>`], consuming `self`, |
1a4d82fc JJ |
319 | /// and discarding the error, if any. |
320 | /// | |
9e0c209e SL |
321 | /// [`Option<T>`]: ../../std/option/enum.Option.html |
322 | /// | |
c34b1796 | 323 | /// # Examples |
1a4d82fc | 324 | /// |
a7813a04 XL |
325 | /// Basic usage: |
326 | /// | |
1a4d82fc | 327 | /// ``` |
85aaf69f | 328 | /// let x: Result<u32, &str> = Ok(2); |
1a4d82fc JJ |
329 | /// assert_eq!(x.ok(), Some(2)); |
330 | /// | |
85aaf69f | 331 | /// let x: Result<u32, &str> = Err("Nothing here"); |
1a4d82fc JJ |
332 | /// assert_eq!(x.ok(), None); |
333 | /// ``` | |
334 | #[inline] | |
85aaf69f | 335 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
336 | pub fn ok(self) -> Option<T> { |
337 | match self { | |
338 | Ok(x) => Some(x), | |
339 | Err(_) => None, | |
340 | } | |
341 | } | |
342 | ||
9e0c209e | 343 | /// Converts from `Result<T, E>` to [`Option<E>`]. |
1a4d82fc | 344 | /// |
9e0c209e | 345 | /// Converts `self` into an [`Option<E>`], consuming `self`, |
c34b1796 | 346 | /// and discarding the success value, if any. |
1a4d82fc | 347 | /// |
9e0c209e SL |
348 | /// [`Option<E>`]: ../../std/option/enum.Option.html |
349 | /// | |
c34b1796 | 350 | /// # Examples |
1a4d82fc | 351 | /// |
a7813a04 XL |
352 | /// Basic usage: |
353 | /// | |
1a4d82fc | 354 | /// ``` |
85aaf69f | 355 | /// let x: Result<u32, &str> = Ok(2); |
1a4d82fc JJ |
356 | /// assert_eq!(x.err(), None); |
357 | /// | |
85aaf69f | 358 | /// let x: Result<u32, &str> = Err("Nothing here"); |
1a4d82fc JJ |
359 | /// assert_eq!(x.err(), Some("Nothing here")); |
360 | /// ``` | |
361 | #[inline] | |
85aaf69f | 362 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
363 | pub fn err(self) -> Option<E> { |
364 | match self { | |
365 | Ok(_) => None, | |
366 | Err(x) => Some(x), | |
367 | } | |
368 | } | |
369 | ||
370 | ///////////////////////////////////////////////////////////////////////// | |
371 | // Adapter for working with references | |
372 | ///////////////////////////////////////////////////////////////////////// | |
373 | ||
532ac7d7 | 374 | /// Converts from `&Result<T, E>` to `Result<&T, &E>`. |
1a4d82fc JJ |
375 | /// |
376 | /// Produces a new `Result`, containing a reference | |
377 | /// into the original, leaving the original in place. | |
378 | /// | |
a7813a04 XL |
379 | /// # Examples |
380 | /// | |
381 | /// Basic usage: | |
382 | /// | |
1a4d82fc | 383 | /// ``` |
85aaf69f | 384 | /// let x: Result<u32, &str> = Ok(2); |
1a4d82fc JJ |
385 | /// assert_eq!(x.as_ref(), Ok(&2)); |
386 | /// | |
85aaf69f | 387 | /// let x: Result<u32, &str> = Err("Error"); |
1a4d82fc JJ |
388 | /// assert_eq!(x.as_ref(), Err(&"Error")); |
389 | /// ``` | |
390 | #[inline] | |
85aaf69f | 391 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
392 | pub fn as_ref(&self) -> Result<&T, &E> { |
393 | match *self { | |
394 | Ok(ref x) => Ok(x), | |
395 | Err(ref x) => Err(x), | |
396 | } | |
397 | } | |
398 | ||
532ac7d7 | 399 | /// Converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`. |
1a4d82fc | 400 | /// |
a7813a04 XL |
401 | /// # Examples |
402 | /// | |
403 | /// Basic usage: | |
404 | /// | |
1a4d82fc | 405 | /// ``` |
c34b1796 | 406 | /// fn mutate(r: &mut Result<i32, i32>) { |
1a4d82fc | 407 | /// match r.as_mut() { |
5bcae85e SL |
408 | /// Ok(v) => *v = 42, |
409 | /// Err(e) => *e = 0, | |
1a4d82fc JJ |
410 | /// } |
411 | /// } | |
412 | /// | |
c34b1796 | 413 | /// let mut x: Result<i32, i32> = Ok(2); |
1a4d82fc JJ |
414 | /// mutate(&mut x); |
415 | /// assert_eq!(x.unwrap(), 42); | |
416 | /// | |
c34b1796 | 417 | /// let mut x: Result<i32, i32> = Err(13); |
1a4d82fc JJ |
418 | /// mutate(&mut x); |
419 | /// assert_eq!(x.unwrap_err(), 0); | |
420 | /// ``` | |
421 | #[inline] | |
85aaf69f | 422 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
423 | pub fn as_mut(&mut self) -> Result<&mut T, &mut E> { |
424 | match *self { | |
425 | Ok(ref mut x) => Ok(x), | |
426 | Err(ref mut x) => Err(x), | |
427 | } | |
428 | } | |
429 | ||
1a4d82fc JJ |
430 | ///////////////////////////////////////////////////////////////////////// |
431 | // Transforming contained values | |
432 | ///////////////////////////////////////////////////////////////////////// | |
433 | ||
92a42be0 | 434 | /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a |
3b2f2976 | 435 | /// contained [`Ok`] value, leaving an [`Err`] value untouched. |
1a4d82fc JJ |
436 | /// |
437 | /// This function can be used to compose the results of two functions. | |
438 | /// | |
3b2f2976 XL |
439 | /// [`Ok`]: enum.Result.html#variant.Ok |
440 | /// [`Err`]: enum.Result.html#variant.Err | |
441 | /// | |
c34b1796 | 442 | /// # Examples |
1a4d82fc | 443 | /// |
9346a6ac | 444 | /// Print the numbers on each line of a string multiplied by two. |
1a4d82fc JJ |
445 | /// |
446 | /// ``` | |
9346a6ac | 447 | /// let line = "1\n2\n3\n4\n"; |
1a4d82fc | 448 | /// |
9346a6ac AL |
449 | /// for num in line.lines() { |
450 | /// match num.parse::<i32>().map(|i| i * 2) { | |
451 | /// Ok(n) => println!("{}", n), | |
452 | /// Err(..) => {} | |
453 | /// } | |
1a4d82fc | 454 | /// } |
1a4d82fc JJ |
455 | /// ``` |
456 | #[inline] | |
85aaf69f | 457 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
458 | pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> { |
459 | match self { | |
460 | Ok(t) => Ok(op(t)), | |
461 | Err(e) => Err(e) | |
462 | } | |
463 | } | |
464 | ||
b7449926 XL |
465 | /// Maps a `Result<T, E>` to `U` by applying a function to a |
466 | /// contained [`Ok`] value, or a fallback function to a | |
467 | /// contained [`Err`] value. | |
468 | /// | |
469 | /// This function can be used to unpack a successful result | |
470 | /// while handling an error. | |
471 | /// | |
472 | /// [`Ok`]: enum.Result.html#variant.Ok | |
473 | /// [`Err`]: enum.Result.html#variant.Err | |
474 | /// | |
475 | /// # Examples | |
476 | /// | |
477 | /// Basic usage: | |
478 | /// | |
479 | /// ``` | |
480 | /// #![feature(result_map_or_else)] | |
481 | /// let k = 21; | |
482 | /// | |
483 | /// let x : Result<_, &str> = Ok("foo"); | |
484 | /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3); | |
485 | /// | |
486 | /// let x : Result<&str, _> = Err("bar"); | |
487 | /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42); | |
488 | /// ``` | |
489 | #[inline] | |
490 | #[unstable(feature = "result_map_or_else", issue = "53268")] | |
491 | pub fn map_or_else<U, M: FnOnce(T) -> U, F: FnOnce(E) -> U>(self, fallback: F, map: M) -> U { | |
492 | self.map(map).unwrap_or_else(fallback) | |
493 | } | |
494 | ||
92a42be0 | 495 | /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a |
3b2f2976 | 496 | /// contained [`Err`] value, leaving an [`Ok`] value untouched. |
1a4d82fc JJ |
497 | /// |
498 | /// This function can be used to pass through a successful result while handling | |
499 | /// an error. | |
500 | /// | |
3b2f2976 XL |
501 | /// [`Ok`]: enum.Result.html#variant.Ok |
502 | /// [`Err`]: enum.Result.html#variant.Err | |
503 | /// | |
c34b1796 | 504 | /// # Examples |
1a4d82fc | 505 | /// |
a7813a04 XL |
506 | /// Basic usage: |
507 | /// | |
1a4d82fc | 508 | /// ``` |
85aaf69f | 509 | /// fn stringify(x: u32) -> String { format!("error code: {}", x) } |
1a4d82fc | 510 | /// |
85aaf69f SL |
511 | /// let x: Result<u32, u32> = Ok(2); |
512 | /// assert_eq!(x.map_err(stringify), Ok(2)); | |
1a4d82fc | 513 | /// |
85aaf69f | 514 | /// let x: Result<u32, u32> = Err(13); |
1a4d82fc JJ |
515 | /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string())); |
516 | /// ``` | |
517 | #[inline] | |
85aaf69f | 518 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
519 | pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> { |
520 | match self { | |
521 | Ok(t) => Ok(t), | |
522 | Err(e) => Err(op(e)) | |
523 | } | |
524 | } | |
525 | ||
526 | ///////////////////////////////////////////////////////////////////////// | |
527 | // Iterator constructors | |
528 | ///////////////////////////////////////////////////////////////////////// | |
529 | ||
530 | /// Returns an iterator over the possibly contained value. | |
531 | /// | |
b7449926 | 532 | /// The iterator yields one value if the result is [`Result::Ok`], otherwise none. |
32a655c1 | 533 | /// |
c34b1796 | 534 | /// # Examples |
1a4d82fc | 535 | /// |
a7813a04 XL |
536 | /// Basic usage: |
537 | /// | |
1a4d82fc | 538 | /// ``` |
85aaf69f | 539 | /// let x: Result<u32, &str> = Ok(7); |
1a4d82fc JJ |
540 | /// assert_eq!(x.iter().next(), Some(&7)); |
541 | /// | |
85aaf69f | 542 | /// let x: Result<u32, &str> = Err("nothing!"); |
1a4d82fc JJ |
543 | /// assert_eq!(x.iter().next(), None); |
544 | /// ``` | |
545 | #[inline] | |
85aaf69f | 546 | #[stable(feature = "rust1", since = "1.0.0")] |
48663c56 | 547 | pub fn iter(&self) -> Iter<'_, T> { |
1a4d82fc JJ |
548 | Iter { inner: self.as_ref().ok() } |
549 | } | |
550 | ||
551 | /// Returns a mutable iterator over the possibly contained value. | |
552 | /// | |
b7449926 | 553 | /// The iterator yields one value if the result is [`Result::Ok`], otherwise none. |
32a655c1 | 554 | /// |
c34b1796 | 555 | /// # Examples |
1a4d82fc | 556 | /// |
a7813a04 XL |
557 | /// Basic usage: |
558 | /// | |
1a4d82fc | 559 | /// ``` |
85aaf69f | 560 | /// let mut x: Result<u32, &str> = Ok(7); |
1a4d82fc | 561 | /// match x.iter_mut().next() { |
b039eaaf | 562 | /// Some(v) => *v = 40, |
1a4d82fc JJ |
563 | /// None => {}, |
564 | /// } | |
565 | /// assert_eq!(x, Ok(40)); | |
566 | /// | |
85aaf69f | 567 | /// let mut x: Result<u32, &str> = Err("nothing!"); |
1a4d82fc JJ |
568 | /// assert_eq!(x.iter_mut().next(), None); |
569 | /// ``` | |
570 | #[inline] | |
85aaf69f | 571 | #[stable(feature = "rust1", since = "1.0.0")] |
48663c56 | 572 | pub fn iter_mut(&mut self) -> IterMut<'_, T> { |
1a4d82fc JJ |
573 | IterMut { inner: self.as_mut().ok() } |
574 | } | |
575 | ||
1a4d82fc JJ |
576 | //////////////////////////////////////////////////////////////////////// |
577 | // Boolean operations on the values, eager and lazy | |
578 | ///////////////////////////////////////////////////////////////////////// | |
579 | ||
3b2f2976 XL |
580 | /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`. |
581 | /// | |
582 | /// [`Ok`]: enum.Result.html#variant.Ok | |
583 | /// [`Err`]: enum.Result.html#variant.Err | |
1a4d82fc | 584 | /// |
c34b1796 | 585 | /// # Examples |
1a4d82fc | 586 | /// |
a7813a04 XL |
587 | /// Basic usage: |
588 | /// | |
1a4d82fc | 589 | /// ``` |
85aaf69f | 590 | /// let x: Result<u32, &str> = Ok(2); |
1a4d82fc JJ |
591 | /// let y: Result<&str, &str> = Err("late error"); |
592 | /// assert_eq!(x.and(y), Err("late error")); | |
593 | /// | |
85aaf69f | 594 | /// let x: Result<u32, &str> = Err("early error"); |
1a4d82fc JJ |
595 | /// let y: Result<&str, &str> = Ok("foo"); |
596 | /// assert_eq!(x.and(y), Err("early error")); | |
597 | /// | |
85aaf69f | 598 | /// let x: Result<u32, &str> = Err("not a 2"); |
1a4d82fc JJ |
599 | /// let y: Result<&str, &str> = Err("late error"); |
600 | /// assert_eq!(x.and(y), Err("not a 2")); | |
601 | /// | |
85aaf69f | 602 | /// let x: Result<u32, &str> = Ok(2); |
1a4d82fc JJ |
603 | /// let y: Result<&str, &str> = Ok("different result type"); |
604 | /// assert_eq!(x.and(y), Ok("different result type")); | |
605 | /// ``` | |
606 | #[inline] | |
85aaf69f | 607 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
608 | pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> { |
609 | match self { | |
610 | Ok(_) => res, | |
611 | Err(e) => Err(e), | |
612 | } | |
613 | } | |
614 | ||
3b2f2976 XL |
615 | /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`. |
616 | /// | |
617 | /// [`Ok`]: enum.Result.html#variant.Ok | |
618 | /// [`Err`]: enum.Result.html#variant.Err | |
1a4d82fc | 619 | /// |
9e0c209e | 620 | /// This function can be used for control flow based on `Result` values. |
1a4d82fc | 621 | /// |
c34b1796 | 622 | /// # Examples |
1a4d82fc | 623 | /// |
a7813a04 XL |
624 | /// Basic usage: |
625 | /// | |
1a4d82fc | 626 | /// ``` |
85aaf69f SL |
627 | /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) } |
628 | /// fn err(x: u32) -> Result<u32, u32> { Err(x) } | |
1a4d82fc JJ |
629 | /// |
630 | /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16)); | |
631 | /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4)); | |
632 | /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2)); | |
633 | /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3)); | |
634 | /// ``` | |
635 | #[inline] | |
85aaf69f | 636 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
637 | pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> { |
638 | match self { | |
639 | Ok(t) => op(t), | |
640 | Err(e) => Err(e), | |
641 | } | |
642 | } | |
643 | ||
3b2f2976 XL |
644 | /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`. |
645 | /// | |
ff7c6d11 XL |
646 | /// Arguments passed to `or` are eagerly evaluated; if you are passing the |
647 | /// result of a function call, it is recommended to use [`or_else`], which is | |
648 | /// lazily evaluated. | |
649 | /// | |
3b2f2976 XL |
650 | /// [`Ok`]: enum.Result.html#variant.Ok |
651 | /// [`Err`]: enum.Result.html#variant.Err | |
ff7c6d11 | 652 | /// [`or_else`]: #method.or_else |
1a4d82fc | 653 | /// |
c34b1796 | 654 | /// # Examples |
1a4d82fc | 655 | /// |
a7813a04 XL |
656 | /// Basic usage: |
657 | /// | |
1a4d82fc | 658 | /// ``` |
85aaf69f SL |
659 | /// let x: Result<u32, &str> = Ok(2); |
660 | /// let y: Result<u32, &str> = Err("late error"); | |
1a4d82fc JJ |
661 | /// assert_eq!(x.or(y), Ok(2)); |
662 | /// | |
85aaf69f SL |
663 | /// let x: Result<u32, &str> = Err("early error"); |
664 | /// let y: Result<u32, &str> = Ok(2); | |
1a4d82fc JJ |
665 | /// assert_eq!(x.or(y), Ok(2)); |
666 | /// | |
85aaf69f SL |
667 | /// let x: Result<u32, &str> = Err("not a 2"); |
668 | /// let y: Result<u32, &str> = Err("late error"); | |
1a4d82fc JJ |
669 | /// assert_eq!(x.or(y), Err("late error")); |
670 | /// | |
85aaf69f SL |
671 | /// let x: Result<u32, &str> = Ok(2); |
672 | /// let y: Result<u32, &str> = Ok(100); | |
1a4d82fc JJ |
673 | /// assert_eq!(x.or(y), Ok(2)); |
674 | /// ``` | |
675 | #[inline] | |
85aaf69f | 676 | #[stable(feature = "rust1", since = "1.0.0")] |
c34b1796 | 677 | pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> { |
1a4d82fc | 678 | match self { |
c34b1796 | 679 | Ok(v) => Ok(v), |
1a4d82fc JJ |
680 | Err(_) => res, |
681 | } | |
682 | } | |
683 | ||
3b2f2976 | 684 | /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`. |
1a4d82fc JJ |
685 | /// |
686 | /// This function can be used for control flow based on result values. | |
687 | /// | |
3b2f2976 XL |
688 | /// [`Ok`]: enum.Result.html#variant.Ok |
689 | /// [`Err`]: enum.Result.html#variant.Err | |
690 | /// | |
c34b1796 | 691 | /// # Examples |
1a4d82fc | 692 | /// |
a7813a04 XL |
693 | /// Basic usage: |
694 | /// | |
1a4d82fc | 695 | /// ``` |
85aaf69f SL |
696 | /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) } |
697 | /// fn err(x: u32) -> Result<u32, u32> { Err(x) } | |
1a4d82fc JJ |
698 | /// |
699 | /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2)); | |
700 | /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2)); | |
701 | /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9)); | |
702 | /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3)); | |
703 | /// ``` | |
704 | #[inline] | |
85aaf69f | 705 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
706 | pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> { |
707 | match self { | |
708 | Ok(t) => Ok(t), | |
709 | Err(e) => op(e), | |
710 | } | |
711 | } | |
712 | ||
3b2f2976 | 713 | /// Unwraps a result, yielding the content of an [`Ok`]. |
9e0c209e | 714 | /// Else, it returns `optb`. |
1a4d82fc | 715 | /// |
ff7c6d11 XL |
716 | /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing |
717 | /// the result of a function call, it is recommended to use [`unwrap_or_else`], | |
718 | /// which is lazily evaluated. | |
719 | /// | |
3b2f2976 XL |
720 | /// [`Ok`]: enum.Result.html#variant.Ok |
721 | /// [`Err`]: enum.Result.html#variant.Err | |
ff7c6d11 | 722 | /// [`unwrap_or_else`]: #method.unwrap_or_else |
3b2f2976 | 723 | /// |
c34b1796 | 724 | /// # Examples |
1a4d82fc | 725 | /// |
a7813a04 XL |
726 | /// Basic usage: |
727 | /// | |
1a4d82fc | 728 | /// ``` |
85aaf69f SL |
729 | /// let optb = 2; |
730 | /// let x: Result<u32, &str> = Ok(9); | |
731 | /// assert_eq!(x.unwrap_or(optb), 9); | |
1a4d82fc | 732 | /// |
85aaf69f | 733 | /// let x: Result<u32, &str> = Err("error"); |
1a4d82fc JJ |
734 | /// assert_eq!(x.unwrap_or(optb), optb); |
735 | /// ``` | |
736 | #[inline] | |
85aaf69f | 737 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
738 | pub fn unwrap_or(self, optb: T) -> T { |
739 | match self { | |
740 | Ok(t) => t, | |
741 | Err(_) => optb | |
742 | } | |
743 | } | |
744 | ||
3b2f2976 XL |
745 | /// Unwraps a result, yielding the content of an [`Ok`]. |
746 | /// If the value is an [`Err`] then it calls `op` with its value. | |
747 | /// | |
748 | /// [`Ok`]: enum.Result.html#variant.Ok | |
749 | /// [`Err`]: enum.Result.html#variant.Err | |
1a4d82fc | 750 | /// |
c34b1796 | 751 | /// # Examples |
1a4d82fc | 752 | /// |
a7813a04 XL |
753 | /// Basic usage: |
754 | /// | |
1a4d82fc | 755 | /// ``` |
85aaf69f | 756 | /// fn count(x: &str) -> usize { x.len() } |
1a4d82fc | 757 | /// |
85aaf69f SL |
758 | /// assert_eq!(Ok(2).unwrap_or_else(count), 2); |
759 | /// assert_eq!(Err("foo").unwrap_or_else(count), 3); | |
1a4d82fc JJ |
760 | /// ``` |
761 | #[inline] | |
85aaf69f | 762 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
763 | pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T { |
764 | match self { | |
765 | Ok(t) => t, | |
766 | Err(e) => op(e) | |
767 | } | |
768 | } | |
769 | } | |
770 | ||
85aaf69f | 771 | impl<T, E: fmt::Debug> Result<T, E> { |
3b2f2976 | 772 | /// Unwraps a result, yielding the content of an [`Ok`]. |
1a4d82fc JJ |
773 | /// |
774 | /// # Panics | |
775 | /// | |
3b2f2976 XL |
776 | /// Panics if the value is an [`Err`], with a panic message provided by the |
777 | /// [`Err`]'s value. | |
778 | /// | |
779 | /// [`Ok`]: enum.Result.html#variant.Ok | |
780 | /// [`Err`]: enum.Result.html#variant.Err | |
1a4d82fc | 781 | /// |
c34b1796 | 782 | /// # Examples |
1a4d82fc | 783 | /// |
a7813a04 XL |
784 | /// Basic usage: |
785 | /// | |
1a4d82fc | 786 | /// ``` |
85aaf69f SL |
787 | /// let x: Result<u32, &str> = Ok(2); |
788 | /// assert_eq!(x.unwrap(), 2); | |
1a4d82fc JJ |
789 | /// ``` |
790 | /// | |
c34b1796 | 791 | /// ```{.should_panic} |
85aaf69f | 792 | /// let x: Result<u32, &str> = Err("emergency failure"); |
1a4d82fc JJ |
793 | /// x.unwrap(); // panics with `emergency failure` |
794 | /// ``` | |
795 | #[inline] | |
85aaf69f | 796 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
797 | pub fn unwrap(self) -> T { |
798 | match self { | |
799 | Ok(t) => t, | |
7453a54e | 800 | Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", e), |
1a4d82fc JJ |
801 | } |
802 | } | |
62682a34 | 803 | |
3b2f2976 | 804 | /// Unwraps a result, yielding the content of an [`Ok`]. |
62682a34 | 805 | /// |
9cc50fc6 SL |
806 | /// # Panics |
807 | /// | |
3b2f2976 XL |
808 | /// Panics if the value is an [`Err`], with a panic message including the |
809 | /// passed message, and the content of the [`Err`]. | |
810 | /// | |
811 | /// [`Ok`]: enum.Result.html#variant.Ok | |
812 | /// [`Err`]: enum.Result.html#variant.Err | |
62682a34 SL |
813 | /// |
814 | /// # Examples | |
a7813a04 XL |
815 | /// |
816 | /// Basic usage: | |
817 | /// | |
62682a34 | 818 | /// ```{.should_panic} |
62682a34 SL |
819 | /// let x: Result<u32, &str> = Err("emergency failure"); |
820 | /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure` | |
821 | /// ``` | |
822 | #[inline] | |
e9174d1e | 823 | #[stable(feature = "result_expect", since = "1.4.0")] |
62682a34 SL |
824 | pub fn expect(self, msg: &str) -> T { |
825 | match self { | |
826 | Ok(t) => t, | |
7453a54e | 827 | Err(e) => unwrap_failed(msg, e), |
62682a34 SL |
828 | } |
829 | } | |
1a4d82fc JJ |
830 | } |
831 | ||
85aaf69f | 832 | impl<T: fmt::Debug, E> Result<T, E> { |
3b2f2976 | 833 | /// Unwraps a result, yielding the content of an [`Err`]. |
1a4d82fc JJ |
834 | /// |
835 | /// # Panics | |
836 | /// | |
3b2f2976 XL |
837 | /// Panics if the value is an [`Ok`], with a custom panic message provided |
838 | /// by the [`Ok`]'s value. | |
839 | /// | |
840 | /// [`Ok`]: enum.Result.html#variant.Ok | |
841 | /// [`Err`]: enum.Result.html#variant.Err | |
842 | /// | |
1a4d82fc | 843 | /// |
c34b1796 | 844 | /// # Examples |
1a4d82fc | 845 | /// |
c34b1796 | 846 | /// ```{.should_panic} |
85aaf69f | 847 | /// let x: Result<u32, &str> = Ok(2); |
1a4d82fc JJ |
848 | /// x.unwrap_err(); // panics with `2` |
849 | /// ``` | |
850 | /// | |
851 | /// ``` | |
85aaf69f | 852 | /// let x: Result<u32, &str> = Err("emergency failure"); |
1a4d82fc JJ |
853 | /// assert_eq!(x.unwrap_err(), "emergency failure"); |
854 | /// ``` | |
855 | #[inline] | |
85aaf69f | 856 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
857 | pub fn unwrap_err(self) -> E { |
858 | match self { | |
7453a54e SL |
859 | Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", t), |
860 | Err(e) => e, | |
1a4d82fc JJ |
861 | } |
862 | } | |
32a655c1 | 863 | |
3b2f2976 | 864 | /// Unwraps a result, yielding the content of an [`Err`]. |
32a655c1 SL |
865 | /// |
866 | /// # Panics | |
867 | /// | |
3b2f2976 XL |
868 | /// Panics if the value is an [`Ok`], with a panic message including the |
869 | /// passed message, and the content of the [`Ok`]. | |
870 | /// | |
871 | /// [`Ok`]: enum.Result.html#variant.Ok | |
872 | /// [`Err`]: enum.Result.html#variant.Err | |
32a655c1 SL |
873 | /// |
874 | /// # Examples | |
875 | /// | |
876 | /// Basic usage: | |
877 | /// | |
878 | /// ```{.should_panic} | |
32a655c1 SL |
879 | /// let x: Result<u32, &str> = Ok(10); |
880 | /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` | |
881 | /// ``` | |
882 | #[inline] | |
8bb4bdeb | 883 | #[stable(feature = "result_expect_err", since = "1.17.0")] |
32a655c1 SL |
884 | pub fn expect_err(self, msg: &str) -> E { |
885 | match self { | |
886 | Ok(t) => unwrap_failed(msg, t), | |
887 | Err(e) => e, | |
888 | } | |
889 | } | |
1a4d82fc JJ |
890 | } |
891 | ||
c30ab7b3 SL |
892 | impl<T: Default, E> Result<T, E> { |
893 | /// Returns the contained value or a default | |
894 | /// | |
3b2f2976 XL |
895 | /// Consumes the `self` argument then, if [`Ok`], returns the contained |
896 | /// value, otherwise if [`Err`], returns the default value for that | |
c30ab7b3 SL |
897 | /// type. |
898 | /// | |
899 | /// # Examples | |
900 | /// | |
9fa01778 | 901 | /// Converts a string to an integer, turning poorly-formed strings |
c30ab7b3 SL |
902 | /// into 0 (the default value for integers). [`parse`] converts |
903 | /// a string to any other type that implements [`FromStr`], returning an | |
3b2f2976 | 904 | /// [`Err`] on error. |
c30ab7b3 SL |
905 | /// |
906 | /// ``` | |
c30ab7b3 SL |
907 | /// let good_year_from_input = "1909"; |
908 | /// let bad_year_from_input = "190blarg"; | |
909 | /// let good_year = good_year_from_input.parse().unwrap_or_default(); | |
910 | /// let bad_year = bad_year_from_input.parse().unwrap_or_default(); | |
911 | /// | |
912 | /// assert_eq!(1909, good_year); | |
913 | /// assert_eq!(0, bad_year); | |
cc61c64b | 914 | /// ``` |
c30ab7b3 SL |
915 | /// |
916 | /// [`parse`]: ../../std/primitive.str.html#method.parse | |
917 | /// [`FromStr`]: ../../std/str/trait.FromStr.html | |
3b2f2976 XL |
918 | /// [`Ok`]: enum.Result.html#variant.Ok |
919 | /// [`Err`]: enum.Result.html#variant.Err | |
c30ab7b3 | 920 | #[inline] |
32a655c1 | 921 | #[stable(feature = "result_unwrap_or_default", since = "1.16.0")] |
c30ab7b3 SL |
922 | pub fn unwrap_or_default(self) -> T { |
923 | match self { | |
924 | Ok(x) => x, | |
925 | Err(_) => Default::default(), | |
2c00a5a8 XL |
926 | } |
927 | } | |
928 | } | |
929 | ||
b7449926 XL |
930 | #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")] |
931 | impl<T: Deref, E> Result<T, E> { | |
932 | /// Converts from `&Result<T, E>` to `Result<&T::Target, &E>`. | |
933 | /// | |
934 | /// Leaves the original Result in-place, creating a new one with a reference | |
935 | /// to the original one, additionally coercing the `Ok` arm of the Result via | |
936 | /// `Deref`. | |
937 | pub fn deref_ok(&self) -> Result<&T::Target, &E> { | |
938 | self.as_ref().map(|t| t.deref()) | |
939 | } | |
940 | } | |
941 | ||
942 | #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")] | |
943 | impl<T, E: Deref> Result<T, E> { | |
944 | /// Converts from `&Result<T, E>` to `Result<&T, &E::Target>`. | |
945 | /// | |
946 | /// Leaves the original Result in-place, creating a new one with a reference | |
947 | /// to the original one, additionally coercing the `Err` arm of the Result via | |
948 | /// `Deref`. | |
949 | pub fn deref_err(&self) -> Result<&T, &E::Target> | |
950 | { | |
951 | self.as_ref().map_err(|e| e.deref()) | |
952 | } | |
953 | } | |
954 | ||
955 | #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")] | |
956 | impl<T: Deref, E: Deref> Result<T, E> { | |
957 | /// Converts from `&Result<T, E>` to `Result<&T::Target, &E::Target>`. | |
958 | /// | |
959 | /// Leaves the original Result in-place, creating a new one with a reference | |
960 | /// to the original one, additionally coercing both the `Ok` and `Err` arms | |
961 | /// of the Result via `Deref`. | |
962 | pub fn deref(&self) -> Result<&T::Target, &E::Target> | |
963 | { | |
964 | self.as_ref().map(|t| t.deref()).map_err(|e| e.deref()) | |
965 | } | |
966 | } | |
967 | ||
2c00a5a8 XL |
968 | impl<T, E> Result<Option<T>, E> { |
969 | /// Transposes a `Result` of an `Option` into an `Option` of a `Result`. | |
970 | /// | |
971 | /// `Ok(None)` will be mapped to `None`. | |
972 | /// `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`. | |
973 | /// | |
974 | /// # Examples | |
975 | /// | |
976 | /// ``` | |
2c00a5a8 XL |
977 | /// #[derive(Debug, Eq, PartialEq)] |
978 | /// struct SomeErr; | |
979 | /// | |
980 | /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5)); | |
981 | /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5)); | |
982 | /// assert_eq!(x.transpose(), y); | |
983 | /// ``` | |
984 | #[inline] | |
0731742a | 985 | #[stable(feature = "transpose_result", since = "1.33.0")] |
2c00a5a8 XL |
986 | pub fn transpose(self) -> Option<Result<T, E>> { |
987 | match self { | |
988 | Ok(Some(x)) => Some(Ok(x)), | |
989 | Ok(None) => None, | |
990 | Err(e) => Some(Err(e)), | |
c30ab7b3 SL |
991 | } |
992 | } | |
993 | } | |
994 | ||
7453a54e SL |
995 | // This is a separate function to reduce the code size of the methods |
996 | #[inline(never)] | |
997 | #[cold] | |
998 | fn unwrap_failed<E: fmt::Debug>(msg: &str, error: E) -> ! { | |
999 | panic!("{}: {:?}", msg, error) | |
1000 | } | |
1001 | ||
1a4d82fc JJ |
1002 | ///////////////////////////////////////////////////////////////////////////// |
1003 | // Trait implementations | |
1004 | ///////////////////////////////////////////////////////////////////////////// | |
1005 | ||
dc9dc135 XL |
1006 | #[stable(feature = "rust1", since = "1.0.0")] |
1007 | impl<T: Clone, E: Clone> Clone for Result<T, E> { | |
1008 | #[inline] | |
1009 | fn clone(&self) -> Self { | |
1010 | match self { | |
1011 | Ok(x) => Ok(x.clone()), | |
1012 | Err(x) => Err(x.clone()), | |
1013 | } | |
1014 | } | |
1015 | ||
1016 | #[inline] | |
1017 | fn clone_from(&mut self, source: &Self) { | |
1018 | match (self, source) { | |
1019 | (Ok(to), Ok(from)) => to.clone_from(from), | |
1020 | (Err(to), Err(from)) => to.clone_from(from), | |
1021 | (to, from) => *to = from.clone(), | |
1022 | } | |
1023 | } | |
1024 | } | |
1025 | ||
1026 | ||
9346a6ac AL |
1027 | #[stable(feature = "rust1", since = "1.0.0")] |
1028 | impl<T, E> IntoIterator for Result<T, E> { | |
1029 | type Item = T; | |
1030 | type IntoIter = IntoIter<T>; | |
1031 | ||
1032 | /// Returns a consuming iterator over the possibly contained value. | |
1033 | /// | |
b7449926 | 1034 | /// The iterator yields one value if the result is [`Result::Ok`], otherwise none. |
32a655c1 | 1035 | /// |
9346a6ac AL |
1036 | /// # Examples |
1037 | /// | |
a7813a04 XL |
1038 | /// Basic usage: |
1039 | /// | |
9346a6ac AL |
1040 | /// ``` |
1041 | /// let x: Result<u32, &str> = Ok(5); | |
1042 | /// let v: Vec<u32> = x.into_iter().collect(); | |
1043 | /// assert_eq!(v, [5]); | |
1044 | /// | |
1045 | /// let x: Result<u32, &str> = Err("nothing!"); | |
1046 | /// let v: Vec<u32> = x.into_iter().collect(); | |
1047 | /// assert_eq!(v, []); | |
1048 | /// ``` | |
1a4d82fc | 1049 | #[inline] |
9346a6ac AL |
1050 | fn into_iter(self) -> IntoIter<T> { |
1051 | IntoIter { inner: self.ok() } | |
1a4d82fc JJ |
1052 | } |
1053 | } | |
1054 | ||
e9174d1e SL |
1055 | #[stable(since = "1.4.0", feature = "result_iter")] |
1056 | impl<'a, T, E> IntoIterator for &'a Result<T, E> { | |
1057 | type Item = &'a T; | |
1058 | type IntoIter = Iter<'a, T>; | |
1059 | ||
1060 | fn into_iter(self) -> Iter<'a, T> { | |
1061 | self.iter() | |
1062 | } | |
1063 | } | |
1064 | ||
1065 | #[stable(since = "1.4.0", feature = "result_iter")] | |
1066 | impl<'a, T, E> IntoIterator for &'a mut Result<T, E> { | |
1067 | type Item = &'a mut T; | |
1068 | type IntoIter = IterMut<'a, T>; | |
1069 | ||
3b2f2976 | 1070 | fn into_iter(self) -> IterMut<'a, T> { |
e9174d1e SL |
1071 | self.iter_mut() |
1072 | } | |
1073 | } | |
1074 | ||
1a4d82fc JJ |
1075 | ///////////////////////////////////////////////////////////////////////////// |
1076 | // The Result Iterators | |
1077 | ///////////////////////////////////////////////////////////////////////////// | |
1078 | ||
9e0c209e SL |
1079 | /// An iterator over a reference to the [`Ok`] variant of a [`Result`]. |
1080 | /// | |
32a655c1 SL |
1081 | /// The iterator yields one value if the result is [`Ok`], otherwise none. |
1082 | /// | |
1083 | /// Created by [`Result::iter`]. | |
1084 | /// | |
9e0c209e SL |
1085 | /// [`Ok`]: enum.Result.html#variant.Ok |
1086 | /// [`Result`]: enum.Result.html | |
32a655c1 | 1087 | /// [`Result::iter`]: enum.Result.html#method.iter |
54a0048b | 1088 | #[derive(Debug)] |
85aaf69f | 1089 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1090 | pub struct Iter<'a, T: 'a> { inner: Option<&'a T> } |
1091 | ||
85aaf69f | 1092 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1093 | impl<'a, T> Iterator for Iter<'a, T> { |
1094 | type Item = &'a T; | |
1095 | ||
1096 | #[inline] | |
1097 | fn next(&mut self) -> Option<&'a T> { self.inner.take() } | |
1098 | #[inline] | |
85aaf69f | 1099 | fn size_hint(&self) -> (usize, Option<usize>) { |
1a4d82fc JJ |
1100 | let n = if self.inner.is_some() {1} else {0}; |
1101 | (n, Some(n)) | |
1102 | } | |
1103 | } | |
1104 | ||
85aaf69f | 1105 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1106 | impl<'a, T> DoubleEndedIterator for Iter<'a, T> { |
1107 | #[inline] | |
1108 | fn next_back(&mut self) -> Option<&'a T> { self.inner.take() } | |
1109 | } | |
1110 | ||
85aaf69f | 1111 | #[stable(feature = "rust1", since = "1.0.0")] |
0bf4aa26 | 1112 | impl<T> ExactSizeIterator for Iter<'_, T> {} |
1a4d82fc | 1113 | |
0531ce1d | 1114 | #[stable(feature = "fused", since = "1.26.0")] |
0bf4aa26 | 1115 | impl<T> FusedIterator for Iter<'_, T> {} |
9e0c209e | 1116 | |
c30ab7b3 | 1117 | #[unstable(feature = "trusted_len", issue = "37572")] |
0bf4aa26 | 1118 | unsafe impl<A> TrustedLen for Iter<'_, A> {} |
c30ab7b3 | 1119 | |
92a42be0 | 1120 | #[stable(feature = "rust1", since = "1.0.0")] |
0bf4aa26 | 1121 | impl<T> Clone for Iter<'_, T> { |
b7449926 | 1122 | #[inline] |
0bf4aa26 | 1123 | fn clone(&self) -> Self { Iter { inner: self.inner } } |
1a4d82fc JJ |
1124 | } |
1125 | ||
9e0c209e SL |
1126 | /// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`]. |
1127 | /// | |
32a655c1 SL |
1128 | /// Created by [`Result::iter_mut`]. |
1129 | /// | |
9e0c209e SL |
1130 | /// [`Ok`]: enum.Result.html#variant.Ok |
1131 | /// [`Result`]: enum.Result.html | |
32a655c1 | 1132 | /// [`Result::iter_mut`]: enum.Result.html#method.iter_mut |
54a0048b | 1133 | #[derive(Debug)] |
85aaf69f | 1134 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1135 | pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> } |
1136 | ||
85aaf69f | 1137 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1138 | impl<'a, T> Iterator for IterMut<'a, T> { |
1139 | type Item = &'a mut T; | |
1140 | ||
1141 | #[inline] | |
1142 | fn next(&mut self) -> Option<&'a mut T> { self.inner.take() } | |
1143 | #[inline] | |
85aaf69f | 1144 | fn size_hint(&self) -> (usize, Option<usize>) { |
1a4d82fc JJ |
1145 | let n = if self.inner.is_some() {1} else {0}; |
1146 | (n, Some(n)) | |
1147 | } | |
1148 | } | |
1149 | ||
85aaf69f | 1150 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1151 | impl<'a, T> DoubleEndedIterator for IterMut<'a, T> { |
1152 | #[inline] | |
1153 | fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() } | |
1154 | } | |
1155 | ||
85aaf69f | 1156 | #[stable(feature = "rust1", since = "1.0.0")] |
0bf4aa26 | 1157 | impl<T> ExactSizeIterator for IterMut<'_, T> {} |
1a4d82fc | 1158 | |
0531ce1d | 1159 | #[stable(feature = "fused", since = "1.26.0")] |
0bf4aa26 | 1160 | impl<T> FusedIterator for IterMut<'_, T> {} |
9e0c209e | 1161 | |
c30ab7b3 | 1162 | #[unstable(feature = "trusted_len", issue = "37572")] |
0bf4aa26 | 1163 | unsafe impl<A> TrustedLen for IterMut<'_, A> {} |
c30ab7b3 | 1164 | |
32a655c1 SL |
1165 | /// An iterator over the value in a [`Ok`] variant of a [`Result`]. |
1166 | /// | |
1167 | /// The iterator yields one value if the result is [`Ok`], otherwise none. | |
1168 | /// | |
1169 | /// This struct is created by the [`into_iter`] method on | |
1170 | /// [`Result`][`Result`] (provided by the [`IntoIterator`] trait). | |
9e0c209e SL |
1171 | /// |
1172 | /// [`Ok`]: enum.Result.html#variant.Ok | |
1173 | /// [`Result`]: enum.Result.html | |
1174 | /// [`into_iter`]: ../iter/trait.IntoIterator.html#tymethod.into_iter | |
1175 | /// [`IntoIterator`]: ../iter/trait.IntoIterator.html | |
abe05a73 | 1176 | #[derive(Clone, Debug)] |
85aaf69f | 1177 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1178 | pub struct IntoIter<T> { inner: Option<T> } |
1179 | ||
85aaf69f | 1180 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1181 | impl<T> Iterator for IntoIter<T> { |
1182 | type Item = T; | |
1183 | ||
1184 | #[inline] | |
1185 | fn next(&mut self) -> Option<T> { self.inner.take() } | |
1186 | #[inline] | |
85aaf69f | 1187 | fn size_hint(&self) -> (usize, Option<usize>) { |
1a4d82fc JJ |
1188 | let n = if self.inner.is_some() {1} else {0}; |
1189 | (n, Some(n)) | |
1190 | } | |
1191 | } | |
1192 | ||
85aaf69f | 1193 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1194 | impl<T> DoubleEndedIterator for IntoIter<T> { |
1195 | #[inline] | |
1196 | fn next_back(&mut self) -> Option<T> { self.inner.take() } | |
1197 | } | |
1198 | ||
85aaf69f | 1199 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1200 | impl<T> ExactSizeIterator for IntoIter<T> {} |
1201 | ||
0531ce1d | 1202 | #[stable(feature = "fused", since = "1.26.0")] |
9e0c209e SL |
1203 | impl<T> FusedIterator for IntoIter<T> {} |
1204 | ||
c30ab7b3 SL |
1205 | #[unstable(feature = "trusted_len", issue = "37572")] |
1206 | unsafe impl<A> TrustedLen for IntoIter<A> {} | |
1207 | ||
1a4d82fc JJ |
1208 | ///////////////////////////////////////////////////////////////////////////// |
1209 | // FromIterator | |
1210 | ///////////////////////////////////////////////////////////////////////////// | |
1211 | ||
85aaf69f | 1212 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1213 | impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> { |
1214 | /// Takes each element in the `Iterator`: if it is an `Err`, no further | |
1215 | /// elements are taken, and the `Err` is returned. Should no `Err` occur, a | |
1216 | /// container with the values of each `Result` is returned. | |
1217 | /// | |
1218 | /// Here is an example which increments every integer in a vector, | |
1219 | /// checking for overflow: | |
1220 | /// | |
c34b1796 | 1221 | /// ``` |
c30ab7b3 | 1222 | /// let v = vec![1, 2]; |
041b39d2 XL |
1223 | /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| |
1224 | /// x.checked_add(1).ok_or("Overflow!") | |
1a4d82fc | 1225 | /// ).collect(); |
532ac7d7 | 1226 | /// assert_eq!(res, Ok(vec![2, 3])); |
1a4d82fc | 1227 | /// ``` |
532ac7d7 XL |
1228 | /// |
1229 | /// Here is another example that tries to subtract one from another list | |
1230 | /// of integers, this time checking for underflow: | |
1231 | /// | |
1232 | /// ``` | |
1233 | /// let v = vec![1, 2, 0]; | |
1234 | /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| | |
1235 | /// x.checked_sub(1).ok_or("Underflow!") | |
1236 | /// ).collect(); | |
1237 | /// assert_eq!(res, Err("Underflow!")); | |
1238 | /// ``` | |
1239 | /// | |
1240 | /// Here is a variation on the previous example, showing that no | |
1241 | /// further elements are taken from `iter` after the first `Err`. | |
1242 | /// | |
1243 | /// ``` | |
1244 | /// let v = vec![3, 2, 1, 10]; | |
1245 | /// let mut shared = 0; | |
1246 | /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| { | |
1247 | /// shared += x; | |
1248 | /// x.checked_sub(2).ok_or("Underflow!") | |
1249 | /// }).collect(); | |
1250 | /// assert_eq!(res, Err("Underflow!")); | |
1251 | /// assert_eq!(shared, 6); | |
1252 | /// ``` | |
1253 | /// | |
1254 | /// Since the third element caused an underflow, no further elements were taken, | |
1255 | /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16. | |
1a4d82fc | 1256 | #[inline] |
85aaf69f | 1257 | fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> { |
1a4d82fc JJ |
1258 | // FIXME(#11084): This could be replaced with Iterator::scan when this |
1259 | // performance bug is closed. | |
1260 | ||
1261 | struct Adapter<Iter, E> { | |
1262 | iter: Iter, | |
1263 | err: Option<E>, | |
1264 | } | |
1265 | ||
1266 | impl<T, E, Iter: Iterator<Item=Result<T, E>>> Iterator for Adapter<Iter, E> { | |
1267 | type Item = T; | |
1268 | ||
1269 | #[inline] | |
1270 | fn next(&mut self) -> Option<T> { | |
1271 | match self.iter.next() { | |
1272 | Some(Ok(value)) => Some(value), | |
1273 | Some(Err(err)) => { | |
1274 | self.err = Some(err); | |
1275 | None | |
1276 | } | |
1277 | None => None, | |
1278 | } | |
1279 | } | |
c30ab7b3 SL |
1280 | |
1281 | fn size_hint(&self) -> (usize, Option<usize>) { | |
1282 | let (_min, max) = self.iter.size_hint(); | |
1283 | (0, max) | |
1284 | } | |
1a4d82fc JJ |
1285 | } |
1286 | ||
85aaf69f | 1287 | let mut adapter = Adapter { iter: iter.into_iter(), err: None }; |
1a4d82fc JJ |
1288 | let v: V = FromIterator::from_iter(adapter.by_ref()); |
1289 | ||
1290 | match adapter.err { | |
1291 | Some(err) => Err(err), | |
1292 | None => Ok(v), | |
1293 | } | |
1294 | } | |
1295 | } | |
7cac9316 XL |
1296 | |
1297 | #[unstable(feature = "try_trait", issue = "42327")] | |
1298 | impl<T,E> ops::Try for Result<T, E> { | |
1299 | type Ok = T; | |
1300 | type Error = E; | |
1301 | ||
b7449926 | 1302 | #[inline] |
7cac9316 XL |
1303 | fn into_result(self) -> Self { |
1304 | self | |
1305 | } | |
1306 | ||
b7449926 | 1307 | #[inline] |
7cac9316 XL |
1308 | fn from_ok(v: T) -> Self { |
1309 | Ok(v) | |
1310 | } | |
1311 | ||
b7449926 | 1312 | #[inline] |
7cac9316 XL |
1313 | fn from_error(v: E) -> Self { |
1314 | Err(v) | |
1315 | } | |
041b39d2 | 1316 | } |