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