]> git.lizzy.rs Git - rust.git/blob - library/core/src/option.rs
Rollup merge of #106829 - compiler-errors:more-alias-combine, r=spastorino
[rust.git] / library / core / src / option.rs
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::marker::Destruct;
551 use crate::panicking::{panic, panic_str};
552 use crate::pin::Pin;
553 use crate::{
554     convert, hint, mem,
555     ops::{self, ControlFlow, Deref, DerefMut},
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 #[stable(feature = "rust1", since = "1.0.0")]
562 pub enum Option<T> {
563     /// No value.
564     #[lang = "None"]
565     #[stable(feature = "rust1", since = "1.0.0")]
566     None,
567     /// Some value of type `T`.
568     #[lang = "Some"]
569     #[stable(feature = "rust1", since = "1.0.0")]
570     Some(#[stable(feature = "rust1", since = "1.0.0")] T),
571 }
572
573 /////////////////////////////////////////////////////////////////////////////
574 // Type implementation
575 /////////////////////////////////////////////////////////////////////////////
576
577 impl<T> Option<T> {
578     /////////////////////////////////////////////////////////////////////////
579     // Querying the contained values
580     /////////////////////////////////////////////////////////////////////////
581
582     /// Returns `true` if the option is a [`Some`] value.
583     ///
584     /// # Examples
585     ///
586     /// ```
587     /// let x: Option<u32> = Some(2);
588     /// assert_eq!(x.is_some(), true);
589     ///
590     /// let x: Option<u32> = None;
591     /// assert_eq!(x.is_some(), false);
592     /// ```
593     #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"]
594     #[inline]
595     #[stable(feature = "rust1", since = "1.0.0")]
596     #[rustc_const_stable(feature = "const_option_basics", since = "1.48.0")]
597     pub const fn is_some(&self) -> bool {
598         matches!(*self, Some(_))
599     }
600
601     /// Returns `true` if the option is a [`Some`] and the value inside of it matches a predicate.
602     ///
603     /// # Examples
604     ///
605     /// ```
606     /// #![feature(is_some_and)]
607     ///
608     /// let x: Option<u32> = Some(2);
609     /// assert_eq!(x.is_some_and(|x| x > 1), true);
610     ///
611     /// let x: Option<u32> = Some(0);
612     /// assert_eq!(x.is_some_and(|x| x > 1), false);
613     ///
614     /// let x: Option<u32> = None;
615     /// assert_eq!(x.is_some_and(|x| x > 1), false);
616     /// ```
617     #[must_use]
618     #[inline]
619     #[unstable(feature = "is_some_and", issue = "93050")]
620     pub fn is_some_and(self, f: impl FnOnce(T) -> bool) -> bool {
621         match self {
622             None => false,
623             Some(x) => f(x),
624         }
625     }
626
627     /// Returns `true` if the option is a [`None`] value.
628     ///
629     /// # Examples
630     ///
631     /// ```
632     /// let x: Option<u32> = Some(2);
633     /// assert_eq!(x.is_none(), false);
634     ///
635     /// let x: Option<u32> = None;
636     /// assert_eq!(x.is_none(), true);
637     /// ```
638     #[must_use = "if you intended to assert that this doesn't have a value, consider \
639                   `.and_then(|_| panic!(\"`Option` had a value when expected `None`\"))` instead"]
640     #[inline]
641     #[stable(feature = "rust1", since = "1.0.0")]
642     #[rustc_const_stable(feature = "const_option_basics", since = "1.48.0")]
643     pub const fn is_none(&self) -> bool {
644         !self.is_some()
645     }
646
647     /////////////////////////////////////////////////////////////////////////
648     // Adapter for working with references
649     /////////////////////////////////////////////////////////////////////////
650
651     /// Converts from `&Option<T>` to `Option<&T>`.
652     ///
653     /// # Examples
654     ///
655     /// Calculates the length of an <code>Option<[String]></code> as an <code>Option<[usize]></code>
656     /// without moving the [`String`]. The [`map`] method takes the `self` argument by value,
657     /// consuming the original, so this technique uses `as_ref` to first take an `Option` to a
658     /// reference to the value inside the original.
659     ///
660     /// [`map`]: Option::map
661     /// [String]: ../../std/string/struct.String.html "String"
662     /// [`String`]: ../../std/string/struct.String.html "String"
663     ///
664     /// ```
665     /// let text: Option<String> = Some("Hello, world!".to_string());
666     /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
667     /// // then consume *that* with `map`, leaving `text` on the stack.
668     /// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
669     /// println!("still can print text: {text:?}");
670     /// ```
671     #[inline]
672     #[rustc_const_stable(feature = "const_option_basics", since = "1.48.0")]
673     #[stable(feature = "rust1", since = "1.0.0")]
674     pub const fn as_ref(&self) -> Option<&T> {
675         match *self {
676             Some(ref x) => Some(x),
677             None => None,
678         }
679     }
680
681     /// Converts from `&mut Option<T>` to `Option<&mut T>`.
682     ///
683     /// # Examples
684     ///
685     /// ```
686     /// let mut x = Some(2);
687     /// match x.as_mut() {
688     ///     Some(v) => *v = 42,
689     ///     None => {},
690     /// }
691     /// assert_eq!(x, Some(42));
692     /// ```
693     #[inline]
694     #[stable(feature = "rust1", since = "1.0.0")]
695     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
696     pub const fn as_mut(&mut self) -> Option<&mut T> {
697         match *self {
698             Some(ref mut x) => Some(x),
699             None => None,
700         }
701     }
702
703     /// Converts from <code>[Pin]<[&]Option\<T>></code> to <code>Option<[Pin]<[&]T>></code>.
704     ///
705     /// [&]: reference "shared reference"
706     #[inline]
707     #[must_use]
708     #[stable(feature = "pin", since = "1.33.0")]
709     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
710     pub const fn as_pin_ref(self: Pin<&Self>) -> Option<Pin<&T>> {
711         match Pin::get_ref(self).as_ref() {
712             // SAFETY: `x` is guaranteed to be pinned because it comes from `self`
713             // which is pinned.
714             Some(x) => unsafe { Some(Pin::new_unchecked(x)) },
715             None => None,
716         }
717     }
718
719     /// Converts from <code>[Pin]<[&mut] Option\<T>></code> to <code>Option<[Pin]<[&mut] T>></code>.
720     ///
721     /// [&mut]: reference "mutable reference"
722     #[inline]
723     #[must_use]
724     #[stable(feature = "pin", since = "1.33.0")]
725     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
726     pub const fn as_pin_mut(self: Pin<&mut Self>) -> Option<Pin<&mut T>> {
727         // SAFETY: `get_unchecked_mut` is never used to move the `Option` inside `self`.
728         // `x` is guaranteed to be pinned because it comes from `self` which is pinned.
729         unsafe {
730             match Pin::get_unchecked_mut(self).as_mut() {
731                 Some(x) => Some(Pin::new_unchecked(x)),
732                 None => None,
733             }
734         }
735     }
736
737     /////////////////////////////////////////////////////////////////////////
738     // Getting to contained values
739     /////////////////////////////////////////////////////////////////////////
740
741     /// Returns the contained [`Some`] value, consuming the `self` value.
742     ///
743     /// # Panics
744     ///
745     /// Panics if the value is a [`None`] with a custom panic message provided by
746     /// `msg`.
747     ///
748     /// # Examples
749     ///
750     /// ```
751     /// let x = Some("value");
752     /// assert_eq!(x.expect("fruits are healthy"), "value");
753     /// ```
754     ///
755     /// ```should_panic
756     /// let x: Option<&str> = None;
757     /// x.expect("fruits are healthy"); // panics with `fruits are healthy`
758     /// ```
759     ///
760     /// # Recommended Message Style
761     ///
762     /// We recommend that `expect` messages are used to describe the reason you
763     /// _expect_ the `Option` should be `Some`.
764     ///
765     /// ```should_panic
766     /// # let slice: &[u8] = &[];
767     /// let item = slice.get(0)
768     ///     .expect("slice should not be empty");
769     /// ```
770     ///
771     /// **Hint**: If you're having trouble remembering how to phrase expect
772     /// error messages remember to focus on the word "should" as in "env
773     /// variable should be set by blah" or "the given binary should be available
774     /// and executable by the current user".
775     ///
776     /// For more detail on expect message styles and the reasoning behind our
777     /// recommendation please refer to the section on ["Common Message
778     /// Styles"](../../std/error/index.html#common-message-styles) in the [`std::error`](../../std/error/index.html) module docs.
779     #[inline]
780     #[track_caller]
781     #[stable(feature = "rust1", since = "1.0.0")]
782     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
783     pub const fn expect(self, msg: &str) -> T {
784         match self {
785             Some(val) => val,
786             None => expect_failed(msg),
787         }
788     }
789
790     /// Returns the contained [`Some`] value, consuming the `self` value.
791     ///
792     /// Because this function may panic, its use is generally discouraged.
793     /// Instead, prefer to use pattern matching and handle the [`None`]
794     /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
795     /// [`unwrap_or_default`].
796     ///
797     /// [`unwrap_or`]: Option::unwrap_or
798     /// [`unwrap_or_else`]: Option::unwrap_or_else
799     /// [`unwrap_or_default`]: Option::unwrap_or_default
800     ///
801     /// # Panics
802     ///
803     /// Panics if the self value equals [`None`].
804     ///
805     /// # Examples
806     ///
807     /// ```
808     /// let x = Some("air");
809     /// assert_eq!(x.unwrap(), "air");
810     /// ```
811     ///
812     /// ```should_panic
813     /// let x: Option<&str> = None;
814     /// assert_eq!(x.unwrap(), "air"); // fails
815     /// ```
816     #[inline]
817     #[track_caller]
818     #[stable(feature = "rust1", since = "1.0.0")]
819     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
820     pub const fn unwrap(self) -> T {
821         match self {
822             Some(val) => val,
823             None => panic("called `Option::unwrap()` on a `None` value"),
824         }
825     }
826
827     /// Returns the contained [`Some`] value or a provided default.
828     ///
829     /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
830     /// the result of a function call, it is recommended to use [`unwrap_or_else`],
831     /// which is lazily evaluated.
832     ///
833     /// [`unwrap_or_else`]: Option::unwrap_or_else
834     ///
835     /// # Examples
836     ///
837     /// ```
838     /// assert_eq!(Some("car").unwrap_or("bike"), "car");
839     /// assert_eq!(None.unwrap_or("bike"), "bike");
840     /// ```
841     #[inline]
842     #[stable(feature = "rust1", since = "1.0.0")]
843     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
844     pub const fn unwrap_or(self, default: T) -> T
845     where
846         T: ~const Destruct,
847     {
848         match self {
849             Some(x) => x,
850             None => default,
851         }
852     }
853
854     /// Returns the contained [`Some`] value or computes it from a closure.
855     ///
856     /// # Examples
857     ///
858     /// ```
859     /// let k = 10;
860     /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
861     /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
862     /// ```
863     #[inline]
864     #[stable(feature = "rust1", since = "1.0.0")]
865     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
866     pub const fn unwrap_or_else<F>(self, f: F) -> T
867     where
868         F: ~const FnOnce() -> T,
869         F: ~const Destruct,
870     {
871         match self {
872             Some(x) => x,
873             None => f(),
874         }
875     }
876
877     /// Returns the contained [`Some`] value or a default.
878     ///
879     /// Consumes the `self` argument then, if [`Some`], returns the contained
880     /// value, otherwise if [`None`], returns the [default value] for that
881     /// type.
882     ///
883     /// # Examples
884     ///
885     /// ```
886     /// let x: Option<u32> = None;
887     /// let y: Option<u32> = Some(12);
888     ///
889     /// assert_eq!(x.unwrap_or_default(), 0);
890     /// assert_eq!(y.unwrap_or_default(), 12);
891     /// ```
892     ///
893     /// [default value]: Default::default
894     /// [`parse`]: str::parse
895     /// [`FromStr`]: crate::str::FromStr
896     #[inline]
897     #[stable(feature = "rust1", since = "1.0.0")]
898     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
899     pub const fn unwrap_or_default(self) -> T
900     where
901         T: ~const Default,
902     {
903         match self {
904             Some(x) => x,
905             None => Default::default(),
906         }
907     }
908
909     /// Returns the contained [`Some`] value, consuming the `self` value,
910     /// without checking that the value is not [`None`].
911     ///
912     /// # Safety
913     ///
914     /// Calling this method on [`None`] is *[undefined behavior]*.
915     ///
916     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
917     ///
918     /// # Examples
919     ///
920     /// ```
921     /// let x = Some("air");
922     /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air");
923     /// ```
924     ///
925     /// ```no_run
926     /// let x: Option<&str> = None;
927     /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air"); // Undefined behavior!
928     /// ```
929     #[inline]
930     #[track_caller]
931     #[stable(feature = "option_result_unwrap_unchecked", since = "1.58.0")]
932     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
933     pub const unsafe fn unwrap_unchecked(self) -> T {
934         debug_assert!(self.is_some());
935         match self {
936             Some(val) => val,
937             // SAFETY: the safety contract must be upheld by the caller.
938             None => unsafe { hint::unreachable_unchecked() },
939         }
940     }
941
942     /////////////////////////////////////////////////////////////////////////
943     // Transforming contained values
944     /////////////////////////////////////////////////////////////////////////
945
946     /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
947     ///
948     /// # Examples
949     ///
950     /// Calculates the length of an <code>Option<[String]></code> as an
951     /// <code>Option<[usize]></code>, consuming the original:
952     ///
953     /// [String]: ../../std/string/struct.String.html "String"
954     /// ```
955     /// let maybe_some_string = Some(String::from("Hello, World!"));
956     /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
957     /// let maybe_some_len = maybe_some_string.map(|s| s.len());
958     ///
959     /// assert_eq!(maybe_some_len, Some(13));
960     /// ```
961     #[inline]
962     #[stable(feature = "rust1", since = "1.0.0")]
963     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
964     pub const fn map<U, F>(self, f: F) -> Option<U>
965     where
966         F: ~const FnOnce(T) -> U,
967         F: ~const Destruct,
968     {
969         match self {
970             Some(x) => Some(f(x)),
971             None => None,
972         }
973     }
974
975     /// Calls the provided closure with a reference to the contained value (if [`Some`]).
976     ///
977     /// # Examples
978     ///
979     /// ```
980     /// #![feature(result_option_inspect)]
981     ///
982     /// let v = vec![1, 2, 3, 4, 5];
983     ///
984     /// // prints "got: 4"
985     /// let x: Option<&usize> = v.get(3).inspect(|x| println!("got: {x}"));
986     ///
987     /// // prints nothing
988     /// let x: Option<&usize> = v.get(5).inspect(|x| println!("got: {x}"));
989     /// ```
990     #[inline]
991     #[unstable(feature = "result_option_inspect", issue = "91345")]
992     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
993     pub const fn inspect<F>(self, f: F) -> Self
994     where
995         F: ~const FnOnce(&T),
996         F: ~const Destruct,
997     {
998         if let Some(ref x) = self {
999             f(x);
1000         }
1001
1002         self
1003     }
1004
1005     /// Returns the provided default result (if none),
1006     /// or applies a function to the contained value (if any).
1007     ///
1008     /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
1009     /// the result of a function call, it is recommended to use [`map_or_else`],
1010     /// which is lazily evaluated.
1011     ///
1012     /// [`map_or_else`]: Option::map_or_else
1013     ///
1014     /// # Examples
1015     ///
1016     /// ```
1017     /// let x = Some("foo");
1018     /// assert_eq!(x.map_or(42, |v| v.len()), 3);
1019     ///
1020     /// let x: Option<&str> = None;
1021     /// assert_eq!(x.map_or(42, |v| v.len()), 42);
1022     /// ```
1023     #[inline]
1024     #[stable(feature = "rust1", since = "1.0.0")]
1025     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1026     pub const fn map_or<U, F>(self, default: U, f: F) -> U
1027     where
1028         F: ~const FnOnce(T) -> U,
1029         F: ~const Destruct,
1030         U: ~const Destruct,
1031     {
1032         match self {
1033             Some(t) => f(t),
1034             None => default,
1035         }
1036     }
1037
1038     /// Computes a default function result (if none), or
1039     /// applies a different function to the contained value (if any).
1040     ///
1041     /// # Examples
1042     ///
1043     /// ```
1044     /// let k = 21;
1045     ///
1046     /// let x = Some("foo");
1047     /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
1048     ///
1049     /// let x: Option<&str> = None;
1050     /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
1051     /// ```
1052     #[inline]
1053     #[stable(feature = "rust1", since = "1.0.0")]
1054     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1055     pub const fn map_or_else<U, D, F>(self, default: D, f: F) -> U
1056     where
1057         D: ~const FnOnce() -> U,
1058         D: ~const Destruct,
1059         F: ~const FnOnce(T) -> U,
1060         F: ~const Destruct,
1061     {
1062         match self {
1063             Some(t) => f(t),
1064             None => default(),
1065         }
1066     }
1067
1068     /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
1069     /// [`Ok(v)`] and [`None`] to [`Err(err)`].
1070     ///
1071     /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
1072     /// result of a function call, it is recommended to use [`ok_or_else`], which is
1073     /// lazily evaluated.
1074     ///
1075     /// [`Ok(v)`]: Ok
1076     /// [`Err(err)`]: Err
1077     /// [`Some(v)`]: Some
1078     /// [`ok_or_else`]: Option::ok_or_else
1079     ///
1080     /// # Examples
1081     ///
1082     /// ```
1083     /// let x = Some("foo");
1084     /// assert_eq!(x.ok_or(0), Ok("foo"));
1085     ///
1086     /// let x: Option<&str> = None;
1087     /// assert_eq!(x.ok_or(0), Err(0));
1088     /// ```
1089     #[inline]
1090     #[stable(feature = "rust1", since = "1.0.0")]
1091     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1092     pub const fn ok_or<E>(self, err: E) -> Result<T, E>
1093     where
1094         E: ~const Destruct,
1095     {
1096         match self {
1097             Some(v) => Ok(v),
1098             None => Err(err),
1099         }
1100     }
1101
1102     /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
1103     /// [`Ok(v)`] and [`None`] to [`Err(err())`].
1104     ///
1105     /// [`Ok(v)`]: Ok
1106     /// [`Err(err())`]: Err
1107     /// [`Some(v)`]: Some
1108     ///
1109     /// # Examples
1110     ///
1111     /// ```
1112     /// let x = Some("foo");
1113     /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
1114     ///
1115     /// let x: Option<&str> = None;
1116     /// assert_eq!(x.ok_or_else(|| 0), Err(0));
1117     /// ```
1118     #[inline]
1119     #[stable(feature = "rust1", since = "1.0.0")]
1120     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1121     pub const fn ok_or_else<E, F>(self, err: F) -> Result<T, E>
1122     where
1123         F: ~const FnOnce() -> E,
1124         F: ~const Destruct,
1125     {
1126         match self {
1127             Some(v) => Ok(v),
1128             None => Err(err()),
1129         }
1130     }
1131
1132     /// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.
1133     ///
1134     /// Leaves the original Option in-place, creating a new one with a reference
1135     /// to the original one, additionally coercing the contents via [`Deref`].
1136     ///
1137     /// # Examples
1138     ///
1139     /// ```
1140     /// let x: Option<String> = Some("hey".to_owned());
1141     /// assert_eq!(x.as_deref(), Some("hey"));
1142     ///
1143     /// let x: Option<String> = None;
1144     /// assert_eq!(x.as_deref(), None);
1145     /// ```
1146     #[stable(feature = "option_deref", since = "1.40.0")]
1147     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1148     pub const fn as_deref(&self) -> Option<&T::Target>
1149     where
1150         T: ~const Deref,
1151     {
1152         match self.as_ref() {
1153             Some(t) => Some(t.deref()),
1154             None => None,
1155         }
1156     }
1157
1158     /// Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`.
1159     ///
1160     /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to
1161     /// the inner type's [`Deref::Target`] type.
1162     ///
1163     /// # Examples
1164     ///
1165     /// ```
1166     /// let mut x: Option<String> = Some("hey".to_owned());
1167     /// assert_eq!(x.as_deref_mut().map(|x| {
1168     ///     x.make_ascii_uppercase();
1169     ///     x
1170     /// }), Some("HEY".to_owned().as_mut_str()));
1171     /// ```
1172     #[stable(feature = "option_deref", since = "1.40.0")]
1173     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1174     pub const fn as_deref_mut(&mut self) -> Option<&mut T::Target>
1175     where
1176         T: ~const DerefMut,
1177     {
1178         match self.as_mut() {
1179             Some(t) => Some(t.deref_mut()),
1180             None => None,
1181         }
1182     }
1183
1184     /////////////////////////////////////////////////////////////////////////
1185     // Iterator constructors
1186     /////////////////////////////////////////////////////////////////////////
1187
1188     /// Returns an iterator over the possibly contained value.
1189     ///
1190     /// # Examples
1191     ///
1192     /// ```
1193     /// let x = Some(4);
1194     /// assert_eq!(x.iter().next(), Some(&4));
1195     ///
1196     /// let x: Option<u32> = None;
1197     /// assert_eq!(x.iter().next(), None);
1198     /// ```
1199     #[inline]
1200     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1201     #[stable(feature = "rust1", since = "1.0.0")]
1202     pub const fn iter(&self) -> Iter<'_, T> {
1203         Iter { inner: Item { opt: self.as_ref() } }
1204     }
1205
1206     /// Returns a mutable iterator over the possibly contained value.
1207     ///
1208     /// # Examples
1209     ///
1210     /// ```
1211     /// let mut x = Some(4);
1212     /// match x.iter_mut().next() {
1213     ///     Some(v) => *v = 42,
1214     ///     None => {},
1215     /// }
1216     /// assert_eq!(x, Some(42));
1217     ///
1218     /// let mut x: Option<u32> = None;
1219     /// assert_eq!(x.iter_mut().next(), None);
1220     /// ```
1221     #[inline]
1222     #[stable(feature = "rust1", since = "1.0.0")]
1223     pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1224         IterMut { inner: Item { opt: self.as_mut() } }
1225     }
1226
1227     /////////////////////////////////////////////////////////////////////////
1228     // Boolean operations on the values, eager and lazy
1229     /////////////////////////////////////////////////////////////////////////
1230
1231     /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
1232     ///
1233     /// Arguments passed to `and` are eagerly evaluated; if you are passing the
1234     /// result of a function call, it is recommended to use [`and_then`], which is
1235     /// lazily evaluated.
1236     ///
1237     /// [`and_then`]: Option::and_then
1238     ///
1239     /// # Examples
1240     ///
1241     /// ```
1242     /// let x = Some(2);
1243     /// let y: Option<&str> = None;
1244     /// assert_eq!(x.and(y), None);
1245     ///
1246     /// let x: Option<u32> = None;
1247     /// let y = Some("foo");
1248     /// assert_eq!(x.and(y), None);
1249     ///
1250     /// let x = Some(2);
1251     /// let y = Some("foo");
1252     /// assert_eq!(x.and(y), Some("foo"));
1253     ///
1254     /// let x: Option<u32> = None;
1255     /// let y: Option<&str> = None;
1256     /// assert_eq!(x.and(y), None);
1257     /// ```
1258     #[inline]
1259     #[stable(feature = "rust1", since = "1.0.0")]
1260     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1261     pub const fn and<U>(self, optb: Option<U>) -> Option<U>
1262     where
1263         T: ~const Destruct,
1264         U: ~const Destruct,
1265     {
1266         match self {
1267             Some(_) => optb,
1268             None => None,
1269         }
1270     }
1271
1272     /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
1273     /// wrapped value and returns the result.
1274     ///
1275     /// Some languages call this operation flatmap.
1276     ///
1277     /// # Examples
1278     ///
1279     /// ```
1280     /// fn sq_then_to_string(x: u32) -> Option<String> {
1281     ///     x.checked_mul(x).map(|sq| sq.to_string())
1282     /// }
1283     ///
1284     /// assert_eq!(Some(2).and_then(sq_then_to_string), Some(4.to_string()));
1285     /// assert_eq!(Some(1_000_000).and_then(sq_then_to_string), None); // overflowed!
1286     /// assert_eq!(None.and_then(sq_then_to_string), None);
1287     /// ```
1288     ///
1289     /// Often used to chain fallible operations that may return [`None`].
1290     ///
1291     /// ```
1292     /// let arr_2d = [["A0", "A1"], ["B0", "B1"]];
1293     ///
1294     /// let item_0_1 = arr_2d.get(0).and_then(|row| row.get(1));
1295     /// assert_eq!(item_0_1, Some(&"A1"));
1296     ///
1297     /// let item_2_0 = arr_2d.get(2).and_then(|row| row.get(0));
1298     /// assert_eq!(item_2_0, None);
1299     /// ```
1300     #[inline]
1301     #[stable(feature = "rust1", since = "1.0.0")]
1302     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1303     pub const fn and_then<U, F>(self, f: F) -> Option<U>
1304     where
1305         F: ~const FnOnce(T) -> Option<U>,
1306         F: ~const Destruct,
1307     {
1308         match self {
1309             Some(x) => f(x),
1310             None => None,
1311         }
1312     }
1313
1314     /// Returns [`None`] if the option is [`None`], otherwise calls `predicate`
1315     /// with the wrapped value and returns:
1316     ///
1317     /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped
1318     ///   value), and
1319     /// - [`None`] if `predicate` returns `false`.
1320     ///
1321     /// This function works similar to [`Iterator::filter()`]. You can imagine
1322     /// the `Option<T>` being an iterator over one or zero elements. `filter()`
1323     /// lets you decide which elements to keep.
1324     ///
1325     /// # Examples
1326     ///
1327     /// ```rust
1328     /// fn is_even(n: &i32) -> bool {
1329     ///     n % 2 == 0
1330     /// }
1331     ///
1332     /// assert_eq!(None.filter(is_even), None);
1333     /// assert_eq!(Some(3).filter(is_even), None);
1334     /// assert_eq!(Some(4).filter(is_even), Some(4));
1335     /// ```
1336     ///
1337     /// [`Some(t)`]: Some
1338     #[inline]
1339     #[stable(feature = "option_filter", since = "1.27.0")]
1340     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1341     pub const fn filter<P>(self, predicate: P) -> Self
1342     where
1343         T: ~const Destruct,
1344         P: ~const FnOnce(&T) -> bool,
1345         P: ~const Destruct,
1346     {
1347         if let Some(x) = self {
1348             if predicate(&x) {
1349                 return Some(x);
1350             }
1351         }
1352         None
1353     }
1354
1355     /// Returns the option if it contains a value, otherwise returns `optb`.
1356     ///
1357     /// Arguments passed to `or` are eagerly evaluated; if you are passing the
1358     /// result of a function call, it is recommended to use [`or_else`], which is
1359     /// lazily evaluated.
1360     ///
1361     /// [`or_else`]: Option::or_else
1362     ///
1363     /// # Examples
1364     ///
1365     /// ```
1366     /// let x = Some(2);
1367     /// let y = None;
1368     /// assert_eq!(x.or(y), Some(2));
1369     ///
1370     /// let x = None;
1371     /// let y = Some(100);
1372     /// assert_eq!(x.or(y), Some(100));
1373     ///
1374     /// let x = Some(2);
1375     /// let y = Some(100);
1376     /// assert_eq!(x.or(y), Some(2));
1377     ///
1378     /// let x: Option<u32> = None;
1379     /// let y = None;
1380     /// assert_eq!(x.or(y), None);
1381     /// ```
1382     #[inline]
1383     #[stable(feature = "rust1", since = "1.0.0")]
1384     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1385     pub const fn or(self, optb: Option<T>) -> Option<T>
1386     where
1387         T: ~const Destruct,
1388     {
1389         match self {
1390             Some(x) => Some(x),
1391             None => optb,
1392         }
1393     }
1394
1395     /// Returns the option if it contains a value, otherwise calls `f` and
1396     /// returns the result.
1397     ///
1398     /// # Examples
1399     ///
1400     /// ```
1401     /// fn nobody() -> Option<&'static str> { None }
1402     /// fn vikings() -> Option<&'static str> { Some("vikings") }
1403     ///
1404     /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
1405     /// assert_eq!(None.or_else(vikings), Some("vikings"));
1406     /// assert_eq!(None.or_else(nobody), None);
1407     /// ```
1408     #[inline]
1409     #[stable(feature = "rust1", since = "1.0.0")]
1410     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1411     pub const fn or_else<F>(self, f: F) -> Option<T>
1412     where
1413         F: ~const FnOnce() -> Option<T>,
1414         F: ~const Destruct,
1415     {
1416         match self {
1417             Some(x) => Some(x),
1418             None => f(),
1419         }
1420     }
1421
1422     /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`].
1423     ///
1424     /// # Examples
1425     ///
1426     /// ```
1427     /// let x = Some(2);
1428     /// let y: Option<u32> = None;
1429     /// assert_eq!(x.xor(y), Some(2));
1430     ///
1431     /// let x: Option<u32> = None;
1432     /// let y = Some(2);
1433     /// assert_eq!(x.xor(y), Some(2));
1434     ///
1435     /// let x = Some(2);
1436     /// let y = Some(2);
1437     /// assert_eq!(x.xor(y), None);
1438     ///
1439     /// let x: Option<u32> = None;
1440     /// let y: Option<u32> = None;
1441     /// assert_eq!(x.xor(y), None);
1442     /// ```
1443     #[inline]
1444     #[stable(feature = "option_xor", since = "1.37.0")]
1445     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1446     pub const fn xor(self, optb: Option<T>) -> Option<T>
1447     where
1448         T: ~const Destruct,
1449     {
1450         match (self, optb) {
1451             (Some(a), None) => Some(a),
1452             (None, Some(b)) => Some(b),
1453             _ => None,
1454         }
1455     }
1456
1457     /////////////////////////////////////////////////////////////////////////
1458     // Entry-like operations to insert a value and return a reference
1459     /////////////////////////////////////////////////////////////////////////
1460
1461     /// Inserts `value` into the option, then returns a mutable reference to it.
1462     ///
1463     /// If the option already contains a value, the old value is dropped.
1464     ///
1465     /// See also [`Option::get_or_insert`], which doesn't update the value if
1466     /// the option already contains [`Some`].
1467     ///
1468     /// # Example
1469     ///
1470     /// ```
1471     /// let mut opt = None;
1472     /// let val = opt.insert(1);
1473     /// assert_eq!(*val, 1);
1474     /// assert_eq!(opt.unwrap(), 1);
1475     /// let val = opt.insert(2);
1476     /// assert_eq!(*val, 2);
1477     /// *val = 3;
1478     /// assert_eq!(opt.unwrap(), 3);
1479     /// ```
1480     #[must_use = "if you intended to set a value, consider assignment instead"]
1481     #[inline]
1482     #[stable(feature = "option_insert", since = "1.53.0")]
1483     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1484     pub const fn insert(&mut self, value: T) -> &mut T
1485     where
1486         T: ~const Destruct,
1487     {
1488         *self = Some(value);
1489
1490         // SAFETY: the code above just filled the option
1491         unsafe { self.as_mut().unwrap_unchecked() }
1492     }
1493
1494     /// Inserts `value` into the option if it is [`None`], then
1495     /// returns a mutable reference to the contained value.
1496     ///
1497     /// See also [`Option::insert`], which updates the value even if
1498     /// the option already contains [`Some`].
1499     ///
1500     /// # Examples
1501     ///
1502     /// ```
1503     /// let mut x = None;
1504     ///
1505     /// {
1506     ///     let y: &mut u32 = x.get_or_insert(5);
1507     ///     assert_eq!(y, &5);
1508     ///
1509     ///     *y = 7;
1510     /// }
1511     ///
1512     /// assert_eq!(x, Some(7));
1513     /// ```
1514     #[inline]
1515     #[stable(feature = "option_entry", since = "1.20.0")]
1516     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1517     pub const fn get_or_insert(&mut self, value: T) -> &mut T
1518     where
1519         T: ~const Destruct,
1520     {
1521         if let None = *self {
1522             *self = Some(value);
1523         }
1524
1525         // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
1526         // variant in the code above.
1527         unsafe { self.as_mut().unwrap_unchecked() }
1528     }
1529
1530     /// Inserts the default value into the option if it is [`None`], then
1531     /// returns a mutable reference to the contained value.
1532     ///
1533     /// # Examples
1534     ///
1535     /// ```
1536     /// #![feature(option_get_or_insert_default)]
1537     ///
1538     /// let mut x = None;
1539     ///
1540     /// {
1541     ///     let y: &mut u32 = x.get_or_insert_default();
1542     ///     assert_eq!(y, &0);
1543     ///
1544     ///     *y = 7;
1545     /// }
1546     ///
1547     /// assert_eq!(x, Some(7));
1548     /// ```
1549     #[inline]
1550     #[unstable(feature = "option_get_or_insert_default", issue = "82901")]
1551     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1552     pub const fn get_or_insert_default(&mut self) -> &mut T
1553     where
1554         T: ~const Default,
1555     {
1556         const fn default<T: ~const Default>() -> T {
1557             T::default()
1558         }
1559
1560         self.get_or_insert_with(default)
1561     }
1562
1563     /// Inserts a value computed from `f` into the option if it is [`None`],
1564     /// then returns a mutable reference to the contained value.
1565     ///
1566     /// # Examples
1567     ///
1568     /// ```
1569     /// let mut x = None;
1570     ///
1571     /// {
1572     ///     let y: &mut u32 = x.get_or_insert_with(|| 5);
1573     ///     assert_eq!(y, &5);
1574     ///
1575     ///     *y = 7;
1576     /// }
1577     ///
1578     /// assert_eq!(x, Some(7));
1579     /// ```
1580     #[inline]
1581     #[stable(feature = "option_entry", since = "1.20.0")]
1582     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1583     pub const fn get_or_insert_with<F>(&mut self, f: F) -> &mut T
1584     where
1585         F: ~const FnOnce() -> T,
1586         F: ~const Destruct,
1587     {
1588         if let None = *self {
1589             // the compiler isn't smart enough to know that we are not dropping a `T`
1590             // here and wants us to ensure `T` can be dropped at compile time.
1591             mem::forget(mem::replace(self, Some(f())))
1592         }
1593
1594         // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
1595         // variant in the code above.
1596         unsafe { self.as_mut().unwrap_unchecked() }
1597     }
1598
1599     /////////////////////////////////////////////////////////////////////////
1600     // Misc
1601     /////////////////////////////////////////////////////////////////////////
1602
1603     /// Takes the value out of the option, leaving a [`None`] in its place.
1604     ///
1605     /// # Examples
1606     ///
1607     /// ```
1608     /// let mut x = Some(2);
1609     /// let y = x.take();
1610     /// assert_eq!(x, None);
1611     /// assert_eq!(y, Some(2));
1612     ///
1613     /// let mut x: Option<u32> = None;
1614     /// let y = x.take();
1615     /// assert_eq!(x, None);
1616     /// assert_eq!(y, None);
1617     /// ```
1618     #[inline]
1619     #[stable(feature = "rust1", since = "1.0.0")]
1620     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1621     pub const fn take(&mut self) -> Option<T> {
1622         // FIXME replace `mem::replace` by `mem::take` when the latter is const ready
1623         mem::replace(self, None)
1624     }
1625
1626     /// Replaces the actual value in the option by the value given in parameter,
1627     /// returning the old value if present,
1628     /// leaving a [`Some`] in its place without deinitializing either one.
1629     ///
1630     /// # Examples
1631     ///
1632     /// ```
1633     /// let mut x = Some(2);
1634     /// let old = x.replace(5);
1635     /// assert_eq!(x, Some(5));
1636     /// assert_eq!(old, Some(2));
1637     ///
1638     /// let mut x = None;
1639     /// let old = x.replace(3);
1640     /// assert_eq!(x, Some(3));
1641     /// assert_eq!(old, None);
1642     /// ```
1643     #[inline]
1644     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1645     #[stable(feature = "option_replace", since = "1.31.0")]
1646     pub const fn replace(&mut self, value: T) -> Option<T> {
1647         mem::replace(self, Some(value))
1648     }
1649
1650     /// Returns `true` if the option is a [`Some`] value containing the given value.
1651     ///
1652     /// # Examples
1653     ///
1654     /// ```
1655     /// #![feature(option_result_contains)]
1656     ///
1657     /// let x: Option<u32> = Some(2);
1658     /// assert_eq!(x.contains(&2), true);
1659     ///
1660     /// let x: Option<u32> = Some(3);
1661     /// assert_eq!(x.contains(&2), false);
1662     ///
1663     /// let x: Option<u32> = None;
1664     /// assert_eq!(x.contains(&2), false);
1665     /// ```
1666     #[must_use]
1667     #[inline]
1668     #[unstable(feature = "option_result_contains", issue = "62358")]
1669     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1670     pub const fn contains<U>(&self, x: &U) -> bool
1671     where
1672         U: ~const PartialEq<T>,
1673     {
1674         match self {
1675             Some(y) => x.eq(y),
1676             None => false,
1677         }
1678     }
1679
1680     /// Zips `self` with another `Option`.
1681     ///
1682     /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some((s, o))`.
1683     /// Otherwise, `None` is returned.
1684     ///
1685     /// # Examples
1686     ///
1687     /// ```
1688     /// let x = Some(1);
1689     /// let y = Some("hi");
1690     /// let z = None::<u8>;
1691     ///
1692     /// assert_eq!(x.zip(y), Some((1, "hi")));
1693     /// assert_eq!(x.zip(z), None);
1694     /// ```
1695     #[stable(feature = "option_zip_option", since = "1.46.0")]
1696     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1697     pub const fn zip<U>(self, other: Option<U>) -> Option<(T, U)>
1698     where
1699         T: ~const Destruct,
1700         U: ~const Destruct,
1701     {
1702         match (self, other) {
1703             (Some(a), Some(b)) => Some((a, b)),
1704             _ => None,
1705         }
1706     }
1707
1708     /// Zips `self` and another `Option` with function `f`.
1709     ///
1710     /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
1711     /// Otherwise, `None` is returned.
1712     ///
1713     /// # Examples
1714     ///
1715     /// ```
1716     /// #![feature(option_zip)]
1717     ///
1718     /// #[derive(Debug, PartialEq)]
1719     /// struct Point {
1720     ///     x: f64,
1721     ///     y: f64,
1722     /// }
1723     ///
1724     /// impl Point {
1725     ///     fn new(x: f64, y: f64) -> Self {
1726     ///         Self { x, y }
1727     ///     }
1728     /// }
1729     ///
1730     /// let x = Some(17.5);
1731     /// let y = Some(42.7);
1732     ///
1733     /// assert_eq!(x.zip_with(y, Point::new), Some(Point { x: 17.5, y: 42.7 }));
1734     /// assert_eq!(x.zip_with(None, Point::new), None);
1735     /// ```
1736     #[unstable(feature = "option_zip", issue = "70086")]
1737     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1738     pub const fn zip_with<U, F, R>(self, other: Option<U>, f: F) -> Option<R>
1739     where
1740         F: ~const FnOnce(T, U) -> R,
1741         F: ~const Destruct,
1742         T: ~const Destruct,
1743         U: ~const Destruct,
1744     {
1745         match (self, other) {
1746             (Some(a), Some(b)) => Some(f(a, b)),
1747             _ => None,
1748         }
1749     }
1750 }
1751
1752 impl<T, U> Option<(T, U)> {
1753     /// Unzips an option containing a tuple of two options.
1754     ///
1755     /// If `self` is `Some((a, b))` this method returns `(Some(a), Some(b))`.
1756     /// Otherwise, `(None, None)` is returned.
1757     ///
1758     /// # Examples
1759     ///
1760     /// ```
1761     /// let x = Some((1, "hi"));
1762     /// let y = None::<(u8, u32)>;
1763     ///
1764     /// assert_eq!(x.unzip(), (Some(1), Some("hi")));
1765     /// assert_eq!(y.unzip(), (None, None));
1766     /// ```
1767     #[inline]
1768     #[stable(feature = "unzip_option", since = "1.66.0")]
1769     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1770     pub const fn unzip(self) -> (Option<T>, Option<U>)
1771     where
1772         T: ~const Destruct,
1773         U: ~const Destruct,
1774     {
1775         match self {
1776             Some((a, b)) => (Some(a), Some(b)),
1777             None => (None, None),
1778         }
1779     }
1780 }
1781
1782 impl<T> Option<&T> {
1783     /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
1784     /// option.
1785     ///
1786     /// # Examples
1787     ///
1788     /// ```
1789     /// let x = 12;
1790     /// let opt_x = Some(&x);
1791     /// assert_eq!(opt_x, Some(&12));
1792     /// let copied = opt_x.copied();
1793     /// assert_eq!(copied, Some(12));
1794     /// ```
1795     #[must_use = "`self` will be dropped if the result is not used"]
1796     #[stable(feature = "copied", since = "1.35.0")]
1797     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1798     pub const fn copied(self) -> Option<T>
1799     where
1800         T: Copy,
1801     {
1802         // FIXME: this implementation, which sidesteps using `Option::map` since it's not const
1803         // ready yet, should be reverted when possible to avoid code repetition
1804         match self {
1805             Some(&v) => Some(v),
1806             None => None,
1807         }
1808     }
1809
1810     /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
1811     /// option.
1812     ///
1813     /// # Examples
1814     ///
1815     /// ```
1816     /// let x = 12;
1817     /// let opt_x = Some(&x);
1818     /// assert_eq!(opt_x, Some(&12));
1819     /// let cloned = opt_x.cloned();
1820     /// assert_eq!(cloned, Some(12));
1821     /// ```
1822     #[must_use = "`self` will be dropped if the result is not used"]
1823     #[stable(feature = "rust1", since = "1.0.0")]
1824     #[rustc_const_unstable(feature = "const_option_cloned", issue = "91582")]
1825     pub const fn cloned(self) -> Option<T>
1826     where
1827         T: ~const Clone,
1828     {
1829         match self {
1830             Some(t) => Some(t.clone()),
1831             None => None,
1832         }
1833     }
1834 }
1835
1836 impl<T> Option<&mut T> {
1837     /// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the
1838     /// option.
1839     ///
1840     /// # Examples
1841     ///
1842     /// ```
1843     /// let mut x = 12;
1844     /// let opt_x = Some(&mut x);
1845     /// assert_eq!(opt_x, Some(&mut 12));
1846     /// let copied = opt_x.copied();
1847     /// assert_eq!(copied, Some(12));
1848     /// ```
1849     #[must_use = "`self` will be dropped if the result is not used"]
1850     #[stable(feature = "copied", since = "1.35.0")]
1851     #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1852     pub const fn copied(self) -> Option<T>
1853     where
1854         T: Copy,
1855     {
1856         match self {
1857             Some(&mut t) => Some(t),
1858             None => None,
1859         }
1860     }
1861
1862     /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
1863     /// option.
1864     ///
1865     /// # Examples
1866     ///
1867     /// ```
1868     /// let mut x = 12;
1869     /// let opt_x = Some(&mut x);
1870     /// assert_eq!(opt_x, Some(&mut 12));
1871     /// let cloned = opt_x.cloned();
1872     /// assert_eq!(cloned, Some(12));
1873     /// ```
1874     #[must_use = "`self` will be dropped if the result is not used"]
1875     #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
1876     #[rustc_const_unstable(feature = "const_option_cloned", issue = "91582")]
1877     pub const fn cloned(self) -> Option<T>
1878     where
1879         T: ~const Clone,
1880     {
1881         match self {
1882             Some(t) => Some(t.clone()),
1883             None => None,
1884         }
1885     }
1886 }
1887
1888 impl<T, E> Option<Result<T, E>> {
1889     /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`.
1890     ///
1891     /// [`None`] will be mapped to <code>[Ok]\([None])</code>.
1892     /// <code>[Some]\([Ok]\(\_))</code> and <code>[Some]\([Err]\(\_))</code> will be mapped to
1893     /// <code>[Ok]\([Some]\(\_))</code> and <code>[Err]\(\_)</code>.
1894     ///
1895     /// # Examples
1896     ///
1897     /// ```
1898     /// #[derive(Debug, Eq, PartialEq)]
1899     /// struct SomeErr;
1900     ///
1901     /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1902     /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1903     /// assert_eq!(x, y.transpose());
1904     /// ```
1905     #[inline]
1906     #[stable(feature = "transpose_result", since = "1.33.0")]
1907     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1908     pub const fn transpose(self) -> Result<Option<T>, E> {
1909         match self {
1910             Some(Ok(x)) => Ok(Some(x)),
1911             Some(Err(e)) => Err(e),
1912             None => Ok(None),
1913         }
1914     }
1915 }
1916
1917 // This is a separate function to reduce the code size of .expect() itself.
1918 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
1919 #[cfg_attr(feature = "panic_immediate_abort", inline)]
1920 #[cold]
1921 #[track_caller]
1922 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1923 const fn expect_failed(msg: &str) -> ! {
1924     panic_str(msg)
1925 }
1926
1927 /////////////////////////////////////////////////////////////////////////////
1928 // Trait implementations
1929 /////////////////////////////////////////////////////////////////////////////
1930
1931 #[stable(feature = "rust1", since = "1.0.0")]
1932 #[rustc_const_unstable(feature = "const_clone", issue = "91805")]
1933 impl<T> const Clone for Option<T>
1934 where
1935     T: ~const Clone + ~const Destruct,
1936 {
1937     #[inline]
1938     fn clone(&self) -> Self {
1939         match self {
1940             Some(x) => Some(x.clone()),
1941             None => None,
1942         }
1943     }
1944
1945     #[inline]
1946     fn clone_from(&mut self, source: &Self) {
1947         match (self, source) {
1948             (Some(to), Some(from)) => to.clone_from(from),
1949             (to, from) => *to = from.clone(),
1950         }
1951     }
1952 }
1953
1954 #[stable(feature = "rust1", since = "1.0.0")]
1955 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1956 impl<T> const Default for Option<T> {
1957     /// Returns [`None`][Option::None].
1958     ///
1959     /// # Examples
1960     ///
1961     /// ```
1962     /// let opt: Option<u32> = Option::default();
1963     /// assert!(opt.is_none());
1964     /// ```
1965     #[inline]
1966     fn default() -> Option<T> {
1967         None
1968     }
1969 }
1970
1971 #[stable(feature = "rust1", since = "1.0.0")]
1972 impl<T> IntoIterator for Option<T> {
1973     type Item = T;
1974     type IntoIter = IntoIter<T>;
1975
1976     /// Returns a consuming iterator over the possibly contained value.
1977     ///
1978     /// # Examples
1979     ///
1980     /// ```
1981     /// let x = Some("string");
1982     /// let v: Vec<&str> = x.into_iter().collect();
1983     /// assert_eq!(v, ["string"]);
1984     ///
1985     /// let x = None;
1986     /// let v: Vec<&str> = x.into_iter().collect();
1987     /// assert!(v.is_empty());
1988     /// ```
1989     #[inline]
1990     fn into_iter(self) -> IntoIter<T> {
1991         IntoIter { inner: Item { opt: self } }
1992     }
1993 }
1994
1995 #[stable(since = "1.4.0", feature = "option_iter")]
1996 impl<'a, T> IntoIterator for &'a Option<T> {
1997     type Item = &'a T;
1998     type IntoIter = Iter<'a, T>;
1999
2000     fn into_iter(self) -> Iter<'a, T> {
2001         self.iter()
2002     }
2003 }
2004
2005 #[stable(since = "1.4.0", feature = "option_iter")]
2006 impl<'a, T> IntoIterator for &'a mut Option<T> {
2007     type Item = &'a mut T;
2008     type IntoIter = IterMut<'a, T>;
2009
2010     fn into_iter(self) -> IterMut<'a, T> {
2011         self.iter_mut()
2012     }
2013 }
2014
2015 #[stable(since = "1.12.0", feature = "option_from")]
2016 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
2017 impl<T> const From<T> for Option<T> {
2018     /// Moves `val` into a new [`Some`].
2019     ///
2020     /// # Examples
2021     ///
2022     /// ```
2023     /// let o: Option<u8> = Option::from(67);
2024     ///
2025     /// assert_eq!(Some(67), o);
2026     /// ```
2027     fn from(val: T) -> Option<T> {
2028         Some(val)
2029     }
2030 }
2031
2032 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
2033 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
2034 impl<'a, T> const From<&'a Option<T>> for Option<&'a T> {
2035     /// Converts from `&Option<T>` to `Option<&T>`.
2036     ///
2037     /// # Examples
2038     ///
2039     /// Converts an <code>[Option]<[String]></code> into an <code>[Option]<[usize]></code>, preserving
2040     /// the original. The [`map`] method takes the `self` argument by value, consuming the original,
2041     /// so this technique uses `from` to first take an [`Option`] to a reference
2042     /// to the value inside the original.
2043     ///
2044     /// [`map`]: Option::map
2045     /// [String]: ../../std/string/struct.String.html "String"
2046     ///
2047     /// ```
2048     /// let s: Option<String> = Some(String::from("Hello, Rustaceans!"));
2049     /// let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());
2050     ///
2051     /// println!("Can still print s: {s:?}");
2052     ///
2053     /// assert_eq!(o, Some(18));
2054     /// ```
2055     fn from(o: &'a Option<T>) -> Option<&'a T> {
2056         o.as_ref()
2057     }
2058 }
2059
2060 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
2061 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
2062 impl<'a, T> const From<&'a mut Option<T>> for Option<&'a mut T> {
2063     /// Converts from `&mut Option<T>` to `Option<&mut T>`
2064     ///
2065     /// # Examples
2066     ///
2067     /// ```
2068     /// let mut s = Some(String::from("Hello"));
2069     /// let o: Option<&mut String> = Option::from(&mut s);
2070     ///
2071     /// match o {
2072     ///     Some(t) => *t = String::from("Hello, Rustaceans!"),
2073     ///     None => (),
2074     /// }
2075     ///
2076     /// assert_eq!(s, Some(String::from("Hello, Rustaceans!")));
2077     /// ```
2078     fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
2079         o.as_mut()
2080     }
2081 }
2082
2083 #[stable(feature = "rust1", since = "1.0.0")]
2084 impl<T> crate::marker::StructuralPartialEq for Option<T> {}
2085 #[stable(feature = "rust1", since = "1.0.0")]
2086 impl<T: PartialEq> PartialEq for Option<T> {
2087     #[inline]
2088     fn eq(&self, other: &Self) -> bool {
2089         SpecOptionPartialEq::eq(self, other)
2090     }
2091 }
2092
2093 #[unstable(feature = "spec_option_partial_eq", issue = "none", reason = "exposed only for rustc")]
2094 #[doc(hidden)]
2095 pub trait SpecOptionPartialEq: Sized {
2096     fn eq(l: &Option<Self>, other: &Option<Self>) -> bool;
2097 }
2098
2099 #[unstable(feature = "spec_option_partial_eq", issue = "none", reason = "exposed only for rustc")]
2100 impl<T: PartialEq> SpecOptionPartialEq for T {
2101     #[inline]
2102     default fn eq(l: &Option<T>, r: &Option<T>) -> bool {
2103         match (l, r) {
2104             (Some(l), Some(r)) => *l == *r,
2105             (None, None) => true,
2106             _ => false,
2107         }
2108     }
2109 }
2110
2111 macro_rules! non_zero_option {
2112     ( $( #[$stability: meta] $NZ:ty; )+ ) => {
2113         $(
2114             #[$stability]
2115             impl SpecOptionPartialEq for $NZ {
2116                 #[inline]
2117                 fn eq(l: &Option<Self>, r: &Option<Self>) -> bool {
2118                     l.map(Self::get).unwrap_or(0) == r.map(Self::get).unwrap_or(0)
2119                 }
2120             }
2121         )+
2122     };
2123 }
2124
2125 non_zero_option! {
2126     #[stable(feature = "nonzero", since = "1.28.0")] crate::num::NonZeroU8;
2127     #[stable(feature = "nonzero", since = "1.28.0")] crate::num::NonZeroU16;
2128     #[stable(feature = "nonzero", since = "1.28.0")] crate::num::NonZeroU32;
2129     #[stable(feature = "nonzero", since = "1.28.0")] crate::num::NonZeroU64;
2130     #[stable(feature = "nonzero", since = "1.28.0")] crate::num::NonZeroU128;
2131     #[stable(feature = "nonzero", since = "1.28.0")] crate::num::NonZeroUsize;
2132     #[stable(feature = "signed_nonzero", since = "1.34.0")] crate::num::NonZeroI8;
2133     #[stable(feature = "signed_nonzero", since = "1.34.0")] crate::num::NonZeroI16;
2134     #[stable(feature = "signed_nonzero", since = "1.34.0")] crate::num::NonZeroI32;
2135     #[stable(feature = "signed_nonzero", since = "1.34.0")] crate::num::NonZeroI64;
2136     #[stable(feature = "signed_nonzero", since = "1.34.0")] crate::num::NonZeroI128;
2137     #[stable(feature = "signed_nonzero", since = "1.34.0")] crate::num::NonZeroIsize;
2138 }
2139
2140 #[stable(feature = "nonnull", since = "1.25.0")]
2141 impl<T> SpecOptionPartialEq for crate::ptr::NonNull<T> {
2142     #[inline]
2143     fn eq(l: &Option<Self>, r: &Option<Self>) -> bool {
2144         l.map(Self::as_ptr).unwrap_or_else(|| crate::ptr::null_mut())
2145             == r.map(Self::as_ptr).unwrap_or_else(|| crate::ptr::null_mut())
2146     }
2147 }
2148
2149 /////////////////////////////////////////////////////////////////////////////
2150 // The Option Iterators
2151 /////////////////////////////////////////////////////////////////////////////
2152
2153 #[derive(Clone, Debug)]
2154 struct Item<A> {
2155     opt: Option<A>,
2156 }
2157
2158 impl<A> Iterator for Item<A> {
2159     type Item = A;
2160
2161     #[inline]
2162     fn next(&mut self) -> Option<A> {
2163         self.opt.take()
2164     }
2165
2166     #[inline]
2167     fn size_hint(&self) -> (usize, Option<usize>) {
2168         match self.opt {
2169             Some(_) => (1, Some(1)),
2170             None => (0, Some(0)),
2171         }
2172     }
2173 }
2174
2175 impl<A> DoubleEndedIterator for Item<A> {
2176     #[inline]
2177     fn next_back(&mut self) -> Option<A> {
2178         self.opt.take()
2179     }
2180 }
2181
2182 impl<A> ExactSizeIterator for Item<A> {}
2183 impl<A> FusedIterator for Item<A> {}
2184 unsafe impl<A> TrustedLen for Item<A> {}
2185
2186 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
2187 ///
2188 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
2189 ///
2190 /// This `struct` is created by the [`Option::iter`] function.
2191 #[stable(feature = "rust1", since = "1.0.0")]
2192 #[derive(Debug)]
2193 pub struct Iter<'a, A: 'a> {
2194     inner: Item<&'a A>,
2195 }
2196
2197 #[stable(feature = "rust1", since = "1.0.0")]
2198 impl<'a, A> Iterator for Iter<'a, A> {
2199     type Item = &'a A;
2200
2201     #[inline]
2202     fn next(&mut self) -> Option<&'a A> {
2203         self.inner.next()
2204     }
2205     #[inline]
2206     fn size_hint(&self) -> (usize, Option<usize>) {
2207         self.inner.size_hint()
2208     }
2209 }
2210
2211 #[stable(feature = "rust1", since = "1.0.0")]
2212 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
2213     #[inline]
2214     fn next_back(&mut self) -> Option<&'a A> {
2215         self.inner.next_back()
2216     }
2217 }
2218
2219 #[stable(feature = "rust1", since = "1.0.0")]
2220 impl<A> ExactSizeIterator for Iter<'_, A> {}
2221
2222 #[stable(feature = "fused", since = "1.26.0")]
2223 impl<A> FusedIterator for Iter<'_, A> {}
2224
2225 #[unstable(feature = "trusted_len", issue = "37572")]
2226 unsafe impl<A> TrustedLen for Iter<'_, A> {}
2227
2228 #[stable(feature = "rust1", since = "1.0.0")]
2229 impl<A> Clone for Iter<'_, A> {
2230     #[inline]
2231     fn clone(&self) -> Self {
2232         Iter { inner: self.inner.clone() }
2233     }
2234 }
2235
2236 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
2237 ///
2238 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
2239 ///
2240 /// This `struct` is created by the [`Option::iter_mut`] function.
2241 #[stable(feature = "rust1", since = "1.0.0")]
2242 #[derive(Debug)]
2243 pub struct IterMut<'a, A: 'a> {
2244     inner: Item<&'a mut A>,
2245 }
2246
2247 #[stable(feature = "rust1", since = "1.0.0")]
2248 impl<'a, A> Iterator for IterMut<'a, A> {
2249     type Item = &'a mut A;
2250
2251     #[inline]
2252     fn next(&mut self) -> Option<&'a mut A> {
2253         self.inner.next()
2254     }
2255     #[inline]
2256     fn size_hint(&self) -> (usize, Option<usize>) {
2257         self.inner.size_hint()
2258     }
2259 }
2260
2261 #[stable(feature = "rust1", since = "1.0.0")]
2262 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
2263     #[inline]
2264     fn next_back(&mut self) -> Option<&'a mut A> {
2265         self.inner.next_back()
2266     }
2267 }
2268
2269 #[stable(feature = "rust1", since = "1.0.0")]
2270 impl<A> ExactSizeIterator for IterMut<'_, A> {}
2271
2272 #[stable(feature = "fused", since = "1.26.0")]
2273 impl<A> FusedIterator for IterMut<'_, A> {}
2274 #[unstable(feature = "trusted_len", issue = "37572")]
2275 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
2276
2277 /// An iterator over the value in [`Some`] variant of an [`Option`].
2278 ///
2279 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
2280 ///
2281 /// This `struct` is created by the [`Option::into_iter`] function.
2282 #[derive(Clone, Debug)]
2283 #[stable(feature = "rust1", since = "1.0.0")]
2284 pub struct IntoIter<A> {
2285     inner: Item<A>,
2286 }
2287
2288 #[stable(feature = "rust1", since = "1.0.0")]
2289 impl<A> Iterator for IntoIter<A> {
2290     type Item = A;
2291
2292     #[inline]
2293     fn next(&mut self) -> Option<A> {
2294         self.inner.next()
2295     }
2296     #[inline]
2297     fn size_hint(&self) -> (usize, Option<usize>) {
2298         self.inner.size_hint()
2299     }
2300 }
2301
2302 #[stable(feature = "rust1", since = "1.0.0")]
2303 impl<A> DoubleEndedIterator for IntoIter<A> {
2304     #[inline]
2305     fn next_back(&mut self) -> Option<A> {
2306         self.inner.next_back()
2307     }
2308 }
2309
2310 #[stable(feature = "rust1", since = "1.0.0")]
2311 impl<A> ExactSizeIterator for IntoIter<A> {}
2312
2313 #[stable(feature = "fused", since = "1.26.0")]
2314 impl<A> FusedIterator for IntoIter<A> {}
2315
2316 #[unstable(feature = "trusted_len", issue = "37572")]
2317 unsafe impl<A> TrustedLen for IntoIter<A> {}
2318
2319 /////////////////////////////////////////////////////////////////////////////
2320 // FromIterator
2321 /////////////////////////////////////////////////////////////////////////////
2322
2323 #[stable(feature = "rust1", since = "1.0.0")]
2324 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
2325     /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
2326     /// no further elements are taken, and the [`None`][Option::None] is
2327     /// returned. Should no [`None`][Option::None] occur, a container of type
2328     /// `V` containing the values of each [`Option`] is returned.
2329     ///
2330     /// # Examples
2331     ///
2332     /// Here is an example which increments every integer in a vector.
2333     /// We use the checked variant of `add` that returns `None` when the
2334     /// calculation would result in an overflow.
2335     ///
2336     /// ```
2337     /// let items = vec![0_u16, 1, 2];
2338     ///
2339     /// let res: Option<Vec<u16>> = items
2340     ///     .iter()
2341     ///     .map(|x| x.checked_add(1))
2342     ///     .collect();
2343     ///
2344     /// assert_eq!(res, Some(vec![1, 2, 3]));
2345     /// ```
2346     ///
2347     /// As you can see, this will return the expected, valid items.
2348     ///
2349     /// Here is another example that tries to subtract one from another list
2350     /// of integers, this time checking for underflow:
2351     ///
2352     /// ```
2353     /// let items = vec![2_u16, 1, 0];
2354     ///
2355     /// let res: Option<Vec<u16>> = items
2356     ///     .iter()
2357     ///     .map(|x| x.checked_sub(1))
2358     ///     .collect();
2359     ///
2360     /// assert_eq!(res, None);
2361     /// ```
2362     ///
2363     /// Since the last element is zero, it would underflow. Thus, the resulting
2364     /// value is `None`.
2365     ///
2366     /// Here is a variation on the previous example, showing that no
2367     /// further elements are taken from `iter` after the first `None`.
2368     ///
2369     /// ```
2370     /// let items = vec![3_u16, 2, 1, 10];
2371     ///
2372     /// let mut shared = 0;
2373     ///
2374     /// let res: Option<Vec<u16>> = items
2375     ///     .iter()
2376     ///     .map(|x| { shared += x; x.checked_sub(2) })
2377     ///     .collect();
2378     ///
2379     /// assert_eq!(res, None);
2380     /// assert_eq!(shared, 6);
2381     /// ```
2382     ///
2383     /// Since the third element caused an underflow, no further elements were taken,
2384     /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
2385     #[inline]
2386     fn from_iter<I: IntoIterator<Item = Option<A>>>(iter: I) -> Option<V> {
2387         // FIXME(#11084): This could be replaced with Iterator::scan when this
2388         // performance bug is closed.
2389
2390         iter::try_process(iter.into_iter(), |i| i.collect())
2391     }
2392 }
2393
2394 #[unstable(feature = "try_trait_v2", issue = "84277")]
2395 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
2396 impl<T> const ops::Try for Option<T> {
2397     type Output = T;
2398     type Residual = Option<convert::Infallible>;
2399
2400     #[inline]
2401     fn from_output(output: Self::Output) -> Self {
2402         Some(output)
2403     }
2404
2405     #[inline]
2406     fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
2407         match self {
2408             Some(v) => ControlFlow::Continue(v),
2409             None => ControlFlow::Break(None),
2410         }
2411     }
2412 }
2413
2414 #[unstable(feature = "try_trait_v2", issue = "84277")]
2415 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
2416 impl<T> const ops::FromResidual for Option<T> {
2417     #[inline]
2418     fn from_residual(residual: Option<convert::Infallible>) -> Self {
2419         match residual {
2420             None => None,
2421         }
2422     }
2423 }
2424
2425 #[unstable(feature = "try_trait_v2_yeet", issue = "96374")]
2426 impl<T> ops::FromResidual<ops::Yeet<()>> for Option<T> {
2427     #[inline]
2428     fn from_residual(ops::Yeet(()): ops::Yeet<()>) -> Self {
2429         None
2430     }
2431 }
2432
2433 #[unstable(feature = "try_trait_v2_residual", issue = "91285")]
2434 #[rustc_const_unstable(feature = "const_try", issue = "74935")]
2435 impl<T> const ops::Residual<T> for Option<convert::Infallible> {
2436     type TryType = Option<T>;
2437 }
2438
2439 impl<T> Option<Option<T>> {
2440     /// Converts from `Option<Option<T>>` to `Option<T>`.
2441     ///
2442     /// # Examples
2443     ///
2444     /// Basic usage:
2445     ///
2446     /// ```
2447     /// let x: Option<Option<u32>> = Some(Some(6));
2448     /// assert_eq!(Some(6), x.flatten());
2449     ///
2450     /// let x: Option<Option<u32>> = Some(None);
2451     /// assert_eq!(None, x.flatten());
2452     ///
2453     /// let x: Option<Option<u32>> = None;
2454     /// assert_eq!(None, x.flatten());
2455     /// ```
2456     ///
2457     /// Flattening only removes one level of nesting at a time:
2458     ///
2459     /// ```
2460     /// let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
2461     /// assert_eq!(Some(Some(6)), x.flatten());
2462     /// assert_eq!(Some(6), x.flatten().flatten());
2463     /// ```
2464     #[inline]
2465     #[stable(feature = "option_flattening", since = "1.40.0")]
2466     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
2467     pub const fn flatten(self) -> Option<T> {
2468         match self {
2469             Some(inner) => inner,
2470             None => None,
2471         }
2472     }
2473 }