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