]>
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 { | |
5e7ed085 FG |
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 | 90 | //! *Note: The actual definition of [`Write`] uses [`io::Result`], which |
c295e0f8 | 91 | //! is just a synonym for <code>[Result]<T, [io::Error]></code>.* |
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 | 114 | //! |
6a06907d | 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 | //! | |
6a06907d | 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 | 218 | //! |
3dfed10e | 219 | //! [`expect`]: Result::expect |
c295e0f8 XL |
220 | //! [`Write`]: ../../std/io/trait.Write.html "io::Write" |
221 | //! [`write_all`]: ../../std/io/trait.Write.html#method.write_all "io::Write::write_all" | |
222 | //! [`io::Result`]: ../../std/io/type.Result.html "io::Result" | |
3dfed10e XL |
223 | //! [`?`]: crate::ops::Try |
224 | //! [`Ok(T)`]: Ok | |
225 | //! [`Err(E)`]: Err | |
c295e0f8 | 226 | //! [io::Error]: ../../std/io/struct.Error.html "io::Error" |
136023e0 XL |
227 | //! |
228 | //! # Method overview | |
229 | //! | |
230 | //! In addition to working with pattern matching, [`Result`] provides a | |
231 | //! wide variety of different methods. | |
232 | //! | |
233 | //! ## Querying the variant | |
234 | //! | |
235 | //! The [`is_ok`] and [`is_err`] methods return [`true`] if the [`Result`] | |
236 | //! is [`Ok`] or [`Err`], respectively. | |
237 | //! | |
238 | //! [`is_err`]: Result::is_err | |
239 | //! [`is_ok`]: Result::is_ok | |
240 | //! | |
241 | //! ## Adapters for working with references | |
242 | //! | |
243 | //! * [`as_ref`] converts from `&Result<T, E>` to `Result<&T, &E>` | |
244 | //! * [`as_mut`] converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>` | |
245 | //! * [`as_deref`] converts from `&Result<T, E>` to `Result<&T::Target, &E>` | |
246 | //! * [`as_deref_mut`] converts from `&mut Result<T, E>` to | |
247 | //! `Result<&mut T::Target, &mut E>` | |
248 | //! | |
249 | //! [`as_deref`]: Result::as_deref | |
250 | //! [`as_deref_mut`]: Result::as_deref_mut | |
251 | //! [`as_mut`]: Result::as_mut | |
252 | //! [`as_ref`]: Result::as_ref | |
253 | //! | |
254 | //! ## Extracting contained values | |
255 | //! | |
256 | //! These methods extract the contained value in a [`Result<T, E>`] when it | |
257 | //! is the [`Ok`] variant. If the [`Result`] is [`Err`]: | |
258 | //! | |
259 | //! * [`expect`] panics with a provided custom message | |
260 | //! * [`unwrap`] panics with a generic message | |
261 | //! * [`unwrap_or`] returns the provided default value | |
262 | //! * [`unwrap_or_default`] returns the default value of the type `T` | |
263 | //! (which must implement the [`Default`] trait) | |
264 | //! * [`unwrap_or_else`] returns the result of evaluating the provided | |
265 | //! function | |
266 | //! | |
267 | //! The panicking methods [`expect`] and [`unwrap`] require `E` to | |
268 | //! implement the [`Debug`] trait. | |
269 | //! | |
270 | //! [`Debug`]: crate::fmt::Debug | |
271 | //! [`expect`]: Result::expect | |
272 | //! [`unwrap`]: Result::unwrap | |
273 | //! [`unwrap_or`]: Result::unwrap_or | |
274 | //! [`unwrap_or_default`]: Result::unwrap_or_default | |
275 | //! [`unwrap_or_else`]: Result::unwrap_or_else | |
276 | //! | |
277 | //! These methods extract the contained value in a [`Result<T, E>`] when it | |
278 | //! is the [`Err`] variant. They require `T` to implement the [`Debug`] | |
279 | //! trait. If the [`Result`] is [`Ok`]: | |
280 | //! | |
281 | //! * [`expect_err`] panics with a provided custom message | |
282 | //! * [`unwrap_err`] panics with a generic message | |
283 | //! | |
284 | //! [`Debug`]: crate::fmt::Debug | |
285 | //! [`expect_err`]: Result::expect_err | |
286 | //! [`unwrap_err`]: Result::unwrap_err | |
287 | //! | |
288 | //! ## Transforming contained values | |
289 | //! | |
290 | //! These methods transform [`Result`] to [`Option`]: | |
291 | //! | |
292 | //! * [`err`][Result::err] transforms [`Result<T, E>`] into [`Option<E>`], | |
293 | //! mapping [`Err(e)`] to [`Some(e)`] and [`Ok(v)`] to [`None`] | |
294 | //! * [`ok`][Result::ok] transforms [`Result<T, E>`] into [`Option<T>`], | |
295 | //! mapping [`Ok(v)`] to [`Some(v)`] and [`Err(e)`] to [`None`] | |
296 | //! * [`transpose`] transposes a [`Result`] of an [`Option`] into an | |
297 | //! [`Option`] of a [`Result`] | |
298 | //! | |
299 | // Do NOT add link reference definitions for `err` or `ok`, because they | |
300 | // will generate numerous incorrect URLs for `Err` and `Ok` elsewhere, due | |
301 | // to case folding. | |
302 | //! | |
303 | //! [`Err(e)`]: Err | |
304 | //! [`Ok(v)`]: Ok | |
305 | //! [`Some(e)`]: Option::Some | |
306 | //! [`Some(v)`]: Option::Some | |
307 | //! [`transpose`]: Result::transpose | |
308 | //! | |
309 | //! This method transforms the contained value of the [`Ok`] variant: | |
310 | //! | |
311 | //! * [`map`] transforms [`Result<T, E>`] into [`Result<U, E>`] by applying | |
312 | //! the provided function to the contained value of [`Ok`] and leaving | |
313 | //! [`Err`] values unchanged | |
314 | //! | |
315 | //! [`map`]: Result::map | |
316 | //! | |
317 | //! This method transforms the contained value of the [`Err`] variant: | |
318 | //! | |
319 | //! * [`map_err`] transforms [`Result<T, E>`] into [`Result<T, F>`] by | |
320 | //! applying the provided function to the contained value of [`Err`] and | |
321 | //! leaving [`Ok`] values unchanged | |
322 | //! | |
323 | //! [`map_err`]: Result::map_err | |
324 | //! | |
325 | //! These methods transform a [`Result<T, E>`] into a value of a possibly | |
326 | //! different type `U`: | |
327 | //! | |
328 | //! * [`map_or`] applies the provided function to the contained value of | |
329 | //! [`Ok`], or returns the provided default value if the [`Result`] is | |
330 | //! [`Err`] | |
331 | //! * [`map_or_else`] applies the provided function to the contained value | |
c295e0f8 XL |
332 | //! of [`Ok`], or applies the provided default fallback function to the |
333 | //! contained value of [`Err`] | |
136023e0 XL |
334 | //! |
335 | //! [`map_or`]: Result::map_or | |
336 | //! [`map_or_else`]: Result::map_or_else | |
337 | //! | |
338 | //! ## Boolean operators | |
339 | //! | |
340 | //! These methods treat the [`Result`] as a boolean value, where [`Ok`] | |
341 | //! acts like [`true`] and [`Err`] acts like [`false`]. There are two | |
342 | //! categories of these methods: ones that take a [`Result`] as input, and | |
343 | //! ones that take a function as input (to be lazily evaluated). | |
344 | //! | |
345 | //! The [`and`] and [`or`] methods take another [`Result`] as input, and | |
346 | //! produce a [`Result`] as output. The [`and`] method can produce a | |
347 | //! [`Result<U, E>`] value having a different inner type `U` than | |
348 | //! [`Result<T, E>`]. The [`or`] method can produce a [`Result<T, F>`] | |
349 | //! value having a different error type `F` than [`Result<T, E>`]. | |
350 | //! | |
351 | //! | method | self | input | output | | |
352 | //! |---------|----------|-----------|----------| | |
353 | //! | [`and`] | `Err(e)` | (ignored) | `Err(e)` | | |
354 | //! | [`and`] | `Ok(x)` | `Err(d)` | `Err(d)` | | |
355 | //! | [`and`] | `Ok(x)` | `Ok(y)` | `Ok(y)` | | |
356 | //! | [`or`] | `Err(e)` | `Err(d)` | `Err(d)` | | |
357 | //! | [`or`] | `Err(e)` | `Ok(y)` | `Ok(y)` | | |
358 | //! | [`or`] | `Ok(x)` | (ignored) | `Ok(x)` | | |
359 | //! | |
360 | //! [`and`]: Result::and | |
361 | //! [`or`]: Result::or | |
362 | //! | |
363 | //! The [`and_then`] and [`or_else`] methods take a function as input, and | |
364 | //! only evaluate the function when they need to produce a new value. The | |
365 | //! [`and_then`] method can produce a [`Result<U, E>`] value having a | |
366 | //! different inner type `U` than [`Result<T, E>`]. The [`or_else`] method | |
367 | //! can produce a [`Result<T, F>`] value having a different error type `F` | |
368 | //! than [`Result<T, E>`]. | |
369 | //! | |
370 | //! | method | self | function input | function result | output | | |
371 | //! |--------------|----------|----------------|-----------------|----------| | |
372 | //! | [`and_then`] | `Err(e)` | (not provided) | (not evaluated) | `Err(e)` | | |
373 | //! | [`and_then`] | `Ok(x)` | `x` | `Err(d)` | `Err(d)` | | |
374 | //! | [`and_then`] | `Ok(x)` | `x` | `Ok(y)` | `Ok(y)` | | |
375 | //! | [`or_else`] | `Err(e)` | `e` | `Err(d)` | `Err(d)` | | |
376 | //! | [`or_else`] | `Err(e)` | `e` | `Ok(y)` | `Ok(y)` | | |
377 | //! | [`or_else`] | `Ok(x)` | (not provided) | (not evaluated) | `Ok(x)` | | |
378 | //! | |
379 | //! [`and_then`]: Result::and_then | |
380 | //! [`or_else`]: Result::or_else | |
381 | //! | |
94222f64 XL |
382 | //! ## Comparison operators |
383 | //! | |
384 | //! If `T` and `E` both implement [`PartialOrd`] then [`Result<T, E>`] will | |
385 | //! derive its [`PartialOrd`] implementation. With this order, an [`Ok`] | |
386 | //! compares as less than any [`Err`], while two [`Ok`] or two [`Err`] | |
387 | //! compare as their contained values would in `T` or `E` respectively. If `T` | |
388 | //! and `E` both also implement [`Ord`], then so does [`Result<T, E>`]. | |
389 | //! | |
390 | //! ``` | |
391 | //! assert!(Ok(1) < Err(0)); | |
392 | //! let x: Result<i32, ()> = Ok(0); | |
393 | //! let y = Ok(1); | |
394 | //! assert!(x < y); | |
395 | //! let x: Result<(), i32> = Err(0); | |
396 | //! let y = Err(1); | |
397 | //! assert!(x < y); | |
398 | //! ``` | |
399 | //! | |
136023e0 XL |
400 | //! ## Iterating over `Result` |
401 | //! | |
402 | //! A [`Result`] can be iterated over. This can be helpful if you need an | |
403 | //! iterator that is conditionally empty. The iterator will either produce | |
404 | //! a single value (when the [`Result`] is [`Ok`]), or produce no values | |
405 | //! (when the [`Result`] is [`Err`]). For example, [`into_iter`] acts like | |
406 | //! [`once(v)`] if the [`Result`] is [`Ok(v)`], and like [`empty()`] if the | |
407 | //! [`Result`] is [`Err`]. | |
408 | //! | |
409 | //! [`Ok(v)`]: Ok | |
410 | //! [`empty()`]: crate::iter::empty | |
411 | //! [`once(v)`]: crate::iter::once | |
412 | //! | |
413 | //! Iterators over [`Result<T, E>`] come in three types: | |
414 | //! | |
415 | //! * [`into_iter`] consumes the [`Result`] and produces the contained | |
416 | //! value | |
417 | //! * [`iter`] produces an immutable reference of type `&T` to the | |
418 | //! contained value | |
419 | //! * [`iter_mut`] produces a mutable reference of type `&mut T` to the | |
420 | //! contained value | |
421 | //! | |
422 | //! See [Iterating over `Option`] for examples of how this can be useful. | |
423 | //! | |
424 | //! [Iterating over `Option`]: crate::option#iterating-over-option | |
425 | //! [`into_iter`]: Result::into_iter | |
426 | //! [`iter`]: Result::iter | |
427 | //! [`iter_mut`]: Result::iter_mut | |
428 | //! | |
429 | //! You might want to use an iterator chain to do multiple instances of an | |
430 | //! operation that can fail, but would like to ignore failures while | |
431 | //! continuing to process the successful results. In this example, we take | |
432 | //! advantage of the iterable nature of [`Result`] to select only the | |
433 | //! [`Ok`] values using [`flatten`][Iterator::flatten]. | |
434 | //! | |
435 | //! ``` | |
436 | //! # use std::str::FromStr; | |
437 | //! let mut results = vec![]; | |
438 | //! let mut errs = vec![]; | |
5099ac24 | 439 | //! let nums: Vec<_> = ["17", "not a number", "99", "-27", "768"] |
136023e0 XL |
440 | //! .into_iter() |
441 | //! .map(u8::from_str) | |
442 | //! // Save clones of the raw `Result` values to inspect | |
443 | //! .inspect(|x| results.push(x.clone())) | |
444 | //! // Challenge: explain how this captures only the `Err` values | |
445 | //! .inspect(|x| errs.extend(x.clone().err())) | |
446 | //! .flatten() | |
447 | //! .collect(); | |
448 | //! assert_eq!(errs.len(), 3); | |
449 | //! assert_eq!(nums, [17, 99]); | |
5e7ed085 FG |
450 | //! println!("results {results:?}"); |
451 | //! println!("errs {errs:?}"); | |
452 | //! println!("nums {nums:?}"); | |
136023e0 XL |
453 | //! ``` |
454 | //! | |
455 | //! ## Collecting into `Result` | |
456 | //! | |
457 | //! [`Result`] implements the [`FromIterator`][impl-FromIterator] trait, | |
458 | //! which allows an iterator over [`Result`] values to be collected into a | |
459 | //! [`Result`] of a collection of each contained value of the original | |
460 | //! [`Result`] values, or [`Err`] if any of the elements was [`Err`]. | |
461 | //! | |
462 | //! [impl-FromIterator]: Result#impl-FromIterator%3CResult%3CA%2C%20E%3E%3E | |
463 | //! | |
464 | //! ``` | |
5099ac24 | 465 | //! let v = [Ok(2), Ok(4), Err("err!"), Ok(8)]; |
136023e0 XL |
466 | //! let res: Result<Vec<_>, &str> = v.into_iter().collect(); |
467 | //! assert_eq!(res, Err("err!")); | |
5099ac24 | 468 | //! let v = [Ok(2), Ok(4), Ok(8)]; |
136023e0 XL |
469 | //! let res: Result<Vec<_>, &str> = v.into_iter().collect(); |
470 | //! assert_eq!(res, Ok(vec![2, 4, 8])); | |
471 | //! ``` | |
472 | //! | |
473 | //! [`Result`] also implements the [`Product`][impl-Product] and | |
474 | //! [`Sum`][impl-Sum] traits, allowing an iterator over [`Result`] values | |
475 | //! to provide the [`product`][Iterator::product] and | |
476 | //! [`sum`][Iterator::sum] methods. | |
477 | //! | |
478 | //! [impl-Product]: Result#impl-Product%3CResult%3CU%2C%20E%3E%3E | |
479 | //! [impl-Sum]: Result#impl-Sum%3CResult%3CU%2C%20E%3E%3E | |
480 | //! | |
481 | //! ``` | |
5099ac24 | 482 | //! let v = [Err("error!"), Ok(1), Ok(2), Ok(3), Err("foo")]; |
136023e0 XL |
483 | //! let res: Result<i32, &str> = v.into_iter().sum(); |
484 | //! assert_eq!(res, Err("error!")); | |
5099ac24 | 485 | //! let v = [Ok(1), Ok(2), Ok(21)]; |
136023e0 XL |
486 | //! let res: Result<i32, &str> = v.into_iter().product(); |
487 | //! assert_eq!(res, Ok(42)); | |
488 | //! ``` | |
1a4d82fc | 489 | |
85aaf69f | 490 | #![stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 491 | |
416331ca | 492 | use crate::iter::{self, FromIterator, FusedIterator, TrustedLen}; |
5e7ed085 | 493 | use crate::marker::Destruct; |
cdc7bbd5 | 494 | use crate::ops::{self, ControlFlow, Deref, DerefMut}; |
5869c6ff | 495 | use crate::{convert, fmt, hint}; |
1a4d82fc | 496 | |
3b2f2976 | 497 | /// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]). |
1a4d82fc | 498 | /// |
29967ef6 | 499 | /// See the [module documentation](self) for details. |
dc9dc135 | 500 | #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] |
94b46f34 | 501 | #[must_use = "this `Result` may be an `Err` variant, which should be handled"] |
c295e0f8 | 502 | #[rustc_diagnostic_item = "Result"] |
85aaf69f | 503 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
504 | pub enum Result<T, E> { |
505 | /// Contains the success value | |
1b1a35ee | 506 | #[lang = "Ok"] |
85aaf69f | 507 | #[stable(feature = "rust1", since = "1.0.0")] |
7453a54e | 508 | Ok(#[stable(feature = "rust1", since = "1.0.0")] T), |
1a4d82fc JJ |
509 | |
510 | /// Contains the error value | |
1b1a35ee | 511 | #[lang = "Err"] |
85aaf69f | 512 | #[stable(feature = "rust1", since = "1.0.0")] |
a7813a04 | 513 | Err(#[stable(feature = "rust1", since = "1.0.0")] E), |
1a4d82fc JJ |
514 | } |
515 | ||
516 | ///////////////////////////////////////////////////////////////////////////// | |
517 | // Type implementation | |
518 | ///////////////////////////////////////////////////////////////////////////// | |
519 | ||
1a4d82fc JJ |
520 | impl<T, E> Result<T, E> { |
521 | ///////////////////////////////////////////////////////////////////////// | |
522 | // Querying the contained values | |
523 | ///////////////////////////////////////////////////////////////////////// | |
524 | ||
3b2f2976 XL |
525 | /// Returns `true` if the result is [`Ok`]. |
526 | /// | |
c34b1796 | 527 | /// # Examples |
1a4d82fc | 528 | /// |
a7813a04 XL |
529 | /// Basic usage: |
530 | /// | |
1a4d82fc | 531 | /// ``` |
c34b1796 | 532 | /// let x: Result<i32, &str> = Ok(-3); |
1a4d82fc JJ |
533 | /// assert_eq!(x.is_ok(), true); |
534 | /// | |
c34b1796 | 535 | /// let x: Result<i32, &str> = Err("Some error message"); |
1a4d82fc JJ |
536 | /// assert_eq!(x.is_ok(), false); |
537 | /// ``` | |
416331ca | 538 | #[must_use = "if you intended to assert that this is ok, consider `.unwrap()` instead"] |
5e7ed085 | 539 | #[rustc_const_stable(feature = "const_result_basics", since = "1.48.0")] |
1a4d82fc | 540 | #[inline] |
85aaf69f | 541 | #[stable(feature = "rust1", since = "1.0.0")] |
dfeec247 XL |
542 | pub const fn is_ok(&self) -> bool { |
543 | matches!(*self, Ok(_)) | |
1a4d82fc JJ |
544 | } |
545 | ||
5e7ed085 | 546 | /// Returns `true` if the result is [`Ok`] and the value inside of it matches a predicate. |
5099ac24 FG |
547 | /// |
548 | /// # Examples | |
549 | /// | |
550 | /// ``` | |
551 | /// #![feature(is_some_with)] | |
552 | /// | |
553 | /// let x: Result<u32, &str> = Ok(2); | |
5e7ed085 | 554 | /// assert_eq!(x.is_ok_and(|&x| x > 1), true); |
5099ac24 FG |
555 | /// |
556 | /// let x: Result<u32, &str> = Ok(0); | |
5e7ed085 | 557 | /// assert_eq!(x.is_ok_and(|&x| x > 1), false); |
5099ac24 FG |
558 | /// |
559 | /// let x: Result<u32, &str> = Err("hey"); | |
5e7ed085 | 560 | /// assert_eq!(x.is_ok_and(|&x| x > 1), false); |
5099ac24 FG |
561 | /// ``` |
562 | #[must_use] | |
563 | #[inline] | |
564 | #[unstable(feature = "is_some_with", issue = "93050")] | |
5e7ed085 | 565 | pub fn is_ok_and(&self, f: impl FnOnce(&T) -> bool) -> bool { |
5099ac24 FG |
566 | matches!(self, Ok(x) if f(x)) |
567 | } | |
568 | ||
3b2f2976 XL |
569 | /// Returns `true` if the result is [`Err`]. |
570 | /// | |
c34b1796 | 571 | /// # Examples |
1a4d82fc | 572 | /// |
a7813a04 XL |
573 | /// Basic usage: |
574 | /// | |
1a4d82fc | 575 | /// ``` |
c34b1796 | 576 | /// let x: Result<i32, &str> = Ok(-3); |
1a4d82fc JJ |
577 | /// assert_eq!(x.is_err(), false); |
578 | /// | |
c34b1796 | 579 | /// let x: Result<i32, &str> = Err("Some error message"); |
1a4d82fc JJ |
580 | /// assert_eq!(x.is_err(), true); |
581 | /// ``` | |
416331ca | 582 | #[must_use = "if you intended to assert that this is err, consider `.unwrap_err()` instead"] |
5e7ed085 | 583 | #[rustc_const_stable(feature = "const_result_basics", since = "1.48.0")] |
1a4d82fc | 584 | #[inline] |
85aaf69f | 585 | #[stable(feature = "rust1", since = "1.0.0")] |
dfeec247 | 586 | pub const fn is_err(&self) -> bool { |
1a4d82fc JJ |
587 | !self.is_ok() |
588 | } | |
589 | ||
5e7ed085 | 590 | /// Returns `true` if the result is [`Err`] and the value inside of it matches a predicate. |
5099ac24 FG |
591 | /// |
592 | /// # Examples | |
593 | /// | |
594 | /// ``` | |
595 | /// #![feature(is_some_with)] | |
596 | /// use std::io::{Error, ErrorKind}; | |
597 | /// | |
598 | /// let x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, "!")); | |
5e7ed085 | 599 | /// assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true); |
5099ac24 FG |
600 | /// |
601 | /// let x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, "!")); | |
5e7ed085 | 602 | /// assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); |
5099ac24 FG |
603 | /// |
604 | /// let x: Result<u32, Error> = Ok(123); | |
5e7ed085 | 605 | /// assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); |
5099ac24 FG |
606 | /// ``` |
607 | #[must_use] | |
608 | #[inline] | |
609 | #[unstable(feature = "is_some_with", issue = "93050")] | |
5e7ed085 | 610 | pub fn is_err_and(&self, f: impl FnOnce(&E) -> bool) -> bool { |
5099ac24 FG |
611 | matches!(self, Err(x) if f(x)) |
612 | } | |
613 | ||
1a4d82fc JJ |
614 | ///////////////////////////////////////////////////////////////////////// |
615 | // Adapter for each variant | |
616 | ///////////////////////////////////////////////////////////////////////// | |
617 | ||
9e0c209e | 618 | /// Converts from `Result<T, E>` to [`Option<T>`]. |
1a4d82fc | 619 | /// |
9e0c209e | 620 | /// Converts `self` into an [`Option<T>`], consuming `self`, |
1a4d82fc JJ |
621 | /// and discarding the error, if any. |
622 | /// | |
c34b1796 | 623 | /// # Examples |
1a4d82fc | 624 | /// |
a7813a04 XL |
625 | /// Basic usage: |
626 | /// | |
1a4d82fc | 627 | /// ``` |
85aaf69f | 628 | /// let x: Result<u32, &str> = Ok(2); |
1a4d82fc JJ |
629 | /// assert_eq!(x.ok(), Some(2)); |
630 | /// | |
85aaf69f | 631 | /// let x: Result<u32, &str> = Err("Nothing here"); |
1a4d82fc JJ |
632 | /// assert_eq!(x.ok(), None); |
633 | /// ``` | |
634 | #[inline] | |
85aaf69f | 635 | #[stable(feature = "rust1", since = "1.0.0")] |
5e7ed085 FG |
636 | #[rustc_const_unstable(feature = "const_result_drop", issue = "92384")] |
637 | pub const fn ok(self) -> Option<T> | |
638 | where | |
04454e1e | 639 | E: ~const Destruct, |
5e7ed085 | 640 | { |
1a4d82fc | 641 | match self { |
dfeec247 | 642 | Ok(x) => Some(x), |
5e7ed085 FG |
643 | // FIXME: ~const Drop doesn't quite work right yet |
644 | #[allow(unused_variables)] | |
645 | Err(x) => None, | |
1a4d82fc JJ |
646 | } |
647 | } | |
648 | ||
9e0c209e | 649 | /// Converts from `Result<T, E>` to [`Option<E>`]. |
1a4d82fc | 650 | /// |
9e0c209e | 651 | /// Converts `self` into an [`Option<E>`], consuming `self`, |
c34b1796 | 652 | /// and discarding the success value, if any. |
1a4d82fc | 653 | /// |
c34b1796 | 654 | /// # Examples |
1a4d82fc | 655 | /// |
a7813a04 XL |
656 | /// Basic usage: |
657 | /// | |
1a4d82fc | 658 | /// ``` |
85aaf69f | 659 | /// let x: Result<u32, &str> = Ok(2); |
1a4d82fc JJ |
660 | /// assert_eq!(x.err(), None); |
661 | /// | |
85aaf69f | 662 | /// let x: Result<u32, &str> = Err("Nothing here"); |
1a4d82fc JJ |
663 | /// assert_eq!(x.err(), Some("Nothing here")); |
664 | /// ``` | |
665 | #[inline] | |
85aaf69f | 666 | #[stable(feature = "rust1", since = "1.0.0")] |
5e7ed085 FG |
667 | #[rustc_const_unstable(feature = "const_result_drop", issue = "92384")] |
668 | pub const fn err(self) -> Option<E> | |
669 | where | |
04454e1e | 670 | T: ~const Destruct, |
5e7ed085 | 671 | { |
1a4d82fc | 672 | match self { |
5e7ed085 FG |
673 | // FIXME: ~const Drop doesn't quite work right yet |
674 | #[allow(unused_variables)] | |
675 | Ok(x) => None, | |
1a4d82fc JJ |
676 | Err(x) => Some(x), |
677 | } | |
678 | } | |
679 | ||
680 | ///////////////////////////////////////////////////////////////////////// | |
681 | // Adapter for working with references | |
682 | ///////////////////////////////////////////////////////////////////////// | |
683 | ||
532ac7d7 | 684 | /// Converts from `&Result<T, E>` to `Result<&T, &E>`. |
1a4d82fc JJ |
685 | /// |
686 | /// Produces a new `Result`, containing a reference | |
687 | /// into the original, leaving the original in place. | |
688 | /// | |
a7813a04 XL |
689 | /// # Examples |
690 | /// | |
691 | /// Basic usage: | |
692 | /// | |
1a4d82fc | 693 | /// ``` |
85aaf69f | 694 | /// let x: Result<u32, &str> = Ok(2); |
1a4d82fc JJ |
695 | /// assert_eq!(x.as_ref(), Ok(&2)); |
696 | /// | |
85aaf69f | 697 | /// let x: Result<u32, &str> = Err("Error"); |
1a4d82fc JJ |
698 | /// assert_eq!(x.as_ref(), Err(&"Error")); |
699 | /// ``` | |
700 | #[inline] | |
5e7ed085 | 701 | #[rustc_const_stable(feature = "const_result_basics", since = "1.48.0")] |
85aaf69f | 702 | #[stable(feature = "rust1", since = "1.0.0")] |
dfeec247 | 703 | pub const fn as_ref(&self) -> Result<&T, &E> { |
1a4d82fc JJ |
704 | match *self { |
705 | Ok(ref x) => Ok(x), | |
706 | Err(ref x) => Err(x), | |
707 | } | |
708 | } | |
709 | ||
532ac7d7 | 710 | /// Converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`. |
1a4d82fc | 711 | /// |
a7813a04 XL |
712 | /// # Examples |
713 | /// | |
714 | /// Basic usage: | |
715 | /// | |
1a4d82fc | 716 | /// ``` |
c34b1796 | 717 | /// fn mutate(r: &mut Result<i32, i32>) { |
1a4d82fc | 718 | /// match r.as_mut() { |
5bcae85e SL |
719 | /// Ok(v) => *v = 42, |
720 | /// Err(e) => *e = 0, | |
1a4d82fc JJ |
721 | /// } |
722 | /// } | |
723 | /// | |
c34b1796 | 724 | /// let mut x: Result<i32, i32> = Ok(2); |
1a4d82fc JJ |
725 | /// mutate(&mut x); |
726 | /// assert_eq!(x.unwrap(), 42); | |
727 | /// | |
c34b1796 | 728 | /// let mut x: Result<i32, i32> = Err(13); |
1a4d82fc JJ |
729 | /// mutate(&mut x); |
730 | /// assert_eq!(x.unwrap_err(), 0); | |
731 | /// ``` | |
732 | #[inline] | |
85aaf69f | 733 | #[stable(feature = "rust1", since = "1.0.0")] |
3c0e092e XL |
734 | #[rustc_const_unstable(feature = "const_result", issue = "82814")] |
735 | pub const fn as_mut(&mut self) -> Result<&mut T, &mut E> { | |
1a4d82fc JJ |
736 | match *self { |
737 | Ok(ref mut x) => Ok(x), | |
738 | Err(ref mut x) => Err(x), | |
739 | } | |
740 | } | |
741 | ||
1a4d82fc JJ |
742 | ///////////////////////////////////////////////////////////////////////// |
743 | // Transforming contained values | |
744 | ///////////////////////////////////////////////////////////////////////// | |
745 | ||
92a42be0 | 746 | /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a |
3b2f2976 | 747 | /// contained [`Ok`] value, leaving an [`Err`] value untouched. |
1a4d82fc JJ |
748 | /// |
749 | /// This function can be used to compose the results of two functions. | |
750 | /// | |
c34b1796 | 751 | /// # Examples |
1a4d82fc | 752 | /// |
9346a6ac | 753 | /// Print the numbers on each line of a string multiplied by two. |
1a4d82fc JJ |
754 | /// |
755 | /// ``` | |
9346a6ac | 756 | /// let line = "1\n2\n3\n4\n"; |
1a4d82fc | 757 | /// |
9346a6ac AL |
758 | /// for num in line.lines() { |
759 | /// match num.parse::<i32>().map(|i| i * 2) { | |
5e7ed085 | 760 | /// Ok(n) => println!("{n}"), |
9346a6ac AL |
761 | /// Err(..) => {} |
762 | /// } | |
1a4d82fc | 763 | /// } |
1a4d82fc JJ |
764 | /// ``` |
765 | #[inline] | |
85aaf69f | 766 | #[stable(feature = "rust1", since = "1.0.0")] |
dfeec247 | 767 | pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U, E> { |
1a4d82fc JJ |
768 | match self { |
769 | Ok(t) => Ok(op(t)), | |
dfeec247 | 770 | Err(e) => Err(e), |
1a4d82fc JJ |
771 | } |
772 | } | |
773 | ||
cdc7bbd5 XL |
774 | /// Returns the provided default (if [`Err`]), or |
775 | /// applies a function to the contained value (if [`Ok`]), | |
60c5eb7d | 776 | /// |
74b04a01 XL |
777 | /// Arguments passed to `map_or` are eagerly evaluated; if you are passing |
778 | /// the result of a function call, it is recommended to use [`map_or_else`], | |
779 | /// which is lazily evaluated. | |
780 | /// | |
3dfed10e | 781 | /// [`map_or_else`]: Result::map_or_else |
74b04a01 | 782 | /// |
60c5eb7d XL |
783 | /// # Examples |
784 | /// | |
785 | /// ``` | |
786 | /// let x: Result<_, &str> = Ok("foo"); | |
787 | /// assert_eq!(x.map_or(42, |v| v.len()), 3); | |
788 | /// | |
789 | /// let x: Result<&str, _> = Err("bar"); | |
790 | /// assert_eq!(x.map_or(42, |v| v.len()), 42); | |
791 | /// ``` | |
792 | #[inline] | |
793 | #[stable(feature = "result_map_or", since = "1.41.0")] | |
794 | pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U { | |
795 | match self { | |
796 | Ok(t) => f(t), | |
797 | Err(_) => default, | |
798 | } | |
799 | } | |
800 | ||
c295e0f8 XL |
801 | /// Maps a `Result<T, E>` to `U` by applying fallback function `default` to |
802 | /// a contained [`Err`] value, or function `f` to a contained [`Ok`] value. | |
b7449926 XL |
803 | /// |
804 | /// This function can be used to unpack a successful result | |
805 | /// while handling an error. | |
806 | /// | |
b7449926 XL |
807 | /// |
808 | /// # Examples | |
809 | /// | |
810 | /// Basic usage: | |
811 | /// | |
812 | /// ``` | |
b7449926 XL |
813 | /// let k = 21; |
814 | /// | |
815 | /// let x : Result<_, &str> = Ok("foo"); | |
816 | /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3); | |
817 | /// | |
818 | /// let x : Result<&str, _> = Err("bar"); | |
819 | /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42); | |
820 | /// ``` | |
821 | #[inline] | |
60c5eb7d XL |
822 | #[stable(feature = "result_map_or_else", since = "1.41.0")] |
823 | pub fn map_or_else<U, D: FnOnce(E) -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U { | |
824 | match self { | |
825 | Ok(t) => f(t), | |
826 | Err(e) => default(e), | |
827 | } | |
b7449926 XL |
828 | } |
829 | ||
92a42be0 | 830 | /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a |
3b2f2976 | 831 | /// contained [`Err`] value, leaving an [`Ok`] value untouched. |
1a4d82fc JJ |
832 | /// |
833 | /// This function can be used to pass through a successful result while handling | |
834 | /// an error. | |
835 | /// | |
3b2f2976 | 836 | /// |
c34b1796 | 837 | /// # Examples |
1a4d82fc | 838 | /// |
a7813a04 XL |
839 | /// Basic usage: |
840 | /// | |
1a4d82fc | 841 | /// ``` |
5e7ed085 | 842 | /// fn stringify(x: u32) -> String { format!("error code: {x}") } |
1a4d82fc | 843 | /// |
85aaf69f SL |
844 | /// let x: Result<u32, u32> = Ok(2); |
845 | /// assert_eq!(x.map_err(stringify), Ok(2)); | |
1a4d82fc | 846 | /// |
85aaf69f | 847 | /// let x: Result<u32, u32> = Err(13); |
1a4d82fc JJ |
848 | /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string())); |
849 | /// ``` | |
850 | #[inline] | |
85aaf69f | 851 | #[stable(feature = "rust1", since = "1.0.0")] |
dfeec247 | 852 | pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T, F> { |
1a4d82fc JJ |
853 | match self { |
854 | Ok(t) => Ok(t), | |
dfeec247 | 855 | Err(e) => Err(op(e)), |
1a4d82fc JJ |
856 | } |
857 | } | |
858 | ||
a2a8927a XL |
859 | /// Calls the provided closure with a reference to the contained value (if [`Ok`]). |
860 | /// | |
861 | /// # Examples | |
862 | /// | |
863 | /// ``` | |
864 | /// #![feature(result_option_inspect)] | |
865 | /// | |
866 | /// let x: u8 = "4" | |
867 | /// .parse::<u8>() | |
5e7ed085 | 868 | /// .inspect(|x| println!("original: {x}")) |
a2a8927a XL |
869 | /// .map(|x| x.pow(3)) |
870 | /// .expect("failed to parse number"); | |
871 | /// ``` | |
872 | #[inline] | |
873 | #[unstable(feature = "result_option_inspect", issue = "91345")] | |
874 | pub fn inspect<F: FnOnce(&T)>(self, f: F) -> Self { | |
875 | if let Ok(ref t) = self { | |
876 | f(t); | |
877 | } | |
878 | ||
879 | self | |
880 | } | |
881 | ||
882 | /// Calls the provided closure with a reference to the contained error (if [`Err`]). | |
883 | /// | |
884 | /// # Examples | |
885 | /// | |
886 | /// ``` | |
887 | /// #![feature(result_option_inspect)] | |
888 | /// | |
889 | /// use std::{fs, io}; | |
890 | /// | |
891 | /// fn read() -> io::Result<String> { | |
892 | /// fs::read_to_string("address.txt") | |
5e7ed085 | 893 | /// .inspect_err(|e| eprintln!("failed to read file: {e}")) |
a2a8927a XL |
894 | /// } |
895 | /// ``` | |
896 | #[inline] | |
897 | #[unstable(feature = "result_option_inspect", issue = "91345")] | |
898 | pub fn inspect_err<F: FnOnce(&E)>(self, f: F) -> Self { | |
899 | if let Err(ref e) = self { | |
900 | f(e); | |
901 | } | |
902 | ||
903 | self | |
904 | } | |
905 | ||
906 | /// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&<T as Deref>::Target, &E>`. | |
907 | /// | |
908 | /// Coerces the [`Ok`] variant of the original [`Result`] via [`Deref`](crate::ops::Deref) | |
909 | /// and returns the new [`Result`]. | |
910 | /// | |
911 | /// # Examples | |
912 | /// | |
913 | /// ``` | |
914 | /// let x: Result<String, u32> = Ok("hello".to_string()); | |
915 | /// let y: Result<&str, &u32> = Ok("hello"); | |
916 | /// assert_eq!(x.as_deref(), y); | |
917 | /// | |
918 | /// let x: Result<String, u32> = Err(42); | |
919 | /// let y: Result<&str, &u32> = Err(&42); | |
920 | /// assert_eq!(x.as_deref(), y); | |
921 | /// ``` | |
922 | #[stable(feature = "inner_deref", since = "1.47.0")] | |
923 | pub fn as_deref(&self) -> Result<&T::Target, &E> | |
924 | where | |
925 | T: Deref, | |
926 | { | |
927 | self.as_ref().map(|t| t.deref()) | |
928 | } | |
929 | ||
930 | /// Converts from `Result<T, E>` (or `&mut Result<T, E>`) to `Result<&mut <T as DerefMut>::Target, &mut E>`. | |
931 | /// | |
932 | /// Coerces the [`Ok`] variant of the original [`Result`] via [`DerefMut`](crate::ops::DerefMut) | |
933 | /// and returns the new [`Result`]. | |
934 | /// | |
935 | /// # Examples | |
936 | /// | |
937 | /// ``` | |
938 | /// let mut s = "HELLO".to_string(); | |
939 | /// let mut x: Result<String, u32> = Ok("hello".to_string()); | |
940 | /// let y: Result<&mut str, &mut u32> = Ok(&mut s); | |
941 | /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); | |
942 | /// | |
943 | /// let mut i = 42; | |
944 | /// let mut x: Result<String, u32> = Err(42); | |
945 | /// let y: Result<&mut str, &mut u32> = Err(&mut i); | |
946 | /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); | |
947 | /// ``` | |
948 | #[stable(feature = "inner_deref", since = "1.47.0")] | |
949 | pub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E> | |
950 | where | |
951 | T: DerefMut, | |
952 | { | |
953 | self.as_mut().map(|t| t.deref_mut()) | |
954 | } | |
955 | ||
1a4d82fc JJ |
956 | ///////////////////////////////////////////////////////////////////////// |
957 | // Iterator constructors | |
958 | ///////////////////////////////////////////////////////////////////////// | |
959 | ||
960 | /// Returns an iterator over the possibly contained value. | |
961 | /// | |
b7449926 | 962 | /// The iterator yields one value if the result is [`Result::Ok`], otherwise none. |
32a655c1 | 963 | /// |
c34b1796 | 964 | /// # Examples |
1a4d82fc | 965 | /// |
a7813a04 XL |
966 | /// Basic usage: |
967 | /// | |
1a4d82fc | 968 | /// ``` |
85aaf69f | 969 | /// let x: Result<u32, &str> = Ok(7); |
1a4d82fc JJ |
970 | /// assert_eq!(x.iter().next(), Some(&7)); |
971 | /// | |
85aaf69f | 972 | /// let x: Result<u32, &str> = Err("nothing!"); |
1a4d82fc JJ |
973 | /// assert_eq!(x.iter().next(), None); |
974 | /// ``` | |
975 | #[inline] | |
85aaf69f | 976 | #[stable(feature = "rust1", since = "1.0.0")] |
48663c56 | 977 | pub fn iter(&self) -> Iter<'_, T> { |
1a4d82fc JJ |
978 | Iter { inner: self.as_ref().ok() } |
979 | } | |
980 | ||
981 | /// Returns a mutable iterator over the possibly contained value. | |
982 | /// | |
b7449926 | 983 | /// The iterator yields one value if the result is [`Result::Ok`], otherwise none. |
32a655c1 | 984 | /// |
c34b1796 | 985 | /// # Examples |
1a4d82fc | 986 | /// |
a7813a04 XL |
987 | /// Basic usage: |
988 | /// | |
1a4d82fc | 989 | /// ``` |
85aaf69f | 990 | /// let mut x: Result<u32, &str> = Ok(7); |
1a4d82fc | 991 | /// match x.iter_mut().next() { |
b039eaaf | 992 | /// Some(v) => *v = 40, |
1a4d82fc JJ |
993 | /// None => {}, |
994 | /// } | |
995 | /// assert_eq!(x, Ok(40)); | |
996 | /// | |
85aaf69f | 997 | /// let mut x: Result<u32, &str> = Err("nothing!"); |
1a4d82fc JJ |
998 | /// assert_eq!(x.iter_mut().next(), None); |
999 | /// ``` | |
1000 | #[inline] | |
85aaf69f | 1001 | #[stable(feature = "rust1", since = "1.0.0")] |
48663c56 | 1002 | pub fn iter_mut(&mut self) -> IterMut<'_, T> { |
1a4d82fc JJ |
1003 | IterMut { inner: self.as_mut().ok() } |
1004 | } | |
1005 | ||
a2a8927a XL |
1006 | ///////////////////////////////////////////////////////////////////////// |
1007 | // Extract a value | |
1a4d82fc JJ |
1008 | ///////////////////////////////////////////////////////////////////////// |
1009 | ||
a2a8927a | 1010 | /// Returns the contained [`Ok`] value, consuming the `self` value. |
1a4d82fc | 1011 | /// |
a2a8927a | 1012 | /// # Panics |
1a4d82fc | 1013 | /// |
a2a8927a XL |
1014 | /// Panics if the value is an [`Err`], with a panic message including the |
1015 | /// passed message, and the content of the [`Err`]. | |
a7813a04 | 1016 | /// |
1a4d82fc | 1017 | /// |
a2a8927a | 1018 | /// # Examples |
1a4d82fc | 1019 | /// |
a2a8927a | 1020 | /// Basic usage: |
1a4d82fc | 1021 | /// |
a2a8927a XL |
1022 | /// ```should_panic |
1023 | /// let x: Result<u32, &str> = Err("emergency failure"); | |
1024 | /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure` | |
1a4d82fc JJ |
1025 | /// ``` |
1026 | #[inline] | |
a2a8927a XL |
1027 | #[track_caller] |
1028 | #[stable(feature = "result_expect", since = "1.4.0")] | |
1029 | pub fn expect(self, msg: &str) -> T | |
1030 | where | |
1031 | E: fmt::Debug, | |
1032 | { | |
1a4d82fc | 1033 | match self { |
a2a8927a XL |
1034 | Ok(t) => t, |
1035 | Err(e) => unwrap_failed(msg, &e), | |
1a4d82fc JJ |
1036 | } |
1037 | } | |
1038 | ||
a2a8927a | 1039 | /// Returns the contained [`Ok`] value, consuming the `self` value. |
3b2f2976 | 1040 | /// |
a2a8927a XL |
1041 | /// Because this function may panic, its use is generally discouraged. |
1042 | /// Instead, prefer to use pattern matching and handle the [`Err`] | |
1043 | /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or | |
1044 | /// [`unwrap_or_default`]. | |
1045 | /// | |
1046 | /// [`unwrap_or`]: Result::unwrap_or | |
1047 | /// [`unwrap_or_else`]: Result::unwrap_or_else | |
1048 | /// [`unwrap_or_default`]: Result::unwrap_or_default | |
1049 | /// | |
1050 | /// # Panics | |
1051 | /// | |
1052 | /// Panics if the value is an [`Err`], with a panic message provided by the | |
1053 | /// [`Err`]'s value. | |
1a4d82fc | 1054 | /// |
1a4d82fc | 1055 | /// |
c34b1796 | 1056 | /// # Examples |
1a4d82fc | 1057 | /// |
a7813a04 XL |
1058 | /// Basic usage: |
1059 | /// | |
1a4d82fc | 1060 | /// ``` |
a2a8927a XL |
1061 | /// let x: Result<u32, &str> = Ok(2); |
1062 | /// assert_eq!(x.unwrap(), 2); | |
1063 | /// ``` | |
1a4d82fc | 1064 | /// |
a2a8927a XL |
1065 | /// ```should_panic |
1066 | /// let x: Result<u32, &str> = Err("emergency failure"); | |
1067 | /// x.unwrap(); // panics with `emergency failure` | |
1a4d82fc JJ |
1068 | /// ``` |
1069 | #[inline] | |
a2a8927a | 1070 | #[track_caller] |
85aaf69f | 1071 | #[stable(feature = "rust1", since = "1.0.0")] |
a2a8927a XL |
1072 | pub fn unwrap(self) -> T |
1073 | where | |
1074 | E: fmt::Debug, | |
1075 | { | |
1a4d82fc | 1076 | match self { |
a2a8927a XL |
1077 | Ok(t) => t, |
1078 | Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e), | |
1a4d82fc JJ |
1079 | } |
1080 | } | |
1081 | ||
a2a8927a | 1082 | /// Returns the contained [`Ok`] value or a default |
ff7c6d11 | 1083 | /// |
a2a8927a XL |
1084 | /// Consumes the `self` argument then, if [`Ok`], returns the contained |
1085 | /// value, otherwise if [`Err`], returns the default value for that | |
1086 | /// type. | |
1a4d82fc | 1087 | /// |
c34b1796 | 1088 | /// # Examples |
1a4d82fc | 1089 | /// |
a2a8927a XL |
1090 | /// Converts a string to an integer, turning poorly-formed strings |
1091 | /// into 0 (the default value for integers). [`parse`] converts | |
1092 | /// a string to any other type that implements [`FromStr`], returning an | |
1093 | /// [`Err`] on error. | |
a7813a04 | 1094 | /// |
1a4d82fc | 1095 | /// ``` |
a2a8927a XL |
1096 | /// let good_year_from_input = "1909"; |
1097 | /// let bad_year_from_input = "190blarg"; | |
1098 | /// let good_year = good_year_from_input.parse().unwrap_or_default(); | |
1099 | /// let bad_year = bad_year_from_input.parse().unwrap_or_default(); | |
1a4d82fc | 1100 | /// |
a2a8927a XL |
1101 | /// assert_eq!(1909, good_year); |
1102 | /// assert_eq!(0, bad_year); | |
1a4d82fc | 1103 | /// ``` |
a2a8927a XL |
1104 | /// |
1105 | /// [`parse`]: str::parse | |
1106 | /// [`FromStr`]: crate::str::FromStr | |
1a4d82fc | 1107 | #[inline] |
a2a8927a XL |
1108 | #[stable(feature = "result_unwrap_or_default", since = "1.16.0")] |
1109 | pub fn unwrap_or_default(self) -> T | |
1110 | where | |
1111 | T: Default, | |
1112 | { | |
1a4d82fc | 1113 | match self { |
a2a8927a XL |
1114 | Ok(x) => x, |
1115 | Err(_) => Default::default(), | |
1a4d82fc JJ |
1116 | } |
1117 | } | |
1118 | ||
a2a8927a | 1119 | /// Returns the contained [`Err`] value, consuming the `self` value. |
1a4d82fc | 1120 | /// |
a2a8927a XL |
1121 | /// # Panics |
1122 | /// | |
1123 | /// Panics if the value is an [`Ok`], with a panic message including the | |
1124 | /// passed message, and the content of the [`Ok`]. | |
1a4d82fc | 1125 | /// |
3b2f2976 | 1126 | /// |
c34b1796 | 1127 | /// # Examples |
1a4d82fc | 1128 | /// |
a7813a04 XL |
1129 | /// Basic usage: |
1130 | /// | |
a2a8927a XL |
1131 | /// ```should_panic |
1132 | /// let x: Result<u32, &str> = Ok(10); | |
1133 | /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` | |
1a4d82fc JJ |
1134 | /// ``` |
1135 | #[inline] | |
a2a8927a XL |
1136 | #[track_caller] |
1137 | #[stable(feature = "result_expect_err", since = "1.17.0")] | |
1138 | pub fn expect_err(self, msg: &str) -> E | |
1139 | where | |
1140 | T: fmt::Debug, | |
1141 | { | |
1a4d82fc | 1142 | match self { |
a2a8927a XL |
1143 | Ok(t) => unwrap_failed(msg, &t), |
1144 | Err(e) => e, | |
1a4d82fc JJ |
1145 | } |
1146 | } | |
1147 | ||
a2a8927a | 1148 | /// Returns the contained [`Err`] value, consuming the `self` value. |
1a4d82fc | 1149 | /// |
a2a8927a | 1150 | /// # Panics |
ff7c6d11 | 1151 | /// |
a2a8927a XL |
1152 | /// Panics if the value is an [`Ok`], with a custom panic message provided |
1153 | /// by the [`Ok`]'s value. | |
3b2f2976 | 1154 | /// |
c34b1796 | 1155 | /// # Examples |
1a4d82fc | 1156 | /// |
a2a8927a XL |
1157 | /// ```should_panic |
1158 | /// let x: Result<u32, &str> = Ok(2); | |
1159 | /// x.unwrap_err(); // panics with `2` | |
1a4d82fc | 1160 | /// ``` |
1a4d82fc | 1161 | /// |
a2a8927a XL |
1162 | /// ``` |
1163 | /// let x: Result<u32, &str> = Err("emergency failure"); | |
1164 | /// assert_eq!(x.unwrap_err(), "emergency failure"); | |
1a4d82fc JJ |
1165 | /// ``` |
1166 | #[inline] | |
a2a8927a | 1167 | #[track_caller] |
85aaf69f | 1168 | #[stable(feature = "rust1", since = "1.0.0")] |
a2a8927a XL |
1169 | pub fn unwrap_err(self) -> E |
1170 | where | |
1171 | T: fmt::Debug, | |
1172 | { | |
1a4d82fc | 1173 | match self { |
a2a8927a XL |
1174 | Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t), |
1175 | Err(e) => e, | |
1a4d82fc JJ |
1176 | } |
1177 | } | |
1178 | ||
a2a8927a XL |
1179 | /// Returns the contained [`Ok`] value, but never panics. |
1180 | /// | |
1181 | /// Unlike [`unwrap`], this method is known to never panic on the | |
1182 | /// result types it is implemented for. Therefore, it can be used | |
1183 | /// instead of `unwrap` as a maintainability safeguard that will fail | |
1184 | /// to compile if the error type of the `Result` is later changed | |
1185 | /// to an error that can actually occur. | |
3b2f2976 | 1186 | /// |
a2a8927a | 1187 | /// [`unwrap`]: Result::unwrap |
1a4d82fc | 1188 | /// |
c34b1796 | 1189 | /// # Examples |
1a4d82fc | 1190 | /// |
a7813a04 XL |
1191 | /// Basic usage: |
1192 | /// | |
1a4d82fc | 1193 | /// ``` |
a2a8927a XL |
1194 | /// # #![feature(never_type)] |
1195 | /// # #![feature(unwrap_infallible)] | |
1a4d82fc | 1196 | /// |
a2a8927a XL |
1197 | /// fn only_good_news() -> Result<String, !> { |
1198 | /// Ok("this is fine".into()) | |
1199 | /// } | |
1200 | /// | |
1201 | /// let s: String = only_good_news().into_ok(); | |
5e7ed085 | 1202 | /// println!("{s}"); |
1a4d82fc | 1203 | /// ``` |
a2a8927a | 1204 | #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")] |
1a4d82fc | 1205 | #[inline] |
a2a8927a XL |
1206 | pub fn into_ok(self) -> T |
1207 | where | |
1208 | E: Into<!>, | |
1209 | { | |
1a4d82fc | 1210 | match self { |
a2a8927a XL |
1211 | Ok(x) => x, |
1212 | Err(e) => e.into(), | |
1a4d82fc JJ |
1213 | } |
1214 | } | |
5869c6ff | 1215 | |
a2a8927a | 1216 | /// Returns the contained [`Err`] value, but never panics. |
5869c6ff | 1217 | /// |
a2a8927a XL |
1218 | /// Unlike [`unwrap_err`], this method is known to never panic on the |
1219 | /// result types it is implemented for. Therefore, it can be used | |
1220 | /// instead of `unwrap_err` as a maintainability safeguard that will fail | |
1221 | /// to compile if the ok type of the `Result` is later changed | |
1222 | /// to a type that can actually occur. | |
5869c6ff | 1223 | /// |
a2a8927a | 1224 | /// [`unwrap_err`]: Result::unwrap_err |
5869c6ff XL |
1225 | /// |
1226 | /// # Examples | |
1227 | /// | |
a2a8927a XL |
1228 | /// Basic usage: |
1229 | /// | |
5869c6ff | 1230 | /// ``` |
a2a8927a XL |
1231 | /// # #![feature(never_type)] |
1232 | /// # #![feature(unwrap_infallible)] | |
5869c6ff | 1233 | /// |
a2a8927a XL |
1234 | /// fn only_bad_news() -> Result<!, String> { |
1235 | /// Err("Oops, it failed".into()) | |
1236 | /// } | |
1237 | /// | |
1238 | /// let error: String = only_bad_news().into_err(); | |
5e7ed085 | 1239 | /// println!("{error}"); |
5869c6ff | 1240 | /// ``` |
a2a8927a | 1241 | #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")] |
5869c6ff | 1242 | #[inline] |
a2a8927a XL |
1243 | pub fn into_err(self) -> E |
1244 | where | |
1245 | T: Into<!>, | |
1246 | { | |
5869c6ff | 1247 | match self { |
a2a8927a XL |
1248 | Ok(x) => x.into(), |
1249 | Err(e) => e, | |
5869c6ff XL |
1250 | } |
1251 | } | |
1252 | ||
a2a8927a XL |
1253 | //////////////////////////////////////////////////////////////////////// |
1254 | // Boolean operations on the values, eager and lazy | |
1255 | ///////////////////////////////////////////////////////////////////////// | |
1256 | ||
1257 | /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`. | |
5869c6ff | 1258 | /// |
5869c6ff XL |
1259 | /// |
1260 | /// # Examples | |
1261 | /// | |
a2a8927a | 1262 | /// Basic usage: |
5869c6ff XL |
1263 | /// |
1264 | /// ``` | |
a2a8927a XL |
1265 | /// let x: Result<u32, &str> = Ok(2); |
1266 | /// let y: Result<&str, &str> = Err("late error"); | |
1267 | /// assert_eq!(x.and(y), Err("late error")); | |
1268 | /// | |
1269 | /// let x: Result<u32, &str> = Err("early error"); | |
1270 | /// let y: Result<&str, &str> = Ok("foo"); | |
1271 | /// assert_eq!(x.and(y), Err("early error")); | |
1272 | /// | |
1273 | /// let x: Result<u32, &str> = Err("not a 2"); | |
1274 | /// let y: Result<&str, &str> = Err("late error"); | |
1275 | /// assert_eq!(x.and(y), Err("not a 2")); | |
1276 | /// | |
1277 | /// let x: Result<u32, &str> = Ok(2); | |
1278 | /// let y: Result<&str, &str> = Ok("different result type"); | |
1279 | /// assert_eq!(x.and(y), Ok("different result type")); | |
5869c6ff XL |
1280 | /// ``` |
1281 | #[inline] | |
5e7ed085 | 1282 | #[rustc_const_unstable(feature = "const_result_drop", issue = "92384")] |
a2a8927a | 1283 | #[stable(feature = "rust1", since = "1.0.0")] |
5e7ed085 FG |
1284 | pub const fn and<U>(self, res: Result<U, E>) -> Result<U, E> |
1285 | where | |
04454e1e FG |
1286 | T: ~const Destruct, |
1287 | U: ~const Destruct, | |
1288 | E: ~const Destruct, | |
5e7ed085 | 1289 | { |
5869c6ff | 1290 | match self { |
5e7ed085 FG |
1291 | // FIXME: ~const Drop doesn't quite work right yet |
1292 | #[allow(unused_variables)] | |
1293 | Ok(x) => res, | |
a2a8927a | 1294 | Err(e) => Err(e), |
5869c6ff XL |
1295 | } |
1296 | } | |
1a4d82fc | 1297 | |
a2a8927a | 1298 | /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`. |
e1599b0c | 1299 | /// |
e1599b0c | 1300 | /// |
a2a8927a | 1301 | /// This function can be used for control flow based on `Result` values. |
e1599b0c XL |
1302 | /// |
1303 | /// # Examples | |
1304 | /// | |
5099ac24 FG |
1305 | /// ``` |
1306 | /// fn sq_then_to_string(x: u32) -> Result<String, &'static str> { | |
1307 | /// x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed") | |
1308 | /// } | |
a2a8927a | 1309 | /// |
5099ac24 FG |
1310 | /// assert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string())); |
1311 | /// assert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err("overflowed")); | |
1312 | /// assert_eq!(Err("not a number").and_then(sq_then_to_string), Err("not a number")); | |
e1599b0c | 1313 | /// ``` |
a2a8927a | 1314 | /// |
5099ac24 FG |
1315 | /// Often used to chain fallible operations that may return [`Err`]. |
1316 | /// | |
1317 | /// ``` | |
1318 | /// use std::{io::ErrorKind, path::Path}; | |
1319 | /// | |
1320 | /// // Note: on Windows "/" maps to "C:\" | |
1321 | /// let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); | |
1322 | /// assert!(root_modified_time.is_ok()); | |
1323 | /// | |
1324 | /// let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); | |
1325 | /// assert!(should_fail.is_err()); | |
1326 | /// assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); | |
e1599b0c | 1327 | /// ``` |
a2a8927a XL |
1328 | #[inline] |
1329 | #[stable(feature = "rust1", since = "1.0.0")] | |
1330 | pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> { | |
1331 | match self { | |
1332 | Ok(t) => op(t), | |
1333 | Err(e) => Err(e), | |
1334 | } | |
e1599b0c | 1335 | } |
e1599b0c | 1336 | |
a2a8927a | 1337 | /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`. |
e1599b0c | 1338 | /// |
a2a8927a XL |
1339 | /// Arguments passed to `or` are eagerly evaluated; if you are passing the |
1340 | /// result of a function call, it is recommended to use [`or_else`], which is | |
1341 | /// lazily evaluated. | |
e1599b0c | 1342 | /// |
a2a8927a | 1343 | /// [`or_else`]: Result::or_else |
e1599b0c XL |
1344 | /// |
1345 | /// # Examples | |
1346 | /// | |
a2a8927a XL |
1347 | /// Basic usage: |
1348 | /// | |
e1599b0c | 1349 | /// ``` |
a2a8927a XL |
1350 | /// let x: Result<u32, &str> = Ok(2); |
1351 | /// let y: Result<u32, &str> = Err("late error"); | |
1352 | /// assert_eq!(x.or(y), Ok(2)); | |
1353 | /// | |
1354 | /// let x: Result<u32, &str> = Err("early error"); | |
1355 | /// let y: Result<u32, &str> = Ok(2); | |
1356 | /// assert_eq!(x.or(y), Ok(2)); | |
1357 | /// | |
1358 | /// let x: Result<u32, &str> = Err("not a 2"); | |
1359 | /// let y: Result<u32, &str> = Err("late error"); | |
1360 | /// assert_eq!(x.or(y), Err("late error")); | |
1361 | /// | |
1362 | /// let x: Result<u32, &str> = Ok(2); | |
1363 | /// let y: Result<u32, &str> = Ok(100); | |
1364 | /// assert_eq!(x.or(y), Ok(2)); | |
e1599b0c | 1365 | /// ``` |
a2a8927a | 1366 | #[inline] |
5e7ed085 | 1367 | #[rustc_const_unstable(feature = "const_result_drop", issue = "92384")] |
a2a8927a | 1368 | #[stable(feature = "rust1", since = "1.0.0")] |
5e7ed085 FG |
1369 | pub const fn or<F>(self, res: Result<T, F>) -> Result<T, F> |
1370 | where | |
04454e1e FG |
1371 | T: ~const Destruct, |
1372 | E: ~const Destruct, | |
1373 | F: ~const Destruct, | |
5e7ed085 | 1374 | { |
a2a8927a XL |
1375 | match self { |
1376 | Ok(v) => Ok(v), | |
5e7ed085 FG |
1377 | // FIXME: ~const Drop doesn't quite work right yet |
1378 | #[allow(unused_variables)] | |
1379 | Err(e) => res, | |
a2a8927a | 1380 | } |
e1599b0c | 1381 | } |
e1599b0c | 1382 | |
a2a8927a | 1383 | /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`. |
74b04a01 | 1384 | /// |
a2a8927a | 1385 | /// This function can be used for control flow based on result values. |
74b04a01 | 1386 | /// |
74b04a01 XL |
1387 | /// |
1388 | /// # Examples | |
1389 | /// | |
1390 | /// Basic usage: | |
1391 | /// | |
a2a8927a XL |
1392 | /// ``` |
1393 | /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) } | |
1394 | /// fn err(x: u32) -> Result<u32, u32> { Err(x) } | |
1395 | /// | |
1396 | /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2)); | |
1397 | /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2)); | |
1398 | /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9)); | |
1399 | /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3)); | |
74b04a01 XL |
1400 | /// ``` |
1401 | #[inline] | |
a2a8927a XL |
1402 | #[stable(feature = "rust1", since = "1.0.0")] |
1403 | pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> { | |
74b04a01 | 1404 | match self { |
a2a8927a XL |
1405 | Ok(t) => Ok(t), |
1406 | Err(e) => op(e), | |
74b04a01 XL |
1407 | } |
1408 | } | |
1409 | ||
a2a8927a | 1410 | /// Returns the contained [`Ok`] value or a provided default. |
74b04a01 | 1411 | /// |
a2a8927a XL |
1412 | /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing |
1413 | /// the result of a function call, it is recommended to use [`unwrap_or_else`], | |
1414 | /// which is lazily evaluated. | |
74b04a01 | 1415 | /// |
3dfed10e | 1416 | /// [`unwrap_or_else`]: Result::unwrap_or_else |
1a4d82fc | 1417 | /// |
a2a8927a | 1418 | /// # Examples |
1a4d82fc | 1419 | /// |
a2a8927a XL |
1420 | /// Basic usage: |
1421 | /// | |
1422 | /// ``` | |
1423 | /// let default = 2; | |
1424 | /// let x: Result<u32, &str> = Ok(9); | |
1425 | /// assert_eq!(x.unwrap_or(default), 9); | |
1426 | /// | |
1427 | /// let x: Result<u32, &str> = Err("error"); | |
1428 | /// assert_eq!(x.unwrap_or(default), default); | |
1429 | /// ``` | |
1430 | #[inline] | |
5e7ed085 | 1431 | #[rustc_const_unstable(feature = "const_result_drop", issue = "92384")] |
a2a8927a | 1432 | #[stable(feature = "rust1", since = "1.0.0")] |
5e7ed085 FG |
1433 | pub const fn unwrap_or(self, default: T) -> T |
1434 | where | |
04454e1e FG |
1435 | T: ~const Destruct, |
1436 | E: ~const Destruct, | |
5e7ed085 | 1437 | { |
a2a8927a XL |
1438 | match self { |
1439 | Ok(t) => t, | |
5e7ed085 FG |
1440 | // FIXME: ~const Drop doesn't quite work right yet |
1441 | #[allow(unused_variables)] | |
1442 | Err(e) => default, | |
a2a8927a XL |
1443 | } |
1444 | } | |
1445 | ||
1446 | /// Returns the contained [`Ok`] value or computes it from a closure. | |
3b2f2976 | 1447 | /// |
1a4d82fc | 1448 | /// |
c34b1796 | 1449 | /// # Examples |
1a4d82fc | 1450 | /// |
a7813a04 XL |
1451 | /// Basic usage: |
1452 | /// | |
1a4d82fc | 1453 | /// ``` |
a2a8927a | 1454 | /// fn count(x: &str) -> usize { x.len() } |
1a4d82fc | 1455 | /// |
a2a8927a XL |
1456 | /// assert_eq!(Ok(2).unwrap_or_else(count), 2); |
1457 | /// assert_eq!(Err("foo").unwrap_or_else(count), 3); | |
1a4d82fc JJ |
1458 | /// ``` |
1459 | #[inline] | |
85aaf69f | 1460 | #[stable(feature = "rust1", since = "1.0.0")] |
a2a8927a | 1461 | pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T { |
1a4d82fc JJ |
1462 | match self { |
1463 | Ok(t) => t, | |
a2a8927a | 1464 | Err(e) => op(e), |
1a4d82fc JJ |
1465 | } |
1466 | } | |
62682a34 | 1467 | |
a2a8927a XL |
1468 | /// Returns the contained [`Ok`] value, consuming the `self` value, |
1469 | /// without checking that the value is not an [`Err`]. | |
62682a34 | 1470 | /// |
a2a8927a | 1471 | /// # Safety |
9cc50fc6 | 1472 | /// |
a2a8927a | 1473 | /// Calling this method on an [`Err`] is *[undefined behavior]*. |
3b2f2976 | 1474 | /// |
a2a8927a | 1475 | /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html |
62682a34 SL |
1476 | /// |
1477 | /// # Examples | |
a7813a04 | 1478 | /// |
a2a8927a XL |
1479 | /// ``` |
1480 | /// let x: Result<u32, &str> = Ok(2); | |
1481 | /// assert_eq!(unsafe { x.unwrap_unchecked() }, 2); | |
1482 | /// ``` | |
a7813a04 | 1483 | /// |
a2a8927a XL |
1484 | /// ```no_run |
1485 | /// let x: Result<u32, &str> = Err("emergency failure"); | |
1486 | /// unsafe { x.unwrap_unchecked(); } // Undefined behavior! | |
62682a34 SL |
1487 | /// ``` |
1488 | #[inline] | |
dfeec247 | 1489 | #[track_caller] |
a2a8927a XL |
1490 | #[stable(feature = "option_result_unwrap_unchecked", since = "1.58.0")] |
1491 | pub unsafe fn unwrap_unchecked(self) -> T { | |
1492 | debug_assert!(self.is_ok()); | |
62682a34 | 1493 | match self { |
a2a8927a XL |
1494 | Ok(t) => t, |
1495 | // SAFETY: the safety contract must be upheld by the caller. | |
1496 | Err(_) => unsafe { hint::unreachable_unchecked() }, | |
62682a34 SL |
1497 | } |
1498 | } | |
1a4d82fc | 1499 | |
a2a8927a XL |
1500 | /// Returns the contained [`Err`] value, consuming the `self` value, |
1501 | /// without checking that the value is not an [`Ok`]. | |
1a4d82fc | 1502 | /// |
a2a8927a | 1503 | /// # Safety |
1a4d82fc | 1504 | /// |
a2a8927a XL |
1505 | /// Calling this method on an [`Ok`] is *[undefined behavior]*. |
1506 | /// | |
1507 | /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html | |
3b2f2976 | 1508 | /// |
c34b1796 | 1509 | /// # Examples |
1a4d82fc | 1510 | /// |
a2a8927a | 1511 | /// ```no_run |
85aaf69f | 1512 | /// let x: Result<u32, &str> = Ok(2); |
a2a8927a | 1513 | /// unsafe { x.unwrap_err_unchecked() }; // Undefined behavior! |
1a4d82fc JJ |
1514 | /// ``` |
1515 | /// | |
1516 | /// ``` | |
85aaf69f | 1517 | /// let x: Result<u32, &str> = Err("emergency failure"); |
a2a8927a | 1518 | /// assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure"); |
1a4d82fc JJ |
1519 | /// ``` |
1520 | #[inline] | |
dfeec247 | 1521 | #[track_caller] |
a2a8927a XL |
1522 | #[stable(feature = "option_result_unwrap_unchecked", since = "1.58.0")] |
1523 | pub unsafe fn unwrap_err_unchecked(self) -> E { | |
1524 | debug_assert!(self.is_err()); | |
1a4d82fc | 1525 | match self { |
a2a8927a XL |
1526 | // SAFETY: the safety contract must be upheld by the caller. |
1527 | Ok(_) => unsafe { hint::unreachable_unchecked() }, | |
7453a54e | 1528 | Err(e) => e, |
1a4d82fc JJ |
1529 | } |
1530 | } | |
1a4d82fc | 1531 | |
a2a8927a XL |
1532 | ///////////////////////////////////////////////////////////////////////// |
1533 | // Misc or niche | |
1534 | ///////////////////////////////////////////////////////////////////////// | |
1535 | ||
1536 | /// Returns `true` if the result is an [`Ok`] value containing the given value. | |
c30ab7b3 SL |
1537 | /// |
1538 | /// # Examples | |
1539 | /// | |
c30ab7b3 | 1540 | /// ``` |
a2a8927a | 1541 | /// #![feature(option_result_contains)] |
c30ab7b3 | 1542 | /// |
a2a8927a XL |
1543 | /// let x: Result<u32, &str> = Ok(2); |
1544 | /// assert_eq!(x.contains(&2), true); | |
c30ab7b3 | 1545 | /// |
a2a8927a XL |
1546 | /// let x: Result<u32, &str> = Ok(3); |
1547 | /// assert_eq!(x.contains(&2), false); | |
1548 | /// | |
1549 | /// let x: Result<u32, &str> = Err("Some error message"); | |
1550 | /// assert_eq!(x.contains(&2), false); | |
1551 | /// ``` | |
1552 | #[must_use] | |
c30ab7b3 | 1553 | #[inline] |
a2a8927a XL |
1554 | #[unstable(feature = "option_result_contains", issue = "62358")] |
1555 | pub fn contains<U>(&self, x: &U) -> bool | |
1556 | where | |
1557 | U: PartialEq<T>, | |
1558 | { | |
c30ab7b3 | 1559 | match self { |
a2a8927a XL |
1560 | Ok(y) => x == y, |
1561 | Err(_) => false, | |
2c00a5a8 XL |
1562 | } |
1563 | } | |
2c00a5a8 | 1564 | |
a2a8927a | 1565 | /// Returns `true` if the result is an [`Err`] value containing the given value. |
dfeec247 XL |
1566 | /// |
1567 | /// # Examples | |
1568 | /// | |
dfeec247 | 1569 | /// ``` |
a2a8927a | 1570 | /// #![feature(result_contains_err)] |
dfeec247 | 1571 | /// |
a2a8927a XL |
1572 | /// let x: Result<u32, &str> = Ok(2); |
1573 | /// assert_eq!(x.contains_err(&"Some error message"), false); | |
dfeec247 | 1574 | /// |
a2a8927a XL |
1575 | /// let x: Result<u32, &str> = Err("Some error message"); |
1576 | /// assert_eq!(x.contains_err(&"Some error message"), true); | |
1577 | /// | |
1578 | /// let x: Result<u32, &str> = Err("Some other error message"); | |
1579 | /// assert_eq!(x.contains_err(&"Some error message"), false); | |
dfeec247 | 1580 | /// ``` |
a2a8927a | 1581 | #[must_use] |
dfeec247 | 1582 | #[inline] |
a2a8927a XL |
1583 | #[unstable(feature = "result_contains_err", issue = "62358")] |
1584 | pub fn contains_err<F>(&self, f: &F) -> bool | |
1585 | where | |
1586 | F: PartialEq<E>, | |
1587 | { | |
dfeec247 | 1588 | match self { |
a2a8927a XL |
1589 | Ok(_) => false, |
1590 | Err(e) => f == e, | |
dfeec247 XL |
1591 | } |
1592 | } | |
1593 | } | |
1594 | ||
a2a8927a XL |
1595 | impl<T, E> Result<&T, E> { |
1596 | /// Maps a `Result<&T, E>` to a `Result<T, E>` by copying the contents of the | |
1597 | /// `Ok` part. | |
cdc7bbd5 XL |
1598 | /// |
1599 | /// # Examples | |
1600 | /// | |
cdc7bbd5 | 1601 | /// ``` |
a2a8927a XL |
1602 | /// let val = 12; |
1603 | /// let x: Result<&i32, i32> = Ok(&val); | |
1604 | /// assert_eq!(x, Ok(&12)); | |
1605 | /// let copied = x.copied(); | |
1606 | /// assert_eq!(copied, Ok(12)); | |
1607 | /// ``` | |
1608 | #[inline] | |
1609 | #[stable(feature = "result_copied", since = "1.59.0")] | |
1610 | pub fn copied(self) -> Result<T, E> | |
1611 | where | |
1612 | T: Copy, | |
1613 | { | |
1614 | self.map(|&t| t) | |
1615 | } | |
1616 | ||
1617 | /// Maps a `Result<&T, E>` to a `Result<T, E>` by cloning the contents of the | |
1618 | /// `Ok` part. | |
cdc7bbd5 | 1619 | /// |
a2a8927a | 1620 | /// # Examples |
cdc7bbd5 | 1621 | /// |
a2a8927a XL |
1622 | /// ``` |
1623 | /// let val = 12; | |
1624 | /// let x: Result<&i32, i32> = Ok(&val); | |
1625 | /// assert_eq!(x, Ok(&12)); | |
1626 | /// let cloned = x.cloned(); | |
1627 | /// assert_eq!(cloned, Ok(12)); | |
cdc7bbd5 XL |
1628 | /// ``` |
1629 | #[inline] | |
a2a8927a XL |
1630 | #[stable(feature = "result_cloned", since = "1.59.0")] |
1631 | pub fn cloned(self) -> Result<T, E> | |
1632 | where | |
1633 | T: Clone, | |
1634 | { | |
1635 | self.map(|t| t.clone()) | |
cdc7bbd5 XL |
1636 | } |
1637 | } | |
1638 | ||
a2a8927a XL |
1639 | impl<T, E> Result<&mut T, E> { |
1640 | /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by copying the contents of the | |
1641 | /// `Ok` part. | |
f035d41b XL |
1642 | /// |
1643 | /// # Examples | |
1644 | /// | |
1645 | /// ``` | |
a2a8927a XL |
1646 | /// let mut val = 12; |
1647 | /// let x: Result<&mut i32, i32> = Ok(&mut val); | |
1648 | /// assert_eq!(x, Ok(&mut 12)); | |
1649 | /// let copied = x.copied(); | |
1650 | /// assert_eq!(copied, Ok(12)); | |
f035d41b | 1651 | /// ``` |
a2a8927a XL |
1652 | #[inline] |
1653 | #[stable(feature = "result_copied", since = "1.59.0")] | |
1654 | pub fn copied(self) -> Result<T, E> | |
1655 | where | |
1656 | T: Copy, | |
1657 | { | |
1658 | self.map(|&mut t| t) | |
b7449926 | 1659 | } |
b7449926 | 1660 | |
a2a8927a XL |
1661 | /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by cloning the contents of the |
1662 | /// `Ok` part. | |
f035d41b XL |
1663 | /// |
1664 | /// # Examples | |
1665 | /// | |
1666 | /// ``` | |
a2a8927a XL |
1667 | /// let mut val = 12; |
1668 | /// let x: Result<&mut i32, i32> = Ok(&mut val); | |
1669 | /// assert_eq!(x, Ok(&mut 12)); | |
1670 | /// let cloned = x.cloned(); | |
1671 | /// assert_eq!(cloned, Ok(12)); | |
f035d41b | 1672 | /// ``` |
a2a8927a XL |
1673 | #[inline] |
1674 | #[stable(feature = "result_cloned", since = "1.59.0")] | |
1675 | pub fn cloned(self) -> Result<T, E> | |
1676 | where | |
1677 | T: Clone, | |
1678 | { | |
1679 | self.map(|t| t.clone()) | |
416331ca XL |
1680 | } |
1681 | } | |
1682 | ||
2c00a5a8 XL |
1683 | impl<T, E> Result<Option<T>, E> { |
1684 | /// Transposes a `Result` of an `Option` into an `Option` of a `Result`. | |
1685 | /// | |
1686 | /// `Ok(None)` will be mapped to `None`. | |
1687 | /// `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`. | |
1688 | /// | |
1689 | /// # Examples | |
1690 | /// | |
1691 | /// ``` | |
2c00a5a8 XL |
1692 | /// #[derive(Debug, Eq, PartialEq)] |
1693 | /// struct SomeErr; | |
1694 | /// | |
1695 | /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5)); | |
1696 | /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5)); | |
1697 | /// assert_eq!(x.transpose(), y); | |
1698 | /// ``` | |
1699 | #[inline] | |
0731742a | 1700 | #[stable(feature = "transpose_result", since = "1.33.0")] |
6a06907d XL |
1701 | #[rustc_const_unstable(feature = "const_result", issue = "82814")] |
1702 | pub const fn transpose(self) -> Option<Result<T, E>> { | |
2c00a5a8 XL |
1703 | match self { |
1704 | Ok(Some(x)) => Some(Ok(x)), | |
1705 | Ok(None) => None, | |
1706 | Err(e) => Some(Err(e)), | |
c30ab7b3 SL |
1707 | } |
1708 | } | |
1709 | } | |
1710 | ||
ba9703b0 XL |
1711 | impl<T, E> Result<Result<T, E>, E> { |
1712 | /// Converts from `Result<Result<T, E>, E>` to `Result<T, E>` | |
1713 | /// | |
1714 | /// # Examples | |
fc512014 | 1715 | /// |
ba9703b0 | 1716 | /// Basic usage: |
fc512014 | 1717 | /// |
ba9703b0 XL |
1718 | /// ``` |
1719 | /// #![feature(result_flattening)] | |
1720 | /// let x: Result<Result<&'static str, u32>, u32> = Ok(Ok("hello")); | |
1721 | /// assert_eq!(Ok("hello"), x.flatten()); | |
1722 | /// | |
1723 | /// let x: Result<Result<&'static str, u32>, u32> = Ok(Err(6)); | |
1724 | /// assert_eq!(Err(6), x.flatten()); | |
1725 | /// | |
1726 | /// let x: Result<Result<&'static str, u32>, u32> = Err(6); | |
1727 | /// assert_eq!(Err(6), x.flatten()); | |
1728 | /// ``` | |
1729 | /// | |
fc512014 | 1730 | /// Flattening only removes one level of nesting at a time: |
ba9703b0 XL |
1731 | /// |
1732 | /// ``` | |
1733 | /// #![feature(result_flattening)] | |
1734 | /// let x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok("hello"))); | |
1735 | /// assert_eq!(Ok(Ok("hello")), x.flatten()); | |
1736 | /// assert_eq!(Ok("hello"), x.flatten().flatten()); | |
1737 | /// ``` | |
1738 | #[inline] | |
1739 | #[unstable(feature = "result_flattening", issue = "70142")] | |
1740 | pub fn flatten(self) -> Result<T, E> { | |
1741 | self.and_then(convert::identity) | |
1742 | } | |
1743 | } | |
1744 | ||
6a06907d XL |
1745 | impl<T> Result<T, T> { |
1746 | /// Returns the [`Ok`] value if `self` is `Ok`, and the [`Err`] value if | |
1747 | /// `self` is `Err`. | |
1748 | /// | |
1749 | /// In other words, this function returns the value (the `T`) of a | |
1750 | /// `Result<T, T>`, regardless of whether or not that result is `Ok` or | |
1751 | /// `Err`. | |
1752 | /// | |
1753 | /// This can be useful in conjunction with APIs such as | |
1754 | /// [`Atomic*::compare_exchange`], or [`slice::binary_search`], but only in | |
1755 | /// cases where you don't care if the result was `Ok` or not. | |
1756 | /// | |
1757 | /// [`Atomic*::compare_exchange`]: crate::sync::atomic::AtomicBool::compare_exchange | |
1758 | /// | |
1759 | /// # Examples | |
1760 | /// | |
1761 | /// ``` | |
1762 | /// #![feature(result_into_ok_or_err)] | |
1763 | /// let ok: Result<u32, u32> = Ok(3); | |
1764 | /// let err: Result<u32, u32> = Err(4); | |
1765 | /// | |
1766 | /// assert_eq!(ok.into_ok_or_err(), 3); | |
1767 | /// assert_eq!(err.into_ok_or_err(), 4); | |
1768 | /// ``` | |
1769 | #[inline] | |
1770 | #[unstable(feature = "result_into_ok_or_err", reason = "newly added", issue = "82223")] | |
1771 | pub const fn into_ok_or_err(self) -> T { | |
1772 | match self { | |
1773 | Ok(v) => v, | |
1774 | Err(v) => v, | |
1775 | } | |
1776 | } | |
1777 | } | |
1778 | ||
7453a54e | 1779 | // This is a separate function to reduce the code size of the methods |
a2a8927a | 1780 | #[cfg(not(feature = "panic_immediate_abort"))] |
7453a54e SL |
1781 | #[inline(never)] |
1782 | #[cold] | |
dfeec247 | 1783 | #[track_caller] |
416331ca | 1784 | fn unwrap_failed(msg: &str, error: &dyn fmt::Debug) -> ! { |
5e7ed085 | 1785 | panic!("{msg}: {error:?}") |
7453a54e SL |
1786 | } |
1787 | ||
a2a8927a XL |
1788 | // This is a separate function to avoid constructing a `dyn Debug` |
1789 | // that gets immediately thrown away, since vtables don't get cleaned up | |
1790 | // by dead code elimination if a trait object is constructed even if it goes | |
1791 | // unused | |
1792 | #[cfg(feature = "panic_immediate_abort")] | |
1793 | #[inline] | |
1794 | #[cold] | |
1795 | #[track_caller] | |
1796 | fn unwrap_failed<T>(_msg: &str, _error: &T) -> ! { | |
1797 | panic!() | |
1798 | } | |
1799 | ||
1a4d82fc JJ |
1800 | ///////////////////////////////////////////////////////////////////////////// |
1801 | // Trait implementations | |
1802 | ///////////////////////////////////////////////////////////////////////////// | |
1803 | ||
dc9dc135 | 1804 | #[stable(feature = "rust1", since = "1.0.0")] |
5e7ed085 | 1805 | #[rustc_const_unstable(feature = "const_clone", issue = "91805")] |
5e7ed085 FG |
1806 | impl<T, E> const Clone for Result<T, E> |
1807 | where | |
04454e1e FG |
1808 | T: ~const Clone + ~const Destruct, |
1809 | E: ~const Clone + ~const Destruct, | |
5e7ed085 | 1810 | { |
dc9dc135 XL |
1811 | #[inline] |
1812 | fn clone(&self) -> Self { | |
1813 | match self { | |
1814 | Ok(x) => Ok(x.clone()), | |
1815 | Err(x) => Err(x.clone()), | |
1816 | } | |
1817 | } | |
1818 | ||
1819 | #[inline] | |
1820 | fn clone_from(&mut self, source: &Self) { | |
1821 | match (self, source) { | |
1822 | (Ok(to), Ok(from)) => to.clone_from(from), | |
1823 | (Err(to), Err(from)) => to.clone_from(from), | |
1824 | (to, from) => *to = from.clone(), | |
1825 | } | |
1826 | } | |
1827 | } | |
1828 | ||
9346a6ac AL |
1829 | #[stable(feature = "rust1", since = "1.0.0")] |
1830 | impl<T, E> IntoIterator for Result<T, E> { | |
1831 | type Item = T; | |
1832 | type IntoIter = IntoIter<T>; | |
1833 | ||
1834 | /// Returns a consuming iterator over the possibly contained value. | |
1835 | /// | |
b7449926 | 1836 | /// The iterator yields one value if the result is [`Result::Ok`], otherwise none. |
32a655c1 | 1837 | /// |
9346a6ac AL |
1838 | /// # Examples |
1839 | /// | |
a7813a04 XL |
1840 | /// Basic usage: |
1841 | /// | |
9346a6ac AL |
1842 | /// ``` |
1843 | /// let x: Result<u32, &str> = Ok(5); | |
1844 | /// let v: Vec<u32> = x.into_iter().collect(); | |
1845 | /// assert_eq!(v, [5]); | |
1846 | /// | |
1847 | /// let x: Result<u32, &str> = Err("nothing!"); | |
1848 | /// let v: Vec<u32> = x.into_iter().collect(); | |
1849 | /// assert_eq!(v, []); | |
1850 | /// ``` | |
1a4d82fc | 1851 | #[inline] |
9346a6ac AL |
1852 | fn into_iter(self) -> IntoIter<T> { |
1853 | IntoIter { inner: self.ok() } | |
1a4d82fc JJ |
1854 | } |
1855 | } | |
1856 | ||
e9174d1e SL |
1857 | #[stable(since = "1.4.0", feature = "result_iter")] |
1858 | impl<'a, T, E> IntoIterator for &'a Result<T, E> { | |
1859 | type Item = &'a T; | |
1860 | type IntoIter = Iter<'a, T>; | |
1861 | ||
1862 | fn into_iter(self) -> Iter<'a, T> { | |
1863 | self.iter() | |
1864 | } | |
1865 | } | |
1866 | ||
1867 | #[stable(since = "1.4.0", feature = "result_iter")] | |
1868 | impl<'a, T, E> IntoIterator for &'a mut Result<T, E> { | |
1869 | type Item = &'a mut T; | |
1870 | type IntoIter = IterMut<'a, T>; | |
1871 | ||
3b2f2976 | 1872 | fn into_iter(self) -> IterMut<'a, T> { |
e9174d1e SL |
1873 | self.iter_mut() |
1874 | } | |
1875 | } | |
1876 | ||
1a4d82fc JJ |
1877 | ///////////////////////////////////////////////////////////////////////////// |
1878 | // The Result Iterators | |
1879 | ///////////////////////////////////////////////////////////////////////////// | |
1880 | ||
9e0c209e SL |
1881 | /// An iterator over a reference to the [`Ok`] variant of a [`Result`]. |
1882 | /// | |
32a655c1 SL |
1883 | /// The iterator yields one value if the result is [`Ok`], otherwise none. |
1884 | /// | |
1885 | /// Created by [`Result::iter`]. | |
54a0048b | 1886 | #[derive(Debug)] |
85aaf69f | 1887 | #[stable(feature = "rust1", since = "1.0.0")] |
dfeec247 XL |
1888 | pub struct Iter<'a, T: 'a> { |
1889 | inner: Option<&'a T>, | |
1890 | } | |
1a4d82fc | 1891 | |
85aaf69f | 1892 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1893 | impl<'a, T> Iterator for Iter<'a, T> { |
1894 | type Item = &'a T; | |
1895 | ||
1896 | #[inline] | |
dfeec247 XL |
1897 | fn next(&mut self) -> Option<&'a T> { |
1898 | self.inner.take() | |
1899 | } | |
1a4d82fc | 1900 | #[inline] |
85aaf69f | 1901 | fn size_hint(&self) -> (usize, Option<usize>) { |
dfeec247 | 1902 | let n = if self.inner.is_some() { 1 } else { 0 }; |
1a4d82fc JJ |
1903 | (n, Some(n)) |
1904 | } | |
1905 | } | |
1906 | ||
85aaf69f | 1907 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1908 | impl<'a, T> DoubleEndedIterator for Iter<'a, T> { |
1909 | #[inline] | |
dfeec247 XL |
1910 | fn next_back(&mut self) -> Option<&'a T> { |
1911 | self.inner.take() | |
1912 | } | |
1a4d82fc JJ |
1913 | } |
1914 | ||
85aaf69f | 1915 | #[stable(feature = "rust1", since = "1.0.0")] |
0bf4aa26 | 1916 | impl<T> ExactSizeIterator for Iter<'_, T> {} |
1a4d82fc | 1917 | |
0531ce1d | 1918 | #[stable(feature = "fused", since = "1.26.0")] |
0bf4aa26 | 1919 | impl<T> FusedIterator for Iter<'_, T> {} |
9e0c209e | 1920 | |
c30ab7b3 | 1921 | #[unstable(feature = "trusted_len", issue = "37572")] |
0bf4aa26 | 1922 | unsafe impl<A> TrustedLen for Iter<'_, A> {} |
c30ab7b3 | 1923 | |
92a42be0 | 1924 | #[stable(feature = "rust1", since = "1.0.0")] |
0bf4aa26 | 1925 | impl<T> Clone for Iter<'_, T> { |
b7449926 | 1926 | #[inline] |
dfeec247 XL |
1927 | fn clone(&self) -> Self { |
1928 | Iter { inner: self.inner } | |
1929 | } | |
1a4d82fc JJ |
1930 | } |
1931 | ||
9e0c209e SL |
1932 | /// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`]. |
1933 | /// | |
32a655c1 | 1934 | /// Created by [`Result::iter_mut`]. |
54a0048b | 1935 | #[derive(Debug)] |
85aaf69f | 1936 | #[stable(feature = "rust1", since = "1.0.0")] |
dfeec247 XL |
1937 | pub struct IterMut<'a, T: 'a> { |
1938 | inner: Option<&'a mut T>, | |
1939 | } | |
1a4d82fc | 1940 | |
85aaf69f | 1941 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1942 | impl<'a, T> Iterator for IterMut<'a, T> { |
1943 | type Item = &'a mut T; | |
1944 | ||
1945 | #[inline] | |
dfeec247 XL |
1946 | fn next(&mut self) -> Option<&'a mut T> { |
1947 | self.inner.take() | |
1948 | } | |
1a4d82fc | 1949 | #[inline] |
85aaf69f | 1950 | fn size_hint(&self) -> (usize, Option<usize>) { |
dfeec247 | 1951 | let n = if self.inner.is_some() { 1 } else { 0 }; |
1a4d82fc JJ |
1952 | (n, Some(n)) |
1953 | } | |
1954 | } | |
1955 | ||
85aaf69f | 1956 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1957 | impl<'a, T> DoubleEndedIterator for IterMut<'a, T> { |
1958 | #[inline] | |
dfeec247 XL |
1959 | fn next_back(&mut self) -> Option<&'a mut T> { |
1960 | self.inner.take() | |
1961 | } | |
1a4d82fc JJ |
1962 | } |
1963 | ||
85aaf69f | 1964 | #[stable(feature = "rust1", since = "1.0.0")] |
0bf4aa26 | 1965 | impl<T> ExactSizeIterator for IterMut<'_, T> {} |
1a4d82fc | 1966 | |
0531ce1d | 1967 | #[stable(feature = "fused", since = "1.26.0")] |
0bf4aa26 | 1968 | impl<T> FusedIterator for IterMut<'_, T> {} |
9e0c209e | 1969 | |
c30ab7b3 | 1970 | #[unstable(feature = "trusted_len", issue = "37572")] |
0bf4aa26 | 1971 | unsafe impl<A> TrustedLen for IterMut<'_, A> {} |
c30ab7b3 | 1972 | |
32a655c1 SL |
1973 | /// An iterator over the value in a [`Ok`] variant of a [`Result`]. |
1974 | /// | |
1975 | /// The iterator yields one value if the result is [`Ok`], otherwise none. | |
1976 | /// | |
1977 | /// This struct is created by the [`into_iter`] method on | |
dfeec247 | 1978 | /// [`Result`] (provided by the [`IntoIterator`] trait). |
9e0c209e | 1979 | /// |
3dfed10e | 1980 | /// [`into_iter`]: IntoIterator::into_iter |
abe05a73 | 1981 | #[derive(Clone, Debug)] |
85aaf69f | 1982 | #[stable(feature = "rust1", since = "1.0.0")] |
dfeec247 XL |
1983 | pub struct IntoIter<T> { |
1984 | inner: Option<T>, | |
1985 | } | |
1a4d82fc | 1986 | |
85aaf69f | 1987 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1988 | impl<T> Iterator for IntoIter<T> { |
1989 | type Item = T; | |
1990 | ||
1991 | #[inline] | |
dfeec247 XL |
1992 | fn next(&mut self) -> Option<T> { |
1993 | self.inner.take() | |
1994 | } | |
1a4d82fc | 1995 | #[inline] |
85aaf69f | 1996 | fn size_hint(&self) -> (usize, Option<usize>) { |
dfeec247 | 1997 | let n = if self.inner.is_some() { 1 } else { 0 }; |
1a4d82fc JJ |
1998 | (n, Some(n)) |
1999 | } | |
2000 | } | |
2001 | ||
85aaf69f | 2002 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
2003 | impl<T> DoubleEndedIterator for IntoIter<T> { |
2004 | #[inline] | |
dfeec247 XL |
2005 | fn next_back(&mut self) -> Option<T> { |
2006 | self.inner.take() | |
2007 | } | |
1a4d82fc JJ |
2008 | } |
2009 | ||
85aaf69f | 2010 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
2011 | impl<T> ExactSizeIterator for IntoIter<T> {} |
2012 | ||
0531ce1d | 2013 | #[stable(feature = "fused", since = "1.26.0")] |
9e0c209e SL |
2014 | impl<T> FusedIterator for IntoIter<T> {} |
2015 | ||
c30ab7b3 SL |
2016 | #[unstable(feature = "trusted_len", issue = "37572")] |
2017 | unsafe impl<A> TrustedLen for IntoIter<A> {} | |
2018 | ||
1a4d82fc JJ |
2019 | ///////////////////////////////////////////////////////////////////////////// |
2020 | // FromIterator | |
2021 | ///////////////////////////////////////////////////////////////////////////// | |
2022 | ||
85aaf69f | 2023 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
2024 | impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> { |
2025 | /// Takes each element in the `Iterator`: if it is an `Err`, no further | |
2026 | /// elements are taken, and the `Err` is returned. Should no `Err` occur, a | |
2027 | /// container with the values of each `Result` is returned. | |
2028 | /// | |
2029 | /// Here is an example which increments every integer in a vector, | |
2030 | /// checking for overflow: | |
2031 | /// | |
c34b1796 | 2032 | /// ``` |
c30ab7b3 | 2033 | /// let v = vec![1, 2]; |
041b39d2 XL |
2034 | /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| |
2035 | /// x.checked_add(1).ok_or("Overflow!") | |
1a4d82fc | 2036 | /// ).collect(); |
532ac7d7 | 2037 | /// assert_eq!(res, Ok(vec![2, 3])); |
1a4d82fc | 2038 | /// ``` |
532ac7d7 XL |
2039 | /// |
2040 | /// Here is another example that tries to subtract one from another list | |
2041 | /// of integers, this time checking for underflow: | |
2042 | /// | |
2043 | /// ``` | |
2044 | /// let v = vec![1, 2, 0]; | |
2045 | /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| | |
2046 | /// x.checked_sub(1).ok_or("Underflow!") | |
2047 | /// ).collect(); | |
2048 | /// assert_eq!(res, Err("Underflow!")); | |
2049 | /// ``` | |
2050 | /// | |
2051 | /// Here is a variation on the previous example, showing that no | |
2052 | /// further elements are taken from `iter` after the first `Err`. | |
2053 | /// | |
2054 | /// ``` | |
2055 | /// let v = vec![3, 2, 1, 10]; | |
2056 | /// let mut shared = 0; | |
2057 | /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| { | |
2058 | /// shared += x; | |
2059 | /// x.checked_sub(2).ok_or("Underflow!") | |
2060 | /// }).collect(); | |
2061 | /// assert_eq!(res, Err("Underflow!")); | |
2062 | /// assert_eq!(shared, 6); | |
2063 | /// ``` | |
2064 | /// | |
2065 | /// Since the third element caused an underflow, no further elements were taken, | |
2066 | /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16. | |
1a4d82fc | 2067 | #[inline] |
dfeec247 | 2068 | fn from_iter<I: IntoIterator<Item = Result<A, E>>>(iter: I) -> Result<V, E> { |
1a4d82fc JJ |
2069 | // FIXME(#11084): This could be replaced with Iterator::scan when this |
2070 | // performance bug is closed. | |
2071 | ||
5099ac24 | 2072 | iter::try_process(iter.into_iter(), |i| i.collect()) |
1a4d82fc JJ |
2073 | } |
2074 | } | |
7cac9316 | 2075 | |
cdc7bbd5 | 2076 | #[unstable(feature = "try_trait_v2", issue = "84277")] |
a2a8927a XL |
2077 | #[rustc_const_unstable(feature = "const_convert", issue = "88674")] |
2078 | impl<T, E> const ops::Try for Result<T, E> { | |
cdc7bbd5 XL |
2079 | type Output = T; |
2080 | type Residual = Result<convert::Infallible, E>; | |
2081 | ||
2082 | #[inline] | |
2083 | fn from_output(output: Self::Output) -> Self { | |
2084 | Ok(output) | |
2085 | } | |
2086 | ||
2087 | #[inline] | |
2088 | fn branch(self) -> ControlFlow<Self::Residual, Self::Output> { | |
2089 | match self { | |
2090 | Ok(v) => ControlFlow::Continue(v), | |
2091 | Err(e) => ControlFlow::Break(Err(e)), | |
2092 | } | |
2093 | } | |
2094 | } | |
2095 | ||
2096 | #[unstable(feature = "try_trait_v2", issue = "84277")] | |
a2a8927a XL |
2097 | #[rustc_const_unstable(feature = "const_convert", issue = "88674")] |
2098 | impl<T, E, F: ~const From<E>> const ops::FromResidual<Result<convert::Infallible, E>> | |
2099 | for Result<T, F> | |
2100 | { | |
cdc7bbd5 | 2101 | #[inline] |
a2a8927a | 2102 | #[track_caller] |
cdc7bbd5 XL |
2103 | fn from_residual(residual: Result<convert::Infallible, E>) -> Self { |
2104 | match residual { | |
2105 | Err(e) => Err(From::from(e)), | |
2106 | } | |
2107 | } | |
2108 | } | |
a2a8927a | 2109 | |
04454e1e FG |
2110 | #[unstable(feature = "try_trait_v2_yeet", issue = "96374")] |
2111 | impl<T, E, F: From<E>> ops::FromResidual<ops::Yeet<E>> for Result<T, F> { | |
2112 | #[inline] | |
2113 | fn from_residual(ops::Yeet(e): ops::Yeet<E>) -> Self { | |
2114 | Err(From::from(e)) | |
2115 | } | |
2116 | } | |
2117 | ||
a2a8927a XL |
2118 | #[unstable(feature = "try_trait_v2_residual", issue = "91285")] |
2119 | impl<T, E> ops::Residual<T> for Result<convert::Infallible, E> { | |
2120 | type TryType = Result<T, E>; | |
2121 | } |