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