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