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