1 //! Optional values.
2 //!
3 //! Type [`Option`] represents an optional value: every [`Option`]
4 //! is either [`Some`] and contains a value, or [`None`], and
5 //! does not. [`Option`] types are very common in Rust code, as
6 //! they have a number of uses:
7 //!
8 //! * Initial values
9 //! * Return values for functions that are not defined
10 //! over their entire input range (partial functions)
11 //! * Return value for otherwise reporting simple errors, where [`None`] is
12 //! returned on error
13 //! * Optional struct fields
14 //! * Struct fields that can be loaned or "taken"
15 //! * Optional function arguments
16 //! * Nullable pointers
17 //! * Swapping things out of difficult situations
18 //!
19 //! [`Option`]s are commonly paired with pattern matching to query the presence
20 //! of a value and take action, always accounting for the [`None`] case.
21 //!
22 //! ```
23 //! fn divide(numerator: f64, denominator: f64) -> Option<f64> {
24 //! if denominator == 0.0 {
25 //! None
26 //! } else {
27 //! Some(numerator / denominator)
28 //! }
29 //! }
30 //!
31 //! // The return value of the function is an option
32 //! let result = divide(2.0, 3.0);
33 //!
34 //! // Pattern match to retrieve the value
35 //! match result {
36 //! // The division was valid
37 //! Some(x) => println!("Result: {x}"),
38 //! // The division was invalid
39 //! None => println!("Cannot divide by 0"),
40 //! }
41 //! ```
42 //!
43 //
44 // FIXME: Show how `Option` is used in practice, with lots of methods
45 //
46 //! # Options and pointers ("nullable" pointers)
47 //!
48 //! Rust's pointer types must always point to a valid location; there are
49 //! no "null" references. Instead, Rust has *optional* pointers, like
50 //! the optional owned box, <code>[Option]<[Box\<T>]></code>.
51 //!
52 //! [Box\<T>]: ../../std/boxed/struct.Box.html
53 //!
54 //! The following example uses [`Option`] to create an optional box of
55 //! [`i32`]. Notice that in order to use the inner [`i32`] value, the
56 //! `check_optional` function first needs to use pattern matching to
57 //! determine whether the box has a value (i.e., it is [`Some(...)`][`Some`]) or
58 //! not ([`None`]).
59 //!
60 //! ```
61 //! let optional = None;
62 //! check_optional(optional);
63 //!
64 //! let optional = Some(Box::new(9000));
65 //! check_optional(optional);
66 //!
67 //! fn check_optional(optional: Option<Box<i32>>) {
68 //! match optional {
69 //! Some(p) => println!("has value {p}"),
70 //! None => println!("has no value"),
71 //! }
72 //! }
73 //! ```
74 //!
75 //! # The question mark operator, `?`
76 //!
77 //! Similar to the [`Result`] type, when writing code that calls many functions that return the
78 //! [`Option`] type, handling `Some`/`None` can be tedious. The question mark
79 //! operator, [`?`], hides some of the boilerplate of propagating values
80 //! up the call stack.
81 //!
82 //! It replaces this:
83 //!
84 //! ```
85 //! # #![allow(dead_code)]
86 //! fn add_last_numbers(stack: &mut Vec<i32>) -> Option<i32> {
87 //! let a = stack.pop();
88 //! let b = stack.pop();
89 //!
90 //! match (a, b) {
91 //! (Some(x), Some(y)) => Some(x + y),
92 //! _ => None,
93 //! }
94 //! }
95 //!
96 //! ```
97 //!
98 //! With this:
99 //!
100 //! ```
101 //! # #![allow(dead_code)]
102 //! fn add_last_numbers(stack: &mut Vec<i32>) -> Option<i32> {
103 //! Some(stack.pop()? + stack.pop()?)
104 //! }
105 //! ```
106 //!
107 //! *It's much nicer!*
108 //!
109 //! Ending the expression with [`?`] will result in the [`Some`]'s unwrapped value, unless the
110 //! result is [`None`], in which case [`None`] is returned early from the enclosing function.
111 //!
112 //! [`?`] can be used in functions that return [`Option`] because of the
113 //! early return of [`None`] that it provides.
114 //!
115 //! [`?`]: crate::ops::Try
116 //! [`Some`]: Some
117 //! [`None`]: None
118 //!
119 //! # Representation
120 //!
121 //! Rust guarantees to optimize the following types `T` such that
122 //! [`Option<T>`] has the same size as `T`:
123 //!
124 //! * [`Box<U>`]
125 //! * `&U`
126 //! * `&mut U`
127 //! * `fn`, `extern "C" fn`[^extern_fn]
128 //! * [`num::NonZero*`]
129 //! * [`ptr::NonNull<U>`]
130 //! * `#[repr(transparent)]` struct around one of the types in this list.
131 //!
132 //! [^extern_fn]: this remains true for any other ABI: `extern "abi" fn` (_e.g._, `extern "system" fn`)
133 //!
134 //! [`Box<U>`]: ../../std/boxed/struct.Box.html
135 //! [`num::NonZero*`]: crate::num
136 //! [`ptr::NonNull<U>`]: crate::ptr::NonNull
137 //!
138 //! This is called the "null pointer optimization" or NPO.
139 //!
140 //! It is further guaranteed that, for the cases above, one can
141 //! [`mem::transmute`] from all valid values of `T` to `Option<T>` and
142 //! from `Some::<T>(_)` to `T` (but transmuting `None::<T>` to `T`
143 //! is undefined behaviour).
144 //!
145 //! # Method overview
146 //!
147 //! In addition to working with pattern matching, [`Option`] provides a wide
148 //! variety of different methods.
149 //!
150 //! ## Querying the variant
151 //!
152 //! The [`is_some`] and [`is_none`] methods return [`true`] if the [`Option`]
153 //! is [`Some`] or [`None`], respectively.
154 //!
155 //! [`is_none`]: Option::is_none
156 //! [`is_some`]: Option::is_some
157 //!
158 //! ## Adapters for working with references
159 //!
160 //! * [`as_ref`] converts from <code>[&][][Option]\<T></code> to <code>[Option]<[&]T></code>
161 //! * [`as_mut`] converts from <code>[&mut] [Option]\<T></code> to <code>[Option]<[&mut] T></code>
162 //! * [`as_deref`] converts from <code>[&][][Option]\<T></code> to
163 //! <code>[Option]<[&]T::[Target]></code>
164 //! * [`as_deref_mut`] converts from <code>[&mut] [Option]\<T></code> to
165 //! <code>[Option]<[&mut] T::[Target]></code>
166 //! * [`as_pin_ref`] converts from <code>[Pin]<[&][][Option]\<T>></code> to
167 //! <code>[Option]<[Pin]<[&]T>></code>
168 //! * [`as_pin_mut`] converts from <code>[Pin]<[&mut] [Option]\<T>></code> to
169 //! <code>[Option]<[Pin]<[&mut] T>></code>
170 //!
171 //! [&]: reference "shared reference"
172 //! [&mut]: reference "mutable reference"
173 //! [Target]: Deref::Target "ops::Deref::Target"
174 //! [`as_deref`]: Option::as_deref
175 //! [`as_deref_mut`]: Option::as_deref_mut
176 //! [`as_mut`]: Option::as_mut
177 //! [`as_pin_mut`]: Option::as_pin_mut
178 //! [`as_pin_ref`]: Option::as_pin_ref
179 //! [`as_ref`]: Option::as_ref
180 //!
181 //! ## Extracting the contained value
182 //!
183 //! These methods extract the contained value in an [`Option<T>`] when it
184 //! is the [`Some`] variant. If the [`Option`] is [`None`]:
185 //!
186 //! * [`expect`] panics with a provided custom message
187 //! * [`unwrap`] panics with a generic message
188 //! * [`unwrap_or`] returns the provided default value
189 //! * [`unwrap_or_default`] returns the default value of the type `T`
190 //! (which must implement the [`Default`] trait)
191 //! * [`unwrap_or_else`] returns the result of evaluating the provided
192 //! function
193 //!
194 //! [`expect`]: Option::expect
195 //! [`unwrap`]: Option::unwrap
196 //! [`unwrap_or`]: Option::unwrap_or
197 //! [`unwrap_or_default`]: Option::unwrap_or_default
198 //! [`unwrap_or_else`]: Option::unwrap_or_else
199 //!
200 //! ## Transforming contained values
201 //!
202 //! These methods transform [`Option`] to [`Result`]:
203 //!
204 //! * [`ok_or`] transforms [`Some(v)`] to [`Ok(v)`], and [`None`] to
205 //! [`Err(err)`] using the provided default `err` value
206 //! * [`ok_or_else`] transforms [`Some(v)`] to [`Ok(v)`], and [`None`] to
207 //! a value of [`Err`] using the provided function
208 //! * [`transpose`] transposes an [`Option`] of a [`Result`] into a
209 //! [`Result`] of an [`Option`]
210 //!
211 //! [`Err(err)`]: Err
212 //! [`Ok(v)`]: Ok
213 //! [`Some(v)`]: Some
214 //! [`ok_or`]: Option::ok_or
215 //! [`ok_or_else`]: Option::ok_or_else
216 //! [`transpose`]: Option::transpose
217 //!
218 //! These methods transform the [`Some`] variant:
219 //!
220 //! * [`filter`] calls the provided predicate function on the contained
221 //! value `t` if the [`Option`] is [`Some(t)`], and returns [`Some(t)`]
222 //! if the function returns `true`; otherwise, returns [`None`]
223 //! * [`flatten`] removes one level of nesting from an
224 //! [`Option<Option<T>>`]
225 //! * [`map`] transforms [`Option<T>`] to [`Option<U>`] by applying the
226 //! provided function to the contained value of [`Some`] and leaving
227 //! [`None`] values unchanged
228 //!
229 //! [`Some(t)`]: Some
230 //! [`filter`]: Option::filter
231 //! [`flatten`]: Option::flatten
232 //! [`map`]: Option::map
233 //!
234 //! These methods transform [`Option<T>`] to a value of a possibly
235 //! different type `U`:
236 //!
237 //! * [`map_or`] applies the provided function to the contained value of
238 //! [`Some`], or returns the provided default value if the [`Option`] is
239 //! [`None`]
240 //! * [`map_or_else`] applies the provided function to the contained value
241 //! of [`Some`], or returns the result of evaluating the provided
242 //! fallback function if the [`Option`] is [`None`]
243 //!
244 //! [`map_or`]: Option::map_or
245 //! [`map_or_else`]: Option::map_or_else
246 //!
247 //! These methods combine the [`Some`] variants of two [`Option`] values:
248 //!
249 //! * [`zip`] returns [`Some((s, o))`] if `self` is [`Some(s)`] and the
250 //! provided [`Option`] value is [`Some(o)`]; otherwise, returns [`None`]
251 //! * [`zip_with`] calls the provided function `f` and returns
252 //! [`Some(f(s, o))`] if `self` is [`Some(s)`] and the provided
253 //! [`Option`] value is [`Some(o)`]; otherwise, returns [`None`]
254 //!
255 //! [`Some(f(s, o))`]: Some
256 //! [`Some(o)`]: Some
257 //! [`Some(s)`]: Some
258 //! [`Some((s, o))`]: Some
259 //! [`zip`]: Option::zip
260 //! [`zip_with`]: Option::zip_with
261 //!
262 //! ## Boolean operators
263 //!
264 //! These methods treat the [`Option`] as a boolean value, where [`Some`]
265 //! acts like [`true`] and [`None`] acts like [`false`]. There are two
266 //! categories of these methods: ones that take an [`Option`] as input, and
267 //! ones that take a function as input (to be lazily evaluated).
268 //!
269 //! The [`and`], [`or`], and [`xor`] methods take another [`Option`] as
270 //! input, and produce an [`Option`] as output. Only the [`and`] method can
271 //! produce an [`Option<U>`] value having a different inner type `U` than
272 //! [`Option<T>`].
273 //!
274 //! | method | self | input | output |
275 //! |---------|-----------|-----------|-----------|
276 //! | [`and`] | `None` | (ignored) | `None` |
277 //! | [`and`] | `Some(x)` | `None` | `None` |
278 //! | [`and`] | `Some(x)` | `Some(y)` | `Some(y)` |
279 //! | [`or`] | `None` | `None` | `None` |
280 //! | [`or`] | `None` | `Some(y)` | `Some(y)` |
281 //! | [`or`] | `Some(x)` | (ignored) | `Some(x)` |
282 //! | [`xor`] | `None` | `None` | `None` |
283 //! | [`xor`] | `None` | `Some(y)` | `Some(y)` |
284 //! | [`xor`] | `Some(x)` | `None` | `Some(x)` |
285 //! | [`xor`] | `Some(x)` | `Some(y)` | `None` |
286 //!
287 //! [`and`]: Option::and
288 //! [`or`]: Option::or
289 //! [`xor`]: Option::xor
290 //!
291 //! The [`and_then`] and [`or_else`] methods take a function as input, and
292 //! only evaluate the function when they need to produce a new value. Only
293 //! the [`and_then`] method can produce an [`Option<U>`] value having a
294 //! different inner type `U` than [`Option<T>`].
295 //!
296 //! | method | self | function input | function result | output |
297 //! |--------------|-----------|----------------|-----------------|-----------|
298 //! | [`and_then`] | `None` | (not provided) | (not evaluated) | `None` |
299 //! | [`and_then`] | `Some(x)` | `x` | `None` | `None` |
300 //! | [`and_then`] | `Some(x)` | `x` | `Some(y)` | `Some(y)` |
301 //! | [`or_else`] | `None` | (not provided) | `None` | `None` |
302 //! | [`or_else`] | `None` | (not provided) | `Some(y)` | `Some(y)` |
303 //! | [`or_else`] | `Some(x)` | (not provided) | (not evaluated) | `Some(x)` |
304 //!
305 //! [`and_then`]: Option::and_then
306 //! [`or_else`]: Option::or_else
307 //!
308 //! This is an example of using methods like [`and_then`] and [`or`] in a
309 //! pipeline of method calls. Early stages of the pipeline pass failure
310 //! values ([`None`]) through unchanged, and continue processing on
311 //! success values ([`Some`]). Toward the end, [`or`] substitutes an error
312 //! message if it receives [`None`].
313 //!
314 //! ```
315 //! # use std::collections::BTreeMap;
316 //! let mut bt = BTreeMap::new();
317 //! bt.insert(20u8, "foo");
318 //! bt.insert(42u8, "bar");
319 //! let res = [0u8, 1, 11, 200, 22]
320 //! .into_iter()
321 //! .map(|x| {
322 //! // `checked_sub()` returns `None` on error
323 //! x.checked_sub(1)
324 //! // same with `checked_mul()`
325 //! .and_then(|x| x.checked_mul(2))
326 //! // `BTreeMap::get` returns `None` on error
327 //! .and_then(|x| bt.get(&x))
328 //! // Substitute an error message if we have `None` so far
329 //! .or(Some(&"error!"))
330 //! .copied()
331 //! // Won't panic because we unconditionally used `Some` above
332 //! .unwrap()
333 //! })
334 //! .collect::<Vec<_>>();
335 //! assert_eq!(res, ["error!", "error!", "foo", "error!", "bar"]);
336 //! ```
337 //!
338 //! ## Comparison operators
339 //!
340 //! If `T` implements [`PartialOrd`] then [`Option<T>`] will derive its
341 //! [`PartialOrd`] implementation. With this order, [`None`] compares as
342 //! less than any [`Some`], and two [`Some`] compare the same way as their
343 //! contained values would in `T`. If `T` also implements
344 //! [`Ord`], then so does [`Option<T>`].
345 //!
346 //! ```
347 //! assert!(None < Some(0));
348 //! assert!(Some(0) < Some(1));
349 //! ```
350 //!
351 //! ## Iterating over `Option`
352 //!
353 //! An [`Option`] can be iterated over. This can be helpful if you need an
354 //! iterator that is conditionally empty. The iterator will either produce
355 //! a single value (when the [`Option`] is [`Some`]), or produce no values
356 //! (when the [`Option`] is [`None`]). For example, [`into_iter`] acts like
357 //! [`once(v)`] if the [`Option`] is [`Some(v)`], and like [`empty()`] if
358 //! the [`Option`] is [`None`].
359 //!
360 //! [`Some(v)`]: Some
361 //! [`empty()`]: crate::iter::empty
362 //! [`once(v)`]: crate::iter::once
363 //!
364 //! Iterators over [`Option<T>`] come in three types:
365 //!
366 //! * [`into_iter`] consumes the [`Option`] and produces the contained
367 //! value
368 //! * [`iter`] produces an immutable reference of type `&T` to the
369 //! contained value
370 //! * [`iter_mut`] produces a mutable reference of type `&mut T` to the
371 //! contained value
372 //!
373 //! [`into_iter`]: Option::into_iter
374 //! [`iter`]: Option::iter
375 //! [`iter_mut`]: Option::iter_mut
376 //!
377 //! An iterator over [`Option`] can be useful when chaining iterators, for
378 //! example, to conditionally insert items. (It's not always necessary to
379 //! explicitly call an iterator constructor: many [`Iterator`] methods that
380 //! accept other iterators will also accept iterable types that implement
381 //! [`IntoIterator`], which includes [`Option`].)
382 //!
383 //! ```
384 //! let yep = Some(42);
385 //! let nope = None;
386 //! // chain() already calls into_iter(), so we don't have to do so
387 //! let nums: Vec<i32> = (0..4).chain(yep).chain(4..8).collect();
388 //! assert_eq!(nums, [0, 1, 2, 3, 42, 4, 5, 6, 7]);
389 //! let nums: Vec<i32> = (0..4).chain(nope).chain(4..8).collect();
390 //! assert_eq!(nums, [0, 1, 2, 3, 4, 5, 6, 7]);
391 //! ```
392 //!
393 //! One reason to chain iterators in this way is that a function returning
394 //! `impl Iterator` must have all possible return values be of the same
395 //! concrete type. Chaining an iterated [`Option`] can help with that.
396 //!
397 //! ```
398 //! fn make_iter(do_insert: bool) -> impl Iterator<Item = i32> {
399 //! // Explicit returns to illustrate return types matching
400 //! match do_insert {
401 //! true => return (0..4).chain(Some(42)).chain(4..8),
402 //! false => return (0..4).chain(None).chain(4..8),
403 //! }
404 //! }
405 //! println!("{:?}", make_iter(true).collect::<Vec<_>>());
406 //! println!("{:?}", make_iter(false).collect::<Vec<_>>());
407 //! ```
408 //!
409 //! If we try to do the same thing, but using [`once()`] and [`empty()`],
410 //! we can't return `impl Iterator` anymore because the concrete types of
411 //! the return values differ.
412 //!
413 //! [`empty()`]: crate::iter::empty
414 //! [`once()`]: crate::iter::once
415 //!
416 //! ```compile_fail,E0308
417 //! # use std::iter::{empty, once};
418 //! // This won't compile because all possible returns from the function
419 //! // must have the same concrete type.
420 //! fn make_iter(do_insert: bool) -> impl Iterator<Item = i32> {
421 //! // Explicit returns to illustrate return types not matching
422 //! match do_insert {
423 //! true => return (0..4).chain(once(42)).chain(4..8),
424 //! false => return (0..4).chain(empty()).chain(4..8),
425 //! }
426 //! }
427 //! ```
428 //!
429 //! ## Collecting into `Option`
430 //!
431 //! [`Option`] implements the [`FromIterator`][impl-FromIterator] trait,
432 //! which allows an iterator over [`Option`] values to be collected into an
433 //! [`Option`] of a collection of each contained value of the original
434 //! [`Option`] values, or [`None`] if any of the elements was [`None`].
435 //!
436 //! [impl-FromIterator]: Option#impl-FromIterator%3COption%3CA%3E%3E-for-Option%3CV%3E
437 //!
438 //! ```
439 //! let v = [Some(2), Some(4), None, Some(8)];
440 //! let res: Option<Vec<_>> = v.into_iter().collect();
441 //! assert_eq!(res, None);
442 //! let v = [Some(2), Some(4), Some(8)];
443 //! let res: Option<Vec<_>> = v.into_iter().collect();
444 //! assert_eq!(res, Some(vec![2, 4, 8]));
445 //! ```
446 //!
447 //! [`Option`] also implements the [`Product`][impl-Product] and
448 //! [`Sum`][impl-Sum] traits, allowing an iterator over [`Option`] values
449 //! to provide the [`product`][Iterator::product] and
450 //! [`sum`][Iterator::sum] methods.
451 //!
452 //! [impl-Product]: Option#impl-Product%3COption%3CU%3E%3E-for-Option%3CT%3E
453 //! [impl-Sum]: Option#impl-Sum%3COption%3CU%3E%3E-for-Option%3CT%3E
454 //!
455 //! ```
456 //! let v = [None, Some(1), Some(2), Some(3)];
457 //! let res: Option<i32> = v.into_iter().sum();
458 //! assert_eq!(res, None);
459 //! let v = [Some(1), Some(2), Some(21)];
460 //! let res: Option<i32> = v.into_iter().product();
461 //! assert_eq!(res, Some(42));
462 //! ```
463 //!
464 //! ## Modifying an [`Option`] in-place
465 //!
466 //! These methods return a mutable reference to the contained value of an
467 //! [`Option<T>`]:
468 //!
469 //! * [`insert`] inserts a value, dropping any old contents
470 //! * [`get_or_insert`] gets the current value, inserting a provided
471 //! default value if it is [`None`]
472 //! * [`get_or_insert_default`] gets the current value, inserting the
473 //! default value of type `T` (which must implement [`Default`]) if it is
474 //! [`None`]
475 //! * [`get_or_insert_with`] gets the current value, inserting a default
476 //! computed by the provided function if it is [`None`]
477 //!
478 //! [`get_or_insert`]: Option::get_or_insert
479 //! [`get_or_insert_default`]: Option::get_or_insert_default
480 //! [`get_or_insert_with`]: Option::get_or_insert_with
481 //! [`insert`]: Option::insert
482 //!
483 //! These methods transfer ownership of the contained value of an
484 //! [`Option`]:
485 //!
486 //! * [`take`] takes ownership of the contained value of an [`Option`], if
487 //! any, replacing the [`Option`] with [`None`]
488 //! * [`replace`] takes ownership of the contained value of an [`Option`],
489 //! if any, replacing the [`Option`] with a [`Some`] containing the
490 //! provided value
491 //!
492 //! [`replace`]: Option::replace
493 //! [`take`]: Option::take
494 //!
495 //! # Examples
496 //!
497 //! Basic pattern matching on [`Option`]:
498 //!
499 //! ```
500 //! let msg = Some("howdy");
501 //!
502 //! // Take a reference to the contained string
503 //! if let Some(m) = &msg {
504 //! println!("{}", *m);
505 //! }
506 //!
507 //! // Remove the contained string, destroying the Option
508 //! let unwrapped_msg = msg.unwrap_or("default message");
509 //! ```
510 //!
511 //! Initialize a result to [`None`] before a loop:
512 //!
513 //! ```
514 //! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) }
515 //!
516 //! // A list of data to search through.
517 //! let all_the_big_things = [
518 //! Kingdom::Plant(250, "redwood"),
519 //! Kingdom::Plant(230, "noble fir"),
520 //! Kingdom::Plant(229, "sugar pine"),
521 //! Kingdom::Animal(25, "blue whale"),
522 //! Kingdom::Animal(19, "fin whale"),
523 //! Kingdom::Animal(15, "north pacific right whale"),
524 //! ];
525 //!
526 //! // We're going to search for the name of the biggest animal,
527 //! // but to start with we've just got `None`.
528 //! let mut name_of_biggest_animal = None;
529 //! let mut size_of_biggest_animal = 0;
530 //! for big_thing in &all_the_big_things {
531 //! match *big_thing {
532 //! Kingdom::Animal(size, name) if size > size_of_biggest_animal => {
533 //! // Now we've found the name of some big animal
534 //! size_of_biggest_animal = size;
535 //! name_of_biggest_animal = Some(name);
536 //! }
537 //! Kingdom::Animal(..) | Kingdom::Plant(..) => ()
538 //! }
539 //! }
540 //!
541 //! match name_of_biggest_animal {
542 //! Some(name) => println!("the biggest animal is {name}"),
543 //! None => println!("there are no animals :("),
544 //! }
545 //! ```
546
547 #![stable(feature = "rust1", since = "1.0.0")]
548
549 use crate::iter::{self, FromIterator, FusedIterator, TrustedLen};
550 use crate::panicking::{panic, panic_str};
551 use crate::pin::Pin;
552 use crate::{
553 cmp, convert, hint, mem,
554 ops::{self, ControlFlow, Deref, DerefMut},
555 slice,
556 };
557
558 /// The `Option` type. See [the module level documentation](self) for more.
559 #[derive(Copy, PartialOrd, Eq, Ord, Debug, Hash)]
560 #[rustc_diagnostic_item = "Option"]
561 #[lang = "Option"]
562 #[stable(feature = "rust1", since = "1.0.0")]
563 pub enum Option<T> {
564 /// No value.
565 #[lang = "None"]
566 #[stable(feature = "rust1", since = "1.0.0")]
567 None,
568 /// Some value of type `T`.
569 #[lang = "Some"]
570 #[stable(feature = "rust1", since = "1.0.0")]
571 Some(#[stable(feature = "rust1", since = "1.0.0")] T),
572 }
573
574 /////////////////////////////////////////////////////////////////////////////
575 // Type implementation
576 /////////////////////////////////////////////////////////////////////////////
577
578 impl<T> Option<T> {
579 /////////////////////////////////////////////////////////////////////////
580 // Querying the contained values
581 /////////////////////////////////////////////////////////////////////////
582
583 /// Returns `true` if the option is a [`Some`] value.
584 ///
585 /// # Examples
586 ///
587 /// ```
588 /// let x: Option<u32> = Some(2);
589 /// assert_eq!(x.is_some(), true);
590 ///
591 /// let x: Option<u32> = None;
592 /// assert_eq!(x.is_some(), false);
593 /// ```
594 #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"]
595 #[inline]
596 #[stable(feature = "rust1", since = "1.0.0")]
597 #[rustc_const_stable(feature = "const_option_basics", since = "1.48.0")]
is_some(&self) -> bool598 pub const fn is_some(&self) -> bool {
599 matches!(*self, Some(_))
600 }
601
602 /// Returns `true` if the option is a [`Some`] and the value inside of it matches a predicate.
603 ///
604 /// # Examples
605 ///
606 /// ```
607 /// let x: Option<u32> = Some(2);
608 /// assert_eq!(x.is_some_and(|x| x > 1), true);
609 ///
610 /// let x: Option<u32> = Some(0);
611 /// assert_eq!(x.is_some_and(|x| x > 1), false);
612 ///
613 /// let x: Option<u32> = None;
614 /// assert_eq!(x.is_some_and(|x| x > 1), false);
615 /// ```
616 #[must_use]
617 #[inline]
618 #[stable(feature = "is_some_and", since = "1.70.0")]
is_some_and(self, f: impl FnOnce(T) -> bool) -> bool619 pub fn is_some_and(self, f: impl FnOnce(T) -> bool) -> bool {
620 match self {
621 None => false,
622 Some(x) => f(x),
623 }
624 }
625
626 /// Returns `true` if the option is a [`None`] value.
627 ///
628 /// # Examples
629 ///
630 /// ```
631 /// let x: Option<u32> = Some(2);
632 /// assert_eq!(x.is_none(), false);
633 ///
634 /// let x: Option<u32> = None;
635 /// assert_eq!(x.is_none(), true);
636 /// ```
637 #[must_use = "if you intended to assert that this doesn't have a value, consider \
638 `.and_then(|_| panic!(\"`Option` had a value when expected `None`\"))` instead"]
639 #[inline]
640 #[stable(feature = "rust1", since = "1.0.0")]
641 #[rustc_const_stable(feature = "const_option_basics", since = "1.48.0")]
is_none(&self) -> bool642 pub const fn is_none(&self) -> bool {
643 !self.is_some()
644 }
645
646 /////////////////////////////////////////////////////////////////////////
647 // Adapter for working with references
648 /////////////////////////////////////////////////////////////////////////
649
650 /// Converts from `&Option<T>` to `Option<&T>`.
651 ///
652 /// # Examples
653 ///
654 /// Calculates the length of an <code>Option<[String]></code> as an <code>Option<[usize]></code>
655 /// without moving the [`String`]. The [`map`] method takes the `self` argument by value,
656 /// consuming the original, so this technique uses `as_ref` to first take an `Option` to a
657 /// reference to the value inside the original.
658 ///
659 /// [`map`]: Option::map
660 /// [String]: ../../std/string/struct.String.html "String"
661 /// [`String`]: ../../std/string/struct.String.html "String"
662 ///
663 /// ```
664 /// let text: Option<String> = Some("Hello, world!".to_string());
665 /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
666 /// // then consume *that* with `map`, leaving `text` on the stack.
667 /// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
668 /// println!("still can print text: {text:?}");
669 /// ```
670 #[inline]
671 #[rustc_const_stable(feature = "const_option_basics", since = "1.48.0")]
672 #[stable(feature = "rust1", since = "1.0.0")]
as_ref(&self) -> Option<&T>673 pub const fn as_ref(&self) -> Option<&T> {
674 match *self {
675 Some(ref x) => Some(x),
676 None => None,
677 }
678 }
679
680 /// Converts from `&mut Option<T>` to `Option<&mut T>`.
681 ///
682 /// # Examples
683 ///
684 /// ```
685 /// let mut x = Some(2);
686 /// match x.as_mut() {
687 /// Some(v) => *v = 42,
688 /// None => {},
689 /// }
690 /// assert_eq!(x, Some(42));
691 /// ```
692 #[inline]
693 #[stable(feature = "rust1", since = "1.0.0")]
694 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
as_mut(&mut self) -> Option<&mut T>695 pub const fn as_mut(&mut self) -> Option<&mut T> {
696 match *self {
697 Some(ref mut x) => Some(x),
698 None => None,
699 }
700 }
701
702 /// Converts from <code>[Pin]<[&]Option\<T>></code> to <code>Option<[Pin]<[&]T>></code>.
703 ///
704 /// [&]: reference "shared reference"
705 #[inline]
706 #[must_use]
707 #[stable(feature = "pin", since = "1.33.0")]
708 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
as_pin_ref(self: Pin<&Self>) -> Option<Pin<&T>>709 pub const fn as_pin_ref(self: Pin<&Self>) -> Option<Pin<&T>> {
710 match Pin::get_ref(self).as_ref() {
711 // SAFETY: `x` is guaranteed to be pinned because it comes from `self`
712 // which is pinned.
713 Some(x) => unsafe { Some(Pin::new_unchecked(x)) },
714 None => None,
715 }
716 }
717
718 /// Converts from <code>[Pin]<[&mut] Option\<T>></code> to <code>Option<[Pin]<[&mut] T>></code>.
719 ///
720 /// [&mut]: reference "mutable reference"
721 #[inline]
722 #[must_use]
723 #[stable(feature = "pin", since = "1.33.0")]
724 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
as_pin_mut(self: Pin<&mut Self>) -> Option<Pin<&mut T>>725 pub const fn as_pin_mut(self: Pin<&mut Self>) -> Option<Pin<&mut T>> {
726 // SAFETY: `get_unchecked_mut` is never used to move the `Option` inside `self`.
727 // `x` is guaranteed to be pinned because it comes from `self` which is pinned.
728 unsafe {
729 match Pin::get_unchecked_mut(self).as_mut() {
730 Some(x) => Some(Pin::new_unchecked(x)),
731 None => None,
732 }
733 }
734 }
735
736 /// Returns a slice of the contained value, if any. If this is `None`, an
737 /// empty slice is returned. This can be useful to have a single type of
738 /// iterator over an `Option` or slice.
739 ///
740 /// Note: Should you have an `Option<&T>` and wish to get a slice of `T`,
741 /// you can unpack it via `opt.map_or(&[], std::slice::from_ref)`.
742 ///
743 /// # Examples
744 ///
745 /// ```rust
746 /// #![feature(option_as_slice)]
747 ///
748 /// assert_eq!(
749 /// [Some(1234).as_slice(), None.as_slice()],
750 /// [&[1234][..], &[][..]],
751 /// );
752 /// ```
753 ///
754 /// The inverse of this function is (discounting
755 /// borrowing) [`[_]::first`](slice::first):
756 ///
757 /// ```rust
758 /// #![feature(option_as_slice)]
759 ///
760 /// for i in [Some(1234_u16), None] {
761 /// assert_eq!(i.as_ref(), i.as_slice().first());
762 /// }
763 /// ```
764 #[inline]
765 #[must_use]
766 #[unstable(feature = "option_as_slice", issue = "108545")]
as_slice(&self) -> &[T]767 pub fn as_slice(&self) -> &[T] {
768 // SAFETY: When the `Option` is `Some`, we're using the actual pointer
769 // to the payload, with a length of 1, so this is equivalent to
770 // `slice::from_ref`, and thus is safe.
771 // When the `Option` is `None`, the length used is 0, so to be safe it
772 // just needs to be aligned, which it is because `&self` is aligned and
773 // the offset used is a multiple of alignment.
774 //
775 // In the new version, the intrinsic always returns a pointer to an
776 // in-bounds and correctly aligned position for a `T` (even if in the
777 // `None` case it's just padding).
778 unsafe {
779 slice::from_raw_parts(
780 crate::intrinsics::option_payload_ptr(crate::ptr::from_ref(self)),
781 usize::from(self.is_some()),
782 )
783 }
784 }
785
786 /// Returns a mutable slice of the contained value, if any. If this is
787 /// `None`, an empty slice is returned. This can be useful to have a
788 /// single type of iterator over an `Option` or slice.
789 ///
790 /// Note: Should you have an `Option<&mut T>` instead of a
791 /// `&mut Option<T>`, which this method takes, you can obtain a mutable
792 /// slice via `opt.map_or(&mut [], std::slice::from_mut)`.
793 ///
794 /// # Examples
795 ///
796 /// ```rust
797 /// #![feature(option_as_slice)]
798 ///
799 /// assert_eq!(
800 /// [Some(1234).as_mut_slice(), None.as_mut_slice()],
801 /// [&mut [1234][..], &mut [][..]],
802 /// );
803 /// ```
804 ///
805 /// The result is a mutable slice of zero or one items that points into
806 /// our original `Option`:
807 ///
808 /// ```rust
809 /// #![feature(option_as_slice)]
810 ///
811 /// let mut x = Some(1234);
812 /// x.as_mut_slice()[0] += 1;
813 /// assert_eq!(x, Some(1235));
814 /// ```
815 ///
816 /// The inverse of this method (discounting borrowing)
817 /// is [`[_]::first_mut`](slice::first_mut):
818 ///
819 /// ```rust
820 /// #![feature(option_as_slice)]
821 ///
822 /// assert_eq!(Some(123).as_mut_slice().first_mut(), Some(&mut 123))
823 /// ```
824 #[inline]
825 #[must_use]
826 #[unstable(feature = "option_as_slice", issue = "108545")]
as_mut_slice(&mut self) -> &mut [T]827 pub fn as_mut_slice(&mut self) -> &mut [T] {
828 // SAFETY: When the `Option` is `Some`, we're using the actual pointer
829 // to the payload, with a length of 1, so this is equivalent to
830 // `slice::from_mut`, and thus is safe.
831 // When the `Option` is `None`, the length used is 0, so to be safe it
832 // just needs to be aligned, which it is because `&self` is aligned and
833 // the offset used is a multiple of alignment.
834 //
835 // In the new version, the intrinsic creates a `*const T` from a
836 // mutable reference so it is safe to cast back to a mutable pointer
837 // here. As with `as_slice`, the intrinsic always returns a pointer to
838 // an in-bounds and correctly aligned position for a `T` (even if in
839 // the `None` case it's just padding).
840 unsafe {
841 slice::from_raw_parts_mut(
842 crate::intrinsics::option_payload_ptr(crate::ptr::from_mut(self).cast_const())
843 .cast_mut(),
844 usize::from(self.is_some()),
845 )
846 }
847 }
848
849 /////////////////////////////////////////////////////////////////////////
850 // Getting to contained values
851 /////////////////////////////////////////////////////////////////////////
852
853 /// Returns the contained [`Some`] value, consuming the `self` value.
854 ///
855 /// # Panics
856 ///
857 /// Panics if the value is a [`None`] with a custom panic message provided by
858 /// `msg`.
859 ///
860 /// # Examples
861 ///
862 /// ```
863 /// let x = Some("value");
864 /// assert_eq!(x.expect("fruits are healthy"), "value");
865 /// ```
866 ///
867 /// ```should_panic
868 /// let x: Option<&str> = None;
869 /// x.expect("fruits are healthy"); // panics with `fruits are healthy`
870 /// ```
871 ///
872 /// # Recommended Message Style
873 ///
874 /// We recommend that `expect` messages are used to describe the reason you
875 /// _expect_ the `Option` should be `Some`.
876 ///
877 /// ```should_panic
878 /// # let slice: &[u8] = &[];
879 /// let item = slice.get(0)
880 /// .expect("slice should not be empty");
881 /// ```
882 ///
883 /// **Hint**: If you're having trouble remembering how to phrase expect
884 /// error messages remember to focus on the word "should" as in "env
885 /// variable should be set by blah" or "the given binary should be available
886 /// and executable by the current user".
887 ///
888 /// For more detail on expect message styles and the reasoning behind our
889 /// recommendation please refer to the section on ["Common Message
890 /// Styles"](../../std/error/index.html#common-message-styles) in the [`std::error`](../../std/error/index.html) module docs.
891 #[inline]
892 #[track_caller]
893 #[stable(feature = "rust1", since = "1.0.0")]
894 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
expect(self, msg: &str) -> T895 pub const fn expect(self, msg: &str) -> T {
896 match self {
897 Some(val) => val,
898 None => expect_failed(msg),
899 }
900 }
901
902 /// Returns the contained [`Some`] value, consuming the `self` value.
903 ///
904 /// Because this function may panic, its use is generally discouraged.
905 /// Instead, prefer to use pattern matching and handle the [`None`]
906 /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
907 /// [`unwrap_or_default`].
908 ///
909 /// [`unwrap_or`]: Option::unwrap_or
910 /// [`unwrap_or_else`]: Option::unwrap_or_else
911 /// [`unwrap_or_default`]: Option::unwrap_or_default
912 ///
913 /// # Panics
914 ///
915 /// Panics if the self value equals [`None`].
916 ///
917 /// # Examples
918 ///
919 /// ```
920 /// let x = Some("air");
921 /// assert_eq!(x.unwrap(), "air");
922 /// ```
923 ///
924 /// ```should_panic
925 /// let x: Option<&str> = None;
926 /// assert_eq!(x.unwrap(), "air"); // fails
927 /// ```
928 #[inline]
929 #[track_caller]
930 #[stable(feature = "rust1", since = "1.0.0")]
931 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
unwrap(self) -> T932 pub const fn unwrap(self) -> T {
933 match self {
934 Some(val) => val,
935 None => panic("called `Option::unwrap()` on a `None` value"),
936 }
937 }
938
939 /// Returns the contained [`Some`] value or a provided default.
940 ///
941 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
942 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
943 /// which is lazily evaluated.
944 ///
945 /// [`unwrap_or_else`]: Option::unwrap_or_else
946 ///
947 /// # Examples
948 ///
949 /// ```
950 /// assert_eq!(Some("car").unwrap_or("bike"), "car");
951 /// assert_eq!(None.unwrap_or("bike"), "bike");
952 /// ```
953 #[inline]
954 #[stable(feature = "rust1", since = "1.0.0")]
unwrap_or(self, default: T) -> T955 pub fn unwrap_or(self, default: T) -> T {
956 match self {
957 Some(x) => x,
958 None => default,
959 }
960 }
961
962 /// Returns the contained [`Some`] value or computes it from a closure.
963 ///
964 /// # Examples
965 ///
966 /// ```
967 /// let k = 10;
968 /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
969 /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
970 /// ```
971 #[inline]
972 #[stable(feature = "rust1", since = "1.0.0")]
unwrap_or_else<F>(self, f: F) -> T where F: FnOnce() -> T,973 pub fn unwrap_or_else<F>(self, f: F) -> T
974 where
975 F: FnOnce() -> T,
976 {
977 match self {
978 Some(x) => x,
979 None => f(),
980 }
981 }
982
983 /// Returns the contained [`Some`] value or a default.
984 ///
985 /// Consumes the `self` argument then, if [`Some`], returns the contained
986 /// value, otherwise if [`None`], returns the [default value] for that
987 /// type.
988 ///
989 /// # Examples
990 ///
991 /// ```
992 /// let x: Option<u32> = None;
993 /// let y: Option<u32> = Some(12);
994 ///
995 /// assert_eq!(x.unwrap_or_default(), 0);
996 /// assert_eq!(y.unwrap_or_default(), 12);
997 /// ```
998 ///
999 /// [default value]: Default::default
1000 /// [`parse`]: str::parse
1001 /// [`FromStr`]: crate::str::FromStr
1002 #[inline]
1003 #[stable(feature = "rust1", since = "1.0.0")]
unwrap_or_default(self) -> T where T: Default,1004 pub fn unwrap_or_default(self) -> T
1005 where
1006 T: Default,
1007 {
1008 match self {
1009 Some(x) => x,
1010 None => T::default(),
1011 }
1012 }
1013
1014 /// Returns the contained [`Some`] value, consuming the `self` value,
1015 /// without checking that the value is not [`None`].
1016 ///
1017 /// # Safety
1018 ///
1019 /// Calling this method on [`None`] is *[undefined behavior]*.
1020 ///
1021 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1022 ///
1023 /// # Examples
1024 ///
1025 /// ```
1026 /// let x = Some("air");
1027 /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air");
1028 /// ```
1029 ///
1030 /// ```no_run
1031 /// let x: Option<&str> = None;
1032 /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air"); // Undefined behavior!
1033 /// ```
1034 #[inline]
1035 #[track_caller]
1036 #[stable(feature = "option_result_unwrap_unchecked", since = "1.58.0")]
1037 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
unwrap_unchecked(self) -> T1038 pub const unsafe fn unwrap_unchecked(self) -> T {
1039 debug_assert!(self.is_some());
1040 match self {
1041 Some(val) => val,
1042 // SAFETY: the safety contract must be upheld by the caller.
1043 None => unsafe { hint::unreachable_unchecked() },
1044 }
1045 }
1046
1047 /////////////////////////////////////////////////////////////////////////
1048 // Transforming contained values
1049 /////////////////////////////////////////////////////////////////////////
1050
1051 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value (if `Some`) or returns `None` (if `None`).
1052 ///
1053 /// # Examples
1054 ///
1055 /// Calculates the length of an <code>Option<[String]></code> as an
1056 /// <code>Option<[usize]></code>, consuming the original:
1057 ///
1058 /// [String]: ../../std/string/struct.String.html "String"
1059 /// ```
1060 /// let maybe_some_string = Some(String::from("Hello, World!"));
1061 /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
1062 /// let maybe_some_len = maybe_some_string.map(|s| s.len());
1063 /// assert_eq!(maybe_some_len, Some(13));
1064 ///
1065 /// let x: Option<&str> = None;
1066 /// assert_eq!(x.map(|s| s.len()), None);
1067 /// ```
1068 #[inline]
1069 #[stable(feature = "rust1", since = "1.0.0")]
map<U, F>(self, f: F) -> Option<U> where F: FnOnce(T) -> U,1070 pub fn map<U, F>(self, f: F) -> Option<U>
1071 where
1072 F: FnOnce(T) -> U,
1073 {
1074 match self {
1075 Some(x) => Some(f(x)),
1076 None => None,
1077 }
1078 }
1079
1080 /// Calls the provided closure with a reference to the contained value (if [`Some`]).
1081 ///
1082 /// # Examples
1083 ///
1084 /// ```
1085 /// #![feature(result_option_inspect)]
1086 ///
1087 /// let v = vec![1, 2, 3, 4, 5];
1088 ///
1089 /// // prints "got: 4"
1090 /// let x: Option<&usize> = v.get(3).inspect(|x| println!("got: {x}"));
1091 ///
1092 /// // prints nothing
1093 /// let x: Option<&usize> = v.get(5).inspect(|x| println!("got: {x}"));
1094 /// ```
1095 #[inline]
1096 #[unstable(feature = "result_option_inspect", issue = "91345")]
inspect<F>(self, f: F) -> Self where F: FnOnce(&T),1097 pub fn inspect<F>(self, f: F) -> Self
1098 where
1099 F: FnOnce(&T),
1100 {
1101 if let Some(ref x) = self {
1102 f(x);
1103 }
1104
1105 self
1106 }
1107
1108 /// Returns the provided default result (if none),
1109 /// or applies a function to the contained value (if any).
1110 ///
1111 /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
1112 /// the result of a function call, it is recommended to use [`map_or_else`],
1113 /// which is lazily evaluated.
1114 ///
1115 /// [`map_or_else`]: Option::map_or_else
1116 ///
1117 /// # Examples
1118 ///
1119 /// ```
1120 /// let x = Some("foo");
1121 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
1122 ///
1123 /// let x: Option<&str> = None;
1124 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
1125 /// ```
1126 #[inline]
1127 #[stable(feature = "rust1", since = "1.0.0")]
map_or<U, F>(self, default: U, f: F) -> U where F: FnOnce(T) -> U,1128 pub fn map_or<U, F>(self, default: U, f: F) -> U
1129 where
1130 F: FnOnce(T) -> U,
1131 {
1132 match self {
1133 Some(t) => f(t),
1134 None => default,
1135 }
1136 }
1137
1138 /// Computes a default function result (if none), or
1139 /// applies a different function to the contained value (if any).
1140 ///
1141 /// # Basic examples
1142 ///
1143 /// ```
1144 /// let k = 21;
1145 ///
1146 /// let x = Some("foo");
1147 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
1148 ///
1149 /// let x: Option<&str> = None;
1150 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
1151 /// ```
1152 ///
1153 /// # Handling a Result-based fallback
1154 ///
1155 /// A somewhat common occurrence when dealing with optional values
1156 /// in combination with [`Result<T, E>`] is the case where one wants to invoke
1157 /// a fallible fallback if the option is not present. This example
1158 /// parses a command line argument (if present), or the contents of a file to
1159 /// an integer. However, unlike accessing the command line argument, reading
1160 /// the file is fallible, so it must be wrapped with `Ok`.
1161 ///
1162 /// ```no_run
1163 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1164 /// let v: u64 = std::env::args()
1165 /// .nth(1)
1166 /// .map_or_else(|| std::fs::read_to_string("/etc/someconfig.conf"), Ok)?
1167 /// .parse()?;
1168 /// # Ok(())
1169 /// # }
1170 /// ```
1171 #[inline]
1172 #[stable(feature = "rust1", since = "1.0.0")]
map_or_else<U, D, F>(self, default: D, f: F) -> U where D: FnOnce() -> U, F: FnOnce(T) -> U,1173 pub fn map_or_else<U, D, F>(self, default: D, f: F) -> U
1174 where
1175 D: FnOnce() -> U,
1176 F: FnOnce(T) -> U,
1177 {
1178 match self {
1179 Some(t) => f(t),
1180 None => default(),
1181 }
1182 }
1183
1184 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
1185 /// [`Ok(v)`] and [`None`] to [`Err(err)`].
1186 ///
1187 /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
1188 /// result of a function call, it is recommended to use [`ok_or_else`], which is
1189 /// lazily evaluated.
1190 ///
1191 /// [`Ok(v)`]: Ok
1192 /// [`Err(err)`]: Err
1193 /// [`Some(v)`]: Some
1194 /// [`ok_or_else`]: Option::ok_or_else
1195 ///
1196 /// # Examples
1197 ///
1198 /// ```
1199 /// let x = Some("foo");
1200 /// assert_eq!(x.ok_or(0), Ok("foo"));
1201 ///
1202 /// let x: Option<&str> = None;
1203 /// assert_eq!(x.ok_or(0), Err(0));
1204 /// ```
1205 #[inline]
1206 #[stable(feature = "rust1", since = "1.0.0")]
ok_or<E>(self, err: E) -> Result<T, E>1207 pub fn ok_or<E>(self, err: E) -> Result<T, E> {
1208 match self {
1209 Some(v) => Ok(v),
1210 None => Err(err),
1211 }
1212 }
1213
1214 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
1215 /// [`Ok(v)`] and [`None`] to [`Err(err())`].
1216 ///
1217 /// [`Ok(v)`]: Ok
1218 /// [`Err(err())`]: Err
1219 /// [`Some(v)`]: Some
1220 ///
1221 /// # Examples
1222 ///
1223 /// ```
1224 /// let x = Some("foo");
1225 /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
1226 ///
1227 /// let x: Option<&str> = None;
1228 /// assert_eq!(x.ok_or_else(|| 0), Err(0));
1229 /// ```
1230 #[inline]
1231 #[stable(feature = "rust1", since = "1.0.0")]
ok_or_else<E, F>(self, err: F) -> Result<T, E> where F: FnOnce() -> E,1232 pub fn ok_or_else<E, F>(self, err: F) -> Result<T, E>
1233 where
1234 F: FnOnce() -> E,
1235 {
1236 match self {
1237 Some(v) => Ok(v),
1238 None => Err(err()),
1239 }
1240 }
1241
1242 /// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.
1243 ///
1244 /// Leaves the original Option in-place, creating a new one with a reference
1245 /// to the original one, additionally coercing the contents via [`Deref`].
1246 ///
1247 /// # Examples
1248 ///
1249 /// ```
1250 /// let x: Option<String> = Some("hey".to_owned());
1251 /// assert_eq!(x.as_deref(), Some("hey"));
1252 ///
1253 /// let x: Option<String> = None;
1254 /// assert_eq!(x.as_deref(), None);
1255 /// ```
1256 #[inline]
1257 #[stable(feature = "option_deref", since = "1.40.0")]
as_deref(&self) -> Option<&T::Target> where T: Deref,1258 pub fn as_deref(&self) -> Option<&T::Target>
1259 where
1260 T: Deref,
1261 {
1262 match self.as_ref() {
1263 Some(t) => Some(t.deref()),
1264 None => None,
1265 }
1266 }
1267
1268 /// Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`.
1269 ///
1270 /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to
1271 /// the inner type's [`Deref::Target`] type.
1272 ///
1273 /// # Examples
1274 ///
1275 /// ```
1276 /// let mut x: Option<String> = Some("hey".to_owned());
1277 /// assert_eq!(x.as_deref_mut().map(|x| {
1278 /// x.make_ascii_uppercase();
1279 /// x
1280 /// }), Some("HEY".to_owned().as_mut_str()));
1281 /// ```
1282 #[inline]
1283 #[stable(feature = "option_deref", since = "1.40.0")]
as_deref_mut(&mut self) -> Option<&mut T::Target> where T: DerefMut,1284 pub fn as_deref_mut(&mut self) -> Option<&mut T::Target>
1285 where
1286 T: DerefMut,
1287 {
1288 match self.as_mut() {
1289 Some(t) => Some(t.deref_mut()),
1290 None => None,
1291 }
1292 }
1293
1294 /////////////////////////////////////////////////////////////////////////
1295 // Iterator constructors
1296 /////////////////////////////////////////////////////////////////////////
1297
1298 /// Returns an iterator over the possibly contained value.
1299 ///
1300 /// # Examples
1301 ///
1302 /// ```
1303 /// let x = Some(4);
1304 /// assert_eq!(x.iter().next(), Some(&4));
1305 ///
1306 /// let x: Option<u32> = None;
1307 /// assert_eq!(x.iter().next(), None);
1308 /// ```
1309 #[inline]
1310 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1311 #[stable(feature = "rust1", since = "1.0.0")]
iter(&self) -> Iter<'_, T>1312 pub const fn iter(&self) -> Iter<'_, T> {
1313 Iter { inner: Item { opt: self.as_ref() } }
1314 }
1315
1316 /// Returns a mutable iterator over the possibly contained value.
1317 ///
1318 /// # Examples
1319 ///
1320 /// ```
1321 /// let mut x = Some(4);
1322 /// match x.iter_mut().next() {
1323 /// Some(v) => *v = 42,
1324 /// None => {},
1325 /// }
1326 /// assert_eq!(x, Some(42));
1327 ///
1328 /// let mut x: Option<u32> = None;
1329 /// assert_eq!(x.iter_mut().next(), None);
1330 /// ```
1331 #[inline]
1332 #[stable(feature = "rust1", since = "1.0.0")]
iter_mut(&mut self) -> IterMut<'_, T>1333 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1334 IterMut { inner: Item { opt: self.as_mut() } }
1335 }
1336
1337 /////////////////////////////////////////////////////////////////////////
1338 // Boolean operations on the values, eager and lazy
1339 /////////////////////////////////////////////////////////////////////////
1340
1341 /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
1342 ///
1343 /// Arguments passed to `and` are eagerly evaluated; if you are passing the
1344 /// result of a function call, it is recommended to use [`and_then`], which is
1345 /// lazily evaluated.
1346 ///
1347 /// [`and_then`]: Option::and_then
1348 ///
1349 /// # Examples
1350 ///
1351 /// ```
1352 /// let x = Some(2);
1353 /// let y: Option<&str> = None;
1354 /// assert_eq!(x.and(y), None);
1355 ///
1356 /// let x: Option<u32> = None;
1357 /// let y = Some("foo");
1358 /// assert_eq!(x.and(y), None);
1359 ///
1360 /// let x = Some(2);
1361 /// let y = Some("foo");
1362 /// assert_eq!(x.and(y), Some("foo"));
1363 ///
1364 /// let x: Option<u32> = None;
1365 /// let y: Option<&str> = None;
1366 /// assert_eq!(x.and(y), None);
1367 /// ```
1368 #[inline]
1369 #[stable(feature = "rust1", since = "1.0.0")]
and<U>(self, optb: Option<U>) -> Option<U>1370 pub fn and<U>(self, optb: Option<U>) -> Option<U> {
1371 match self {
1372 Some(_) => optb,
1373 None => None,
1374 }
1375 }
1376
1377 /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
1378 /// wrapped value and returns the result.
1379 ///
1380 /// Some languages call this operation flatmap.
1381 ///
1382 /// # Examples
1383 ///
1384 /// ```
1385 /// fn sq_then_to_string(x: u32) -> Option<String> {
1386 /// x.checked_mul(x).map(|sq| sq.to_string())
1387 /// }
1388 ///
1389 /// assert_eq!(Some(2).and_then(sq_then_to_string), Some(4.to_string()));
1390 /// assert_eq!(Some(1_000_000).and_then(sq_then_to_string), None); // overflowed!
1391 /// assert_eq!(None.and_then(sq_then_to_string), None);
1392 /// ```
1393 ///
1394 /// Often used to chain fallible operations that may return [`None`].
1395 ///
1396 /// ```
1397 /// let arr_2d = [["A0", "A1"], ["B0", "B1"]];
1398 ///
1399 /// let item_0_1 = arr_2d.get(0).and_then(|row| row.get(1));
1400 /// assert_eq!(item_0_1, Some(&"A1"));
1401 ///
1402 /// let item_2_0 = arr_2d.get(2).and_then(|row| row.get(0));
1403 /// assert_eq!(item_2_0, None);
1404 /// ```
1405 #[doc(alias = "flatmap")]
1406 #[inline]
1407 #[stable(feature = "rust1", since = "1.0.0")]
and_then<U, F>(self, f: F) -> Option<U> where F: FnOnce(T) -> Option<U>,1408 pub fn and_then<U, F>(self, f: F) -> Option<U>
1409 where
1410 F: FnOnce(T) -> Option<U>,
1411 {
1412 match self {
1413 Some(x) => f(x),
1414 None => None,
1415 }
1416 }
1417
1418 /// Returns [`None`] if the option is [`None`], otherwise calls `predicate`
1419 /// with the wrapped value and returns:
1420 ///
1421 /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped
1422 /// value), and
1423 /// - [`None`] if `predicate` returns `false`.
1424 ///
1425 /// This function works similar to [`Iterator::filter()`]. You can imagine
1426 /// the `Option<T>` being an iterator over one or zero elements. `filter()`
1427 /// lets you decide which elements to keep.
1428 ///
1429 /// # Examples
1430 ///
1431 /// ```rust
1432 /// fn is_even(n: &i32) -> bool {
1433 /// n % 2 == 0
1434 /// }
1435 ///
1436 /// assert_eq!(None.filter(is_even), None);
1437 /// assert_eq!(Some(3).filter(is_even), None);
1438 /// assert_eq!(Some(4).filter(is_even), Some(4));
1439 /// ```
1440 ///
1441 /// [`Some(t)`]: Some
1442 #[inline]
1443 #[stable(feature = "option_filter", since = "1.27.0")]
filter<P>(self, predicate: P) -> Self where P: FnOnce(&T) -> bool,1444 pub fn filter<P>(self, predicate: P) -> Self
1445 where
1446 P: FnOnce(&T) -> bool,
1447 {
1448 if let Some(x) = self {
1449 if predicate(&x) {
1450 return Some(x);
1451 }
1452 }
1453 None
1454 }
1455
1456 /// Returns the option if it contains a value, otherwise returns `optb`.
1457 ///
1458 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
1459 /// result of a function call, it is recommended to use [`or_else`], which is
1460 /// lazily evaluated.
1461 ///
1462 /// [`or_else`]: Option::or_else
1463 ///
1464 /// # Examples
1465 ///
1466 /// ```
1467 /// let x = Some(2);
1468 /// let y = None;
1469 /// assert_eq!(x.or(y), Some(2));
1470 ///
1471 /// let x = None;
1472 /// let y = Some(100);
1473 /// assert_eq!(x.or(y), Some(100));
1474 ///
1475 /// let x = Some(2);
1476 /// let y = Some(100);
1477 /// assert_eq!(x.or(y), Some(2));
1478 ///
1479 /// let x: Option<u32> = None;
1480 /// let y = None;
1481 /// assert_eq!(x.or(y), None);
1482 /// ```
1483 #[inline]
1484 #[stable(feature = "rust1", since = "1.0.0")]
or(self, optb: Option<T>) -> Option<T>1485 pub fn or(self, optb: Option<T>) -> Option<T> {
1486 match self {
1487 Some(x) => Some(x),
1488 None => optb,
1489 }
1490 }
1491
1492 /// Returns the option if it contains a value, otherwise calls `f` and
1493 /// returns the result.
1494 ///
1495 /// # Examples
1496 ///
1497 /// ```
1498 /// fn nobody() -> Option<&'static str> { None }
1499 /// fn vikings() -> Option<&'static str> { Some("vikings") }
1500 ///
1501 /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
1502 /// assert_eq!(None.or_else(vikings), Some("vikings"));
1503 /// assert_eq!(None.or_else(nobody), None);
1504 /// ```
1505 #[inline]
1506 #[stable(feature = "rust1", since = "1.0.0")]
or_else<F>(self, f: F) -> Option<T> where F: FnOnce() -> Option<T>,1507 pub fn or_else<F>(self, f: F) -> Option<T>
1508 where
1509 F: FnOnce() -> Option<T>,
1510 {
1511 match self {
1512 Some(x) => Some(x),
1513 None => f(),
1514 }
1515 }
1516
1517 /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`].
1518 ///
1519 /// # Examples
1520 ///
1521 /// ```
1522 /// let x = Some(2);
1523 /// let y: Option<u32> = None;
1524 /// assert_eq!(x.xor(y), Some(2));
1525 ///
1526 /// let x: Option<u32> = None;
1527 /// let y = Some(2);
1528 /// assert_eq!(x.xor(y), Some(2));
1529 ///
1530 /// let x = Some(2);
1531 /// let y = Some(2);
1532 /// assert_eq!(x.xor(y), None);
1533 ///
1534 /// let x: Option<u32> = None;
1535 /// let y: Option<u32> = None;
1536 /// assert_eq!(x.xor(y), None);
1537 /// ```
1538 #[inline]
1539 #[stable(feature = "option_xor", since = "1.37.0")]
xor(self, optb: Option<T>) -> Option<T>1540 pub fn xor(self, optb: Option<T>) -> Option<T> {
1541 match (self, optb) {
1542 (Some(a), None) => Some(a),
1543 (None, Some(b)) => Some(b),
1544 _ => None,
1545 }
1546 }
1547
1548 /////////////////////////////////////////////////////////////////////////
1549 // Entry-like operations to insert a value and return a reference
1550 /////////////////////////////////////////////////////////////////////////
1551
1552 /// Inserts `value` into the option, then returns a mutable reference to it.
1553 ///
1554 /// If the option already contains a value, the old value is dropped.
1555 ///
1556 /// See also [`Option::get_or_insert`], which doesn't update the value if
1557 /// the option already contains [`Some`].
1558 ///
1559 /// # Example
1560 ///
1561 /// ```
1562 /// let mut opt = None;
1563 /// let val = opt.insert(1);
1564 /// assert_eq!(*val, 1);
1565 /// assert_eq!(opt.unwrap(), 1);
1566 /// let val = opt.insert(2);
1567 /// assert_eq!(*val, 2);
1568 /// *val = 3;
1569 /// assert_eq!(opt.unwrap(), 3);
1570 /// ```
1571 #[must_use = "if you intended to set a value, consider assignment instead"]
1572 #[inline]
1573 #[stable(feature = "option_insert", since = "1.53.0")]
insert(&mut self, value: T) -> &mut T1574 pub fn insert(&mut self, value: T) -> &mut T {
1575 *self = Some(value);
1576
1577 // SAFETY: the code above just filled the option
1578 unsafe { self.as_mut().unwrap_unchecked() }
1579 }
1580
1581 /// Inserts `value` into the option if it is [`None`], then
1582 /// returns a mutable reference to the contained value.
1583 ///
1584 /// See also [`Option::insert`], which updates the value even if
1585 /// the option already contains [`Some`].
1586 ///
1587 /// # Examples
1588 ///
1589 /// ```
1590 /// let mut x = None;
1591 ///
1592 /// {
1593 /// let y: &mut u32 = x.get_or_insert(5);
1594 /// assert_eq!(y, &5);
1595 ///
1596 /// *y = 7;
1597 /// }
1598 ///
1599 /// assert_eq!(x, Some(7));
1600 /// ```
1601 #[inline]
1602 #[stable(feature = "option_entry", since = "1.20.0")]
get_or_insert(&mut self, value: T) -> &mut T1603 pub fn get_or_insert(&mut self, value: T) -> &mut T {
1604 if let None = *self {
1605 *self = Some(value);
1606 }
1607
1608 // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
1609 // variant in the code above.
1610 unsafe { self.as_mut().unwrap_unchecked() }
1611 }
1612
1613 /// Inserts the default value into the option if it is [`None`], then
1614 /// returns a mutable reference to the contained value.
1615 ///
1616 /// # Examples
1617 ///
1618 /// ```
1619 /// #![feature(option_get_or_insert_default)]
1620 ///
1621 /// let mut x = None;
1622 ///
1623 /// {
1624 /// let y: &mut u32 = x.get_or_insert_default();
1625 /// assert_eq!(y, &0);
1626 ///
1627 /// *y = 7;
1628 /// }
1629 ///
1630 /// assert_eq!(x, Some(7));
1631 /// ```
1632 #[inline]
1633 #[unstable(feature = "option_get_or_insert_default", issue = "82901")]
get_or_insert_default(&mut self) -> &mut T where T: Default,1634 pub fn get_or_insert_default(&mut self) -> &mut T
1635 where
1636 T: Default,
1637 {
1638 self.get_or_insert_with(T::default)
1639 }
1640
1641 /// Inserts a value computed from `f` into the option if it is [`None`],
1642 /// then returns a mutable reference to the contained value.
1643 ///
1644 /// # Examples
1645 ///
1646 /// ```
1647 /// let mut x = None;
1648 ///
1649 /// {
1650 /// let y: &mut u32 = x.get_or_insert_with(|| 5);
1651 /// assert_eq!(y, &5);
1652 ///
1653 /// *y = 7;
1654 /// }
1655 ///
1656 /// assert_eq!(x, Some(7));
1657 /// ```
1658 #[inline]
1659 #[stable(feature = "option_entry", since = "1.20.0")]
get_or_insert_with<F>(&mut self, f: F) -> &mut T where F: FnOnce() -> T,1660 pub fn get_or_insert_with<F>(&mut self, f: F) -> &mut T
1661 where
1662 F: FnOnce() -> T,
1663 {
1664 if let None = self {
1665 *self = Some(f());
1666 }
1667
1668 // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
1669 // variant in the code above.
1670 unsafe { self.as_mut().unwrap_unchecked() }
1671 }
1672
1673 /////////////////////////////////////////////////////////////////////////
1674 // Misc
1675 /////////////////////////////////////////////////////////////////////////
1676
1677 /// Takes the value out of the option, leaving a [`None`] in its place.
1678 ///
1679 /// # Examples
1680 ///
1681 /// ```
1682 /// let mut x = Some(2);
1683 /// let y = x.take();
1684 /// assert_eq!(x, None);
1685 /// assert_eq!(y, Some(2));
1686 ///
1687 /// let mut x: Option<u32> = None;
1688 /// let y = x.take();
1689 /// assert_eq!(x, None);
1690 /// assert_eq!(y, None);
1691 /// ```
1692 #[inline]
1693 #[stable(feature = "rust1", since = "1.0.0")]
1694 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
take(&mut self) -> Option<T>1695 pub const fn take(&mut self) -> Option<T> {
1696 // FIXME replace `mem::replace` by `mem::take` when the latter is const ready
1697 mem::replace(self, None)
1698 }
1699
1700 /// Replaces the actual value in the option by the value given in parameter,
1701 /// returning the old value if present,
1702 /// leaving a [`Some`] in its place without deinitializing either one.
1703 ///
1704 /// # Examples
1705 ///
1706 /// ```
1707 /// let mut x = Some(2);
1708 /// let old = x.replace(5);
1709 /// assert_eq!(x, Some(5));
1710 /// assert_eq!(old, Some(2));
1711 ///
1712 /// let mut x = None;
1713 /// let old = x.replace(3);
1714 /// assert_eq!(x, Some(3));
1715 /// assert_eq!(old, None);
1716 /// ```
1717 #[inline]
1718 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1719 #[stable(feature = "option_replace", since = "1.31.0")]
replace(&mut self, value: T) -> Option<T>1720 pub const fn replace(&mut self, value: T) -> Option<T> {
1721 mem::replace(self, Some(value))
1722 }
1723
1724 /// Zips `self` with another `Option`.
1725 ///
1726 /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some((s, o))`.
1727 /// Otherwise, `None` is returned.
1728 ///
1729 /// # Examples
1730 ///
1731 /// ```
1732 /// let x = Some(1);
1733 /// let y = Some("hi");
1734 /// let z = None::<u8>;
1735 ///
1736 /// assert_eq!(x.zip(y), Some((1, "hi")));
1737 /// assert_eq!(x.zip(z), None);
1738 /// ```
1739 #[stable(feature = "option_zip_option", since = "1.46.0")]
zip<U>(self, other: Option<U>) -> Option<(T, U)>1740 pub fn zip<U>(self, other: Option<U>) -> Option<(T, U)> {
1741 match (self, other) {
1742 (Some(a), Some(b)) => Some((a, b)),
1743 _ => None,
1744 }
1745 }
1746
1747 /// Zips `self` and another `Option` with function `f`.
1748 ///
1749 /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
1750 /// Otherwise, `None` is returned.
1751 ///
1752 /// # Examples
1753 ///
1754 /// ```
1755 /// #![feature(option_zip)]
1756 ///
1757 /// #[derive(Debug, PartialEq)]
1758 /// struct Point {
1759 /// x: f64,
1760 /// y: f64,
1761 /// }
1762 ///
1763 /// impl Point {
1764 /// fn new(x: f64, y: f64) -> Self {
1765 /// Self { x, y }
1766 /// }
1767 /// }
1768 ///
1769 /// let x = Some(17.5);
1770 /// let y = Some(42.7);
1771 ///
1772 /// assert_eq!(x.zip_with(y, Point::new), Some(Point { x: 17.5, y: 42.7 }));
1773 /// assert_eq!(x.zip_with(None, Point::new), None);
1774 /// ```
1775 #[unstable(feature = "option_zip", issue = "70086")]
zip_with<U, F, R>(self, other: Option<U>, f: F) -> Option<R> where F: FnOnce(T, U) -> R,1776 pub fn zip_with<U, F, R>(self, other: Option<U>, f: F) -> Option<R>
1777 where
1778 F: FnOnce(T, U) -> R,
1779 {
1780 match (self, other) {
1781 (Some(a), Some(b)) => Some(f(a, b)),
1782 _ => None,
1783 }
1784 }
1785 }
1786
1787 impl<T, U> Option<(T, U)> {
1788 /// Unzips an option containing a tuple of two options.
1789 ///
1790 /// If `self` is `Some((a, b))` this method returns `(Some(a), Some(b))`.
1791 /// Otherwise, `(None, None)` is returned.
1792 ///
1793 /// # Examples
1794 ///
1795 /// ```
1796 /// let x = Some((1, "hi"));
1797 /// let y = None::<(u8, u32)>;
1798 ///
1799 /// assert_eq!(x.unzip(), (Some(1), Some("hi")));
1800 /// assert_eq!(y.unzip(), (None, None));
1801 /// ```
1802 #[inline]
1803 #[stable(feature = "unzip_option", since = "1.66.0")]
unzip(self) -> (Option<T>, Option<U>)1804 pub fn unzip(self) -> (Option<T>, Option<U>) {
1805 match self {
1806 Some((a, b)) => (Some(a), Some(b)),
1807 None => (None, None),
1808 }
1809 }
1810 }
1811
1812 impl<T> Option<&T> {
1813 /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
1814 /// option.
1815 ///
1816 /// # Examples
1817 ///
1818 /// ```
1819 /// let x = 12;
1820 /// let opt_x = Some(&x);
1821 /// assert_eq!(opt_x, Some(&12));
1822 /// let copied = opt_x.copied();
1823 /// assert_eq!(copied, Some(12));
1824 /// ```
1825 #[must_use = "`self` will be dropped if the result is not used"]
1826 #[stable(feature = "copied", since = "1.35.0")]
1827 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
copied(self) -> Option<T> where T: Copy,1828 pub const fn copied(self) -> Option<T>
1829 where
1830 T: Copy,
1831 {
1832 // FIXME: this implementation, which sidesteps using `Option::map` since it's not const
1833 // ready yet, should be reverted when possible to avoid code repetition
1834 match self {
1835 Some(&v) => Some(v),
1836 None => None,
1837 }
1838 }
1839
1840 /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
1841 /// option.
1842 ///
1843 /// # Examples
1844 ///
1845 /// ```
1846 /// let x = 12;
1847 /// let opt_x = Some(&x);
1848 /// assert_eq!(opt_x, Some(&12));
1849 /// let cloned = opt_x.cloned();
1850 /// assert_eq!(cloned, Some(12));
1851 /// ```
1852 #[must_use = "`self` will be dropped if the result is not used"]
1853 #[stable(feature = "rust1", since = "1.0.0")]
cloned(self) -> Option<T> where T: Clone,1854 pub fn cloned(self) -> Option<T>
1855 where
1856 T: Clone,
1857 {
1858 match self {
1859 Some(t) => Some(t.clone()),
1860 None => None,
1861 }
1862 }
1863 }
1864
1865 impl<T> Option<&mut T> {
1866 /// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the
1867 /// option.
1868 ///
1869 /// # Examples
1870 ///
1871 /// ```
1872 /// let mut x = 12;
1873 /// let opt_x = Some(&mut x);
1874 /// assert_eq!(opt_x, Some(&mut 12));
1875 /// let copied = opt_x.copied();
1876 /// assert_eq!(copied, Some(12));
1877 /// ```
1878 #[must_use = "`self` will be dropped if the result is not used"]
1879 #[stable(feature = "copied", since = "1.35.0")]
1880 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
copied(self) -> Option<T> where T: Copy,1881 pub const fn copied(self) -> Option<T>
1882 where
1883 T: Copy,
1884 {
1885 match self {
1886 Some(&mut t) => Some(t),
1887 None => None,
1888 }
1889 }
1890
1891 /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
1892 /// option.
1893 ///
1894 /// # Examples
1895 ///
1896 /// ```
1897 /// let mut x = 12;
1898 /// let opt_x = Some(&mut x);
1899 /// assert_eq!(opt_x, Some(&mut 12));
1900 /// let cloned = opt_x.cloned();
1901 /// assert_eq!(cloned, Some(12));
1902 /// ```
1903 #[must_use = "`self` will be dropped if the result is not used"]
1904 #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
cloned(self) -> Option<T> where T: Clone,1905 pub fn cloned(self) -> Option<T>
1906 where
1907 T: Clone,
1908 {
1909 match self {
1910 Some(t) => Some(t.clone()),
1911 None => None,
1912 }
1913 }
1914 }
1915
1916 impl<T, E> Option<Result<T, E>> {
1917 /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`.
1918 ///
1919 /// [`None`] will be mapped to <code>[Ok]\([None])</code>.
1920 /// <code>[Some]\([Ok]\(\_))</code> and <code>[Some]\([Err]\(\_))</code> will be mapped to
1921 /// <code>[Ok]\([Some]\(\_))</code> and <code>[Err]\(\_)</code>.
1922 ///
1923 /// # Examples
1924 ///
1925 /// ```
1926 /// #[derive(Debug, Eq, PartialEq)]
1927 /// struct SomeErr;
1928 ///
1929 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1930 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1931 /// assert_eq!(x, y.transpose());
1932 /// ```
1933 #[inline]
1934 #[stable(feature = "transpose_result", since = "1.33.0")]
1935 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
transpose(self) -> Result<Option<T>, E>1936 pub const fn transpose(self) -> Result<Option<T>, E> {
1937 match self {
1938 Some(Ok(x)) => Ok(Some(x)),
1939 Some(Err(e)) => Err(e),
1940 None => Ok(None),
1941 }
1942 }
1943 }
1944
1945 // This is a separate function to reduce the code size of .expect() itself.
1946 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
1947 #[cfg_attr(feature = "panic_immediate_abort", inline)]
1948 #[cold]
1949 #[track_caller]
1950 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
expect_failed(msg: &str) -> !1951 const fn expect_failed(msg: &str) -> ! {
1952 panic_str(msg)
1953 }
1954
1955 /////////////////////////////////////////////////////////////////////////////
1956 // Trait implementations
1957 /////////////////////////////////////////////////////////////////////////////
1958
1959 #[stable(feature = "rust1", since = "1.0.0")]
1960 impl<T> Clone for Option<T>
1961 where
1962 T: Clone,
1963 {
1964 #[inline]
clone(&self) -> Self1965 fn clone(&self) -> Self {
1966 match self {
1967 Some(x) => Some(x.clone()),
1968 None => None,
1969 }
1970 }
1971
1972 #[inline]
clone_from(&mut self, source: &Self)1973 fn clone_from(&mut self, source: &Self) {
1974 match (self, source) {
1975 (Some(to), Some(from)) => to.clone_from(from),
1976 (to, from) => *to = from.clone(),
1977 }
1978 }
1979 }
1980
1981 #[stable(feature = "rust1", since = "1.0.0")]
1982 impl<T> Default for Option<T> {
1983 /// Returns [`None`][Option::None].
1984 ///
1985 /// # Examples
1986 ///
1987 /// ```
1988 /// let opt: Option<u32> = Option::default();
1989 /// assert!(opt.is_none());
1990 /// ```
1991 #[inline]
default() -> Option<T>1992 fn default() -> Option<T> {
1993 None
1994 }
1995 }
1996
1997 #[stable(feature = "rust1", since = "1.0.0")]
1998 impl<T> IntoIterator for Option<T> {
1999 type Item = T;
2000 type IntoIter = IntoIter<T>;
2001
2002 /// Returns a consuming iterator over the possibly contained value.
2003 ///
2004 /// # Examples
2005 ///
2006 /// ```
2007 /// let x = Some("string");
2008 /// let v: Vec<&str> = x.into_iter().collect();
2009 /// assert_eq!(v, ["string"]);
2010 ///
2011 /// let x = None;
2012 /// let v: Vec<&str> = x.into_iter().collect();
2013 /// assert!(v.is_empty());
2014 /// ```
2015 #[inline]
into_iter(self) -> IntoIter<T>2016 fn into_iter(self) -> IntoIter<T> {
2017 IntoIter { inner: Item { opt: self } }
2018 }
2019 }
2020
2021 #[stable(since = "1.4.0", feature = "option_iter")]
2022 impl<'a, T> IntoIterator for &'a Option<T> {
2023 type Item = &'a T;
2024 type IntoIter = Iter<'a, T>;
2025
into_iter(self) -> Iter<'a, T>2026 fn into_iter(self) -> Iter<'a, T> {
2027 self.iter()
2028 }
2029 }
2030
2031 #[stable(since = "1.4.0", feature = "option_iter")]
2032 impl<'a, T> IntoIterator for &'a mut Option<T> {
2033 type Item = &'a mut T;
2034 type IntoIter = IterMut<'a, T>;
2035
into_iter(self) -> IterMut<'a, T>2036 fn into_iter(self) -> IterMut<'a, T> {
2037 self.iter_mut()
2038 }
2039 }
2040
2041 #[stable(since = "1.12.0", feature = "option_from")]
2042 impl<T> From<T> for Option<T> {
2043 /// Moves `val` into a new [`Some`].
2044 ///
2045 /// # Examples
2046 ///
2047 /// ```
2048 /// let o: Option<u8> = Option::from(67);
2049 ///
2050 /// assert_eq!(Some(67), o);
2051 /// ```
from(val: T) -> Option<T>2052 fn from(val: T) -> Option<T> {
2053 Some(val)
2054 }
2055 }
2056
2057 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
2058 impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
2059 /// Converts from `&Option<T>` to `Option<&T>`.
2060 ///
2061 /// # Examples
2062 ///
2063 /// Converts an <code>[Option]<[String]></code> into an <code>[Option]<[usize]></code>, preserving
2064 /// the original. The [`map`] method takes the `self` argument by value, consuming the original,
2065 /// so this technique uses `from` to first take an [`Option`] to a reference
2066 /// to the value inside the original.
2067 ///
2068 /// [`map`]: Option::map
2069 /// [String]: ../../std/string/struct.String.html "String"
2070 ///
2071 /// ```
2072 /// let s: Option<String> = Some(String::from("Hello, Rustaceans!"));
2073 /// let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());
2074 ///
2075 /// println!("Can still print s: {s:?}");
2076 ///
2077 /// assert_eq!(o, Some(18));
2078 /// ```
from(o: &'a Option<T>) -> Option<&'a T>2079 fn from(o: &'a Option<T>) -> Option<&'a T> {
2080 o.as_ref()
2081 }
2082 }
2083
2084 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
2085 impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> {
2086 /// Converts from `&mut Option<T>` to `Option<&mut T>`
2087 ///
2088 /// # Examples
2089 ///
2090 /// ```
2091 /// let mut s = Some(String::from("Hello"));
2092 /// let o: Option<&mut String> = Option::from(&mut s);
2093 ///
2094 /// match o {
2095 /// Some(t) => *t = String::from("Hello, Rustaceans!"),
2096 /// None => (),
2097 /// }
2098 ///
2099 /// assert_eq!(s, Some(String::from("Hello, Rustaceans!")));
2100 /// ```
from(o: &'a mut Option<T>) -> Option<&'a mut T>2101 fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
2102 o.as_mut()
2103 }
2104 }
2105
2106 #[stable(feature = "rust1", since = "1.0.0")]
2107 impl<T> crate::marker::StructuralPartialEq for Option<T> {}
2108 #[stable(feature = "rust1", since = "1.0.0")]
2109 impl<T: PartialEq> PartialEq for Option<T> {
2110 #[inline]
eq(&self, other: &Self) -> bool2111 fn eq(&self, other: &Self) -> bool {
2112 SpecOptionPartialEq::eq(self, other)
2113 }
2114 }
2115
2116 /// This specialization trait is a workaround for LLVM not currently (2023-01)
2117 /// being able to optimize this itself, even though Alive confirms that it would
2118 /// be legal to do so: <https://github.com/llvm/llvm-project/issues/52622>
2119 ///
2120 /// Once that's fixed, `Option` should go back to deriving `PartialEq`, as
2121 /// it used to do before <https://github.com/rust-lang/rust/pull/103556>.
2122 #[unstable(feature = "spec_option_partial_eq", issue = "none", reason = "exposed only for rustc")]
2123 #[doc(hidden)]
2124 pub trait SpecOptionPartialEq: Sized {
eq(l: &Option<Self>, other: &Option<Self>) -> bool2125 fn eq(l: &Option<Self>, other: &Option<Self>) -> bool;
2126 }
2127
2128 #[unstable(feature = "spec_option_partial_eq", issue = "none", reason = "exposed only for rustc")]
2129 impl<T: PartialEq> SpecOptionPartialEq for T {
2130 #[inline]
eq(l: &Option<T>, r: &Option<T>) -> bool2131 default fn eq(l: &Option<T>, r: &Option<T>) -> bool {
2132 match (l, r) {
2133 (Some(l), Some(r)) => *l == *r,
2134 (None, None) => true,
2135 _ => false,
2136 }
2137 }
2138 }
2139
2140 macro_rules! non_zero_option {
2141 ( $( #[$stability: meta] $NZ:ty; )+ ) => {
2142 $(
2143 #[$stability]
2144 impl SpecOptionPartialEq for $NZ {
2145 #[inline]
2146 fn eq(l: &Option<Self>, r: &Option<Self>) -> bool {
2147 l.map(Self::get).unwrap_or(0) == r.map(Self::get).unwrap_or(0)
2148 }
2149 }
2150 )+
2151 };
2152 }
2153
2154 non_zero_option! {
2155 #[stable(feature = "nonzero", since = "1.28.0")] crate::num::NonZeroU8;
2156 #[stable(feature = "nonzero", since = "1.28.0")] crate::num::NonZeroU16;
2157 #[stable(feature = "nonzero", since = "1.28.0")] crate::num::NonZeroU32;
2158 #[stable(feature = "nonzero", since = "1.28.0")] crate::num::NonZeroU64;
2159 #[stable(feature = "nonzero", since = "1.28.0")] crate::num::NonZeroU128;
2160 #[stable(feature = "nonzero", since = "1.28.0")] crate::num::NonZeroUsize;
2161 #[stable(feature = "signed_nonzero", since = "1.34.0")] crate::num::NonZeroI8;
2162 #[stable(feature = "signed_nonzero", since = "1.34.0")] crate::num::NonZeroI16;
2163 #[stable(feature = "signed_nonzero", since = "1.34.0")] crate::num::NonZeroI32;
2164 #[stable(feature = "signed_nonzero", since = "1.34.0")] crate::num::NonZeroI64;
2165 #[stable(feature = "signed_nonzero", since = "1.34.0")] crate::num::NonZeroI128;
2166 #[stable(feature = "signed_nonzero", since = "1.34.0")] crate::num::NonZeroIsize;
2167 }
2168
2169 #[stable(feature = "nonnull", since = "1.25.0")]
2170 impl<T> SpecOptionPartialEq for crate::ptr::NonNull<T> {
2171 #[inline]
eq(l: &Option<Self>, r: &Option<Self>) -> bool2172 fn eq(l: &Option<Self>, r: &Option<Self>) -> bool {
2173 l.map(Self::as_ptr).unwrap_or_else(|| crate::ptr::null_mut())
2174 == r.map(Self::as_ptr).unwrap_or_else(|| crate::ptr::null_mut())
2175 }
2176 }
2177
2178 #[stable(feature = "rust1", since = "1.0.0")]
2179 impl SpecOptionPartialEq for cmp::Ordering {
2180 #[inline]
eq(l: &Option<Self>, r: &Option<Self>) -> bool2181 fn eq(l: &Option<Self>, r: &Option<Self>) -> bool {
2182 l.map_or(2, |x| x as i8) == r.map_or(2, |x| x as i8)
2183 }
2184 }
2185
2186 /////////////////////////////////////////////////////////////////////////////
2187 // The Option Iterators
2188 /////////////////////////////////////////////////////////////////////////////
2189
2190 #[derive(Clone, Debug)]
2191 struct Item<A> {
2192 opt: Option<A>,
2193 }
2194
2195 impl<A> Iterator for Item<A> {
2196 type Item = A;
2197
2198 #[inline]
next(&mut self) -> Option<A>2199 fn next(&mut self) -> Option<A> {
2200 self.opt.take()
2201 }
2202
2203 #[inline]
size_hint(&self) -> (usize, Option<usize>)2204 fn size_hint(&self) -> (usize, Option<usize>) {
2205 match self.opt {
2206 Some(_) => (1, Some(1)),
2207 None => (0, Some(0)),
2208 }
2209 }
2210 }
2211
2212 impl<A> DoubleEndedIterator for Item<A> {
2213 #[inline]
next_back(&mut self) -> Option<A>2214 fn next_back(&mut self) -> Option<A> {
2215 self.opt.take()
2216 }
2217 }
2218
2219 impl<A> ExactSizeIterator for Item<A> {}
2220 impl<A> FusedIterator for Item<A> {}
2221 unsafe impl<A> TrustedLen for Item<A> {}
2222
2223 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
2224 ///
2225 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
2226 ///
2227 /// This `struct` is created by the [`Option::iter`] function.
2228 #[stable(feature = "rust1", since = "1.0.0")]
2229 #[derive(Debug)]
2230 pub struct Iter<'a, A: 'a> {
2231 inner: Item<&'a A>,
2232 }
2233
2234 #[stable(feature = "rust1", since = "1.0.0")]
2235 impl<'a, A> Iterator for Iter<'a, A> {
2236 type Item = &'a A;
2237
2238 #[inline]
next(&mut self) -> Option<&'a A>2239 fn next(&mut self) -> Option<&'a A> {
2240 self.inner.next()
2241 }
2242 #[inline]
size_hint(&self) -> (usize, Option<usize>)2243 fn size_hint(&self) -> (usize, Option<usize>) {
2244 self.inner.size_hint()
2245 }
2246 }
2247
2248 #[stable(feature = "rust1", since = "1.0.0")]
2249 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
2250 #[inline]
next_back(&mut self) -> Option<&'a A>2251 fn next_back(&mut self) -> Option<&'a A> {
2252 self.inner.next_back()
2253 }
2254 }
2255
2256 #[stable(feature = "rust1", since = "1.0.0")]
2257 impl<A> ExactSizeIterator for Iter<'_, A> {}
2258
2259 #[stable(feature = "fused", since = "1.26.0")]
2260 impl<A> FusedIterator for Iter<'_, A> {}
2261
2262 #[unstable(feature = "trusted_len", issue = "37572")]
2263 unsafe impl<A> TrustedLen for Iter<'_, A> {}
2264
2265 #[stable(feature = "rust1", since = "1.0.0")]
2266 impl<A> Clone for Iter<'_, A> {
2267 #[inline]
clone(&self) -> Self2268 fn clone(&self) -> Self {
2269 Iter { inner: self.inner.clone() }
2270 }
2271 }
2272
2273 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
2274 ///
2275 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
2276 ///
2277 /// This `struct` is created by the [`Option::iter_mut`] function.
2278 #[stable(feature = "rust1", since = "1.0.0")]
2279 #[derive(Debug)]
2280 pub struct IterMut<'a, A: 'a> {
2281 inner: Item<&'a mut A>,
2282 }
2283
2284 #[stable(feature = "rust1", since = "1.0.0")]
2285 impl<'a, A> Iterator for IterMut<'a, A> {
2286 type Item = &'a mut A;
2287
2288 #[inline]
next(&mut self) -> Option<&'a mut A>2289 fn next(&mut self) -> Option<&'a mut A> {
2290 self.inner.next()
2291 }
2292 #[inline]
size_hint(&self) -> (usize, Option<usize>)2293 fn size_hint(&self) -> (usize, Option<usize>) {
2294 self.inner.size_hint()
2295 }
2296 }
2297
2298 #[stable(feature = "rust1", since = "1.0.0")]
2299 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
2300 #[inline]
next_back(&mut self) -> Option<&'a mut A>2301 fn next_back(&mut self) -> Option<&'a mut A> {
2302 self.inner.next_back()
2303 }
2304 }
2305
2306 #[stable(feature = "rust1", since = "1.0.0")]
2307 impl<A> ExactSizeIterator for IterMut<'_, A> {}
2308
2309 #[stable(feature = "fused", since = "1.26.0")]
2310 impl<A> FusedIterator for IterMut<'_, A> {}
2311 #[unstable(feature = "trusted_len", issue = "37572")]
2312 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
2313
2314 /// An iterator over the value in [`Some`] variant of an [`Option`].
2315 ///
2316 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
2317 ///
2318 /// This `struct` is created by the [`Option::into_iter`] function.
2319 #[derive(Clone, Debug)]
2320 #[stable(feature = "rust1", since = "1.0.0")]
2321 pub struct IntoIter<A> {
2322 inner: Item<A>,
2323 }
2324
2325 #[stable(feature = "rust1", since = "1.0.0")]
2326 impl<A> Iterator for IntoIter<A> {
2327 type Item = A;
2328
2329 #[inline]
next(&mut self) -> Option<A>2330 fn next(&mut self) -> Option<A> {
2331 self.inner.next()
2332 }
2333 #[inline]
size_hint(&self) -> (usize, Option<usize>)2334 fn size_hint(&self) -> (usize, Option<usize>) {
2335 self.inner.size_hint()
2336 }
2337 }
2338
2339 #[stable(feature = "rust1", since = "1.0.0")]
2340 impl<A> DoubleEndedIterator for IntoIter<A> {
2341 #[inline]
next_back(&mut self) -> Option<A>2342 fn next_back(&mut self) -> Option<A> {
2343 self.inner.next_back()
2344 }
2345 }
2346
2347 #[stable(feature = "rust1", since = "1.0.0")]
2348 impl<A> ExactSizeIterator for IntoIter<A> {}
2349
2350 #[stable(feature = "fused", since = "1.26.0")]
2351 impl<A> FusedIterator for IntoIter<A> {}
2352
2353 #[unstable(feature = "trusted_len", issue = "37572")]
2354 unsafe impl<A> TrustedLen for IntoIter<A> {}
2355
2356 /////////////////////////////////////////////////////////////////////////////
2357 // FromIterator
2358 /////////////////////////////////////////////////////////////////////////////
2359
2360 #[stable(feature = "rust1", since = "1.0.0")]
2361 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
2362 /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
2363 /// no further elements are taken, and the [`None`][Option::None] is
2364 /// returned. Should no [`None`][Option::None] occur, a container of type
2365 /// `V` containing the values of each [`Option`] is returned.
2366 ///
2367 /// # Examples
2368 ///
2369 /// Here is an example which increments every integer in a vector.
2370 /// We use the checked variant of `add` that returns `None` when the
2371 /// calculation would result in an overflow.
2372 ///
2373 /// ```
2374 /// let items = vec![0_u16, 1, 2];
2375 ///
2376 /// let res: Option<Vec<u16>> = items
2377 /// .iter()
2378 /// .map(|x| x.checked_add(1))
2379 /// .collect();
2380 ///
2381 /// assert_eq!(res, Some(vec![1, 2, 3]));
2382 /// ```
2383 ///
2384 /// As you can see, this will return the expected, valid items.
2385 ///
2386 /// Here is another example that tries to subtract one from another list
2387 /// of integers, this time checking for underflow:
2388 ///
2389 /// ```
2390 /// let items = vec![2_u16, 1, 0];
2391 ///
2392 /// let res: Option<Vec<u16>> = items
2393 /// .iter()
2394 /// .map(|x| x.checked_sub(1))
2395 /// .collect();
2396 ///
2397 /// assert_eq!(res, None);
2398 /// ```
2399 ///
2400 /// Since the last element is zero, it would underflow. Thus, the resulting
2401 /// value is `None`.
2402 ///
2403 /// Here is a variation on the previous example, showing that no
2404 /// further elements are taken from `iter` after the first `None`.
2405 ///
2406 /// ```
2407 /// let items = vec![3_u16, 2, 1, 10];
2408 ///
2409 /// let mut shared = 0;
2410 ///
2411 /// let res: Option<Vec<u16>> = items
2412 /// .iter()
2413 /// .map(|x| { shared += x; x.checked_sub(2) })
2414 /// .collect();
2415 ///
2416 /// assert_eq!(res, None);
2417 /// assert_eq!(shared, 6);
2418 /// ```
2419 ///
2420 /// Since the third element caused an underflow, no further elements were taken,
2421 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
2422 #[inline]
from_iter<I: IntoIterator<Item = Option<A>>>(iter: I) -> Option<V>2423 fn from_iter<I: IntoIterator<Item = Option<A>>>(iter: I) -> Option<V> {
2424 // FIXME(#11084): This could be replaced with Iterator::scan when this
2425 // performance bug is closed.
2426
2427 iter::try_process(iter.into_iter(), |i| i.collect())
2428 }
2429 }
2430
2431 #[unstable(feature = "try_trait_v2", issue = "84277")]
2432 impl<T> ops::Try for Option<T> {
2433 type Output = T;
2434 type Residual = Option<convert::Infallible>;
2435
2436 #[inline]
from_output(output: Self::Output) -> Self2437 fn from_output(output: Self::Output) -> Self {
2438 Some(output)
2439 }
2440
2441 #[inline]
branch(self) -> ControlFlow<Self::Residual, Self::Output>2442 fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
2443 match self {
2444 Some(v) => ControlFlow::Continue(v),
2445 None => ControlFlow::Break(None),
2446 }
2447 }
2448 }
2449
2450 #[unstable(feature = "try_trait_v2", issue = "84277")]
2451 impl<T> ops::FromResidual for Option<T> {
2452 #[inline]
from_residual(residual: Option<convert::Infallible>) -> Self2453 fn from_residual(residual: Option<convert::Infallible>) -> Self {
2454 match residual {
2455 None => None,
2456 }
2457 }
2458 }
2459
2460 #[unstable(feature = "try_trait_v2_yeet", issue = "96374")]
2461 impl<T> ops::FromResidual<ops::Yeet<()>> for Option<T> {
2462 #[inline]
from_residual(ops::Yeet(()): ops::Yeet<()>) -> Self2463 fn from_residual(ops::Yeet(()): ops::Yeet<()>) -> Self {
2464 None
2465 }
2466 }
2467
2468 #[unstable(feature = "try_trait_v2_residual", issue = "91285")]
2469 impl<T> ops::Residual<T> for Option<convert::Infallible> {
2470 type TryType = Option<T>;
2471 }
2472
2473 impl<T> Option<Option<T>> {
2474 /// Converts from `Option<Option<T>>` to `Option<T>`.
2475 ///
2476 /// # Examples
2477 ///
2478 /// Basic usage:
2479 ///
2480 /// ```
2481 /// let x: Option<Option<u32>> = Some(Some(6));
2482 /// assert_eq!(Some(6), x.flatten());
2483 ///
2484 /// let x: Option<Option<u32>> = Some(None);
2485 /// assert_eq!(None, x.flatten());
2486 ///
2487 /// let x: Option<Option<u32>> = None;
2488 /// assert_eq!(None, x.flatten());
2489 /// ```
2490 ///
2491 /// Flattening only removes one level of nesting at a time:
2492 ///
2493 /// ```
2494 /// let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
2495 /// assert_eq!(Some(Some(6)), x.flatten());
2496 /// assert_eq!(Some(6), x.flatten().flatten());
2497 /// ```
2498 #[inline]
2499 #[stable(feature = "option_flattening", since = "1.40.0")]
2500 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
flatten(self) -> Option<T>2501 pub const fn flatten(self) -> Option<T> {
2502 match self {
2503 Some(inner) => inner,
2504 None => None,
2505 }
2506 }
2507 }
2508