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