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:
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
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
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.
23 //! fn divide(numerator: f64, denominator: f64) -> Option<f64> {
24 //! if denominator == 0.0 {
27 //! Some(numerator / denominator)
31 //! // The return value of the function is an option
32 //! let result = divide(2.0, 3.0);
34 //! // Pattern match to retrieve the value
36 //! // The division was valid
37 //! Some(x) => println!("Result: {}", x),
38 //! // The division was invalid
39 //! None => println!("Cannot divide by 0"),
44 // FIXME: Show how `Option` is used in practice, with lots of methods
46 //! # Options and pointers ("nullable" pointers)
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>.
52 //! [Box\<T>]: ../../std/boxed/struct.Box.html
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
61 //! let optional = None;
62 //! check_optional(optional);
64 //! let optional = Some(Box::new(9000));
65 //! check_optional(optional);
67 //! fn check_optional(optional: Option<Box<i32>>) {
69 //! Some(p) => println!("has value {}", p),
70 //! None => println!("has no value"),
77 //! Rust guarantees to optimize the following types `T` such that
78 //! [`Option<T>`] has the same size as `T`:
83 //! * `fn`, `extern "C" fn`
84 //! * [`num::NonZero*`]
85 //! * [`ptr::NonNull<U>`]
86 //! * `#[repr(transparent)]` struct around one of the types in this list.
88 //! [`Box<U>`]: ../../std/boxed/struct.Box.html
89 //! [`num::NonZero*`]: crate::num
90 //! [`ptr::NonNull<U>`]: crate::ptr::NonNull
92 //! This is called the "null pointer optimization" or NPO.
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).
101 //! In addition to working with pattern matching, [`Option`] provides a wide
102 //! variety of different methods.
104 //! ## Querying the variant
106 //! The [`is_some`] and [`is_none`] methods return [`true`] if the [`Option`]
107 //! is [`Some`] or [`None`], respectively.
109 //! [`is_none`]: Option::is_none
110 //! [`is_some`]: Option::is_some
112 //! ## Adapters for working with references
114 //! * [`as_ref`] converts from <code>[&][][Option]\<T></code> to <code>[Option]<[&]T></code>
115 //! * [`as_mut`] converts from <code>[&mut] [Option]\<T></code> to <code>[Option]<[&mut] T></code>
116 //! * [`as_deref`] converts from <code>[&][][Option]\<T></code> to
117 //! <code>[Option]<[&]T::[Target]></code>
118 //! * [`as_deref_mut`] converts from <code>[&mut] [Option]\<T></code> to
119 //! <code>[Option]<[&mut] T::[Target]></code>
120 //! * [`as_pin_ref`] converts from <code>[Pin]<[&][][Option]\<T>></code> to
121 //! <code>[Option]<[Pin]<[&]T>></code>
122 //! * [`as_pin_mut`] converts from <code>[Pin]<[&mut] [Option]\<T>></code> to
123 //! <code>[Option]<[Pin]<[&mut] T>></code>
125 //! [&]: reference "shared reference"
126 //! [&mut]: reference "mutable reference"
127 //! [Target]: Deref::Target "ops::Deref::Target"
128 //! [`as_deref`]: Option::as_deref
129 //! [`as_deref_mut`]: Option::as_deref_mut
130 //! [`as_mut`]: Option::as_mut
131 //! [`as_pin_mut`]: Option::as_pin_mut
132 //! [`as_pin_ref`]: Option::as_pin_ref
133 //! [`as_ref`]: Option::as_ref
135 //! ## Extracting the contained value
137 //! These methods extract the contained value in an [`Option<T>`] when it
138 //! is the [`Some`] variant. If the [`Option`] is [`None`]:
140 //! * [`expect`] panics with a provided custom message
141 //! * [`unwrap`] panics with a generic message
142 //! * [`unwrap_or`] returns the provided default value
143 //! * [`unwrap_or_default`] returns the default value of the type `T`
144 //! (which must implement the [`Default`] trait)
145 //! * [`unwrap_or_else`] returns the result of evaluating the provided
148 //! [`expect`]: Option::expect
149 //! [`unwrap`]: Option::unwrap
150 //! [`unwrap_or`]: Option::unwrap_or
151 //! [`unwrap_or_default`]: Option::unwrap_or_default
152 //! [`unwrap_or_else`]: Option::unwrap_or_else
154 //! ## Transforming contained values
156 //! These methods transform [`Option`] to [`Result`]:
158 //! * [`ok_or`] transforms [`Some(v)`] to [`Ok(v)`], and [`None`] to
159 //! [`Err(err)`] using the provided default `err` value
160 //! * [`ok_or_else`] transforms [`Some(v)`] to [`Ok(v)`], and [`None`] to
161 //! a value of [`Err`] using the provided function
162 //! * [`transpose`] transposes an [`Option`] of a [`Result`] into a
163 //! [`Result`] of an [`Option`]
165 //! [`Err(err)`]: Err
167 //! [`Some(v)`]: Some
168 //! [`ok_or`]: Option::ok_or
169 //! [`ok_or_else`]: Option::ok_or_else
170 //! [`transpose`]: Option::transpose
172 //! These methods transform the [`Some`] variant:
174 //! * [`filter`] calls the provided predicate function on the contained
175 //! value `t` if the [`Option`] is [`Some(t)`], and returns [`Some(t)`]
176 //! if the function returns `true`; otherwise, returns [`None`]
177 //! * [`flatten`] removes one level of nesting from an
178 //! [`Option<Option<T>>`]
179 //! * [`map`] transforms [`Option<T>`] to [`Option<U>`] by applying the
180 //! provided function to the contained value of [`Some`] and leaving
181 //! [`None`] values unchanged
183 //! [`Some(t)`]: Some
184 //! [`filter`]: Option::filter
185 //! [`flatten`]: Option::flatten
186 //! [`map`]: Option::map
188 //! These methods transform [`Option<T>`] to a value of a possibly
189 //! different type `U`:
191 //! * [`map_or`] applies the provided function to the contained value of
192 //! [`Some`], or returns the provided default value if the [`Option`] is
194 //! * [`map_or_else`] applies the provided function to the contained value
195 //! of [`Some`], or returns the result of evaluating the provided
196 //! fallback function if the [`Option`] is [`None`]
198 //! [`map_or`]: Option::map_or
199 //! [`map_or_else`]: Option::map_or_else
201 //! These methods combine the [`Some`] variants of two [`Option`] values:
203 //! * [`zip`] returns [`Some((s, o))`] if `self` is [`Some(s)`] and the
204 //! provided [`Option`] value is [`Some(o)`]; otherwise, returns [`None`]
205 //! * [`zip_with`] calls the provided function `f` and returns
206 //! [`Some(f(s, o))`] if `self` is [`Some(s)`] and the provided
207 //! [`Option`] value is [`Some(o)`]; otherwise, returns [`None`]
209 //! [`Some(f(s, o))`]: Some
210 //! [`Some(o)`]: Some
211 //! [`Some(s)`]: Some
212 //! [`Some((s, o))`]: Some
213 //! [`zip`]: Option::zip
214 //! [`zip_with`]: Option::zip_with
216 //! ## Boolean operators
218 //! These methods treat the [`Option`] as a boolean value, where [`Some`]
219 //! acts like [`true`] and [`None`] acts like [`false`]. There are two
220 //! categories of these methods: ones that take an [`Option`] as input, and
221 //! ones that take a function as input (to be lazily evaluated).
223 //! The [`and`], [`or`], and [`xor`] methods take another [`Option`] as
224 //! input, and produce an [`Option`] as output. Only the [`and`] method can
225 //! produce an [`Option<U>`] value having a different inner type `U` than
228 //! | method | self | input | output |
229 //! |---------|-----------|-----------|-----------|
230 //! | [`and`] | `None` | (ignored) | `None` |
231 //! | [`and`] | `Some(x)` | `None` | `None` |
232 //! | [`and`] | `Some(x)` | `Some(y)` | `Some(y)` |
233 //! | [`or`] | `None` | `None` | `None` |
234 //! | [`or`] | `None` | `Some(y)` | `Some(y)` |
235 //! | [`or`] | `Some(x)` | (ignored) | `Some(x)` |
236 //! | [`xor`] | `None` | `None` | `None` |
237 //! | [`xor`] | `None` | `Some(y)` | `Some(y)` |
238 //! | [`xor`] | `Some(x)` | `None` | `Some(x)` |
239 //! | [`xor`] | `Some(x)` | `Some(y)` | `None` |
241 //! [`and`]: Option::and
242 //! [`or`]: Option::or
243 //! [`xor`]: Option::xor
245 //! The [`and_then`] and [`or_else`] methods take a function as input, and
246 //! only evaluate the function when they need to produce a new value. Only
247 //! the [`and_then`] method can produce an [`Option<U>`] value having a
248 //! different inner type `U` than [`Option<T>`].
250 //! | method | self | function input | function result | output |
251 //! |--------------|-----------|----------------|-----------------|-----------|
252 //! | [`and_then`] | `None` | (not provided) | (not evaluated) | `None` |
253 //! | [`and_then`] | `Some(x)` | `x` | `None` | `None` |
254 //! | [`and_then`] | `Some(x)` | `x` | `Some(y)` | `Some(y)` |
255 //! | [`or_else`] | `None` | (not provided) | `None` | `None` |
256 //! | [`or_else`] | `None` | (not provided) | `Some(y)` | `Some(y)` |
257 //! | [`or_else`] | `Some(x)` | (not provided) | (not evaluated) | `Some(x)` |
259 //! [`and_then`]: Option::and_then
260 //! [`or_else`]: Option::or_else
262 //! This is an example of using methods like [`and_then`] and [`or`] in a
263 //! pipeline of method calls. Early stages of the pipeline pass failure
264 //! values ([`None`]) through unchanged, and continue processing on
265 //! success values ([`Some`]). Toward the end, [`or`] substitutes an error
266 //! message if it receives [`None`].
269 //! # use std::collections::BTreeMap;
270 //! let mut bt = BTreeMap::new();
271 //! bt.insert(20u8, "foo");
272 //! bt.insert(42u8, "bar");
273 //! let res = vec![0u8, 1, 11, 200, 22]
276 //! // `checked_sub()` returns `None` on error
278 //! // same with `checked_mul()`
279 //! .and_then(|x| x.checked_mul(2))
280 //! // `BTreeMap::get` returns `None` on error
281 //! .and_then(|x| bt.get(&x))
282 //! // Substitute an error message if we have `None` so far
283 //! .or(Some(&"error!"))
285 //! // Won't panic because we unconditionally used `Some` above
288 //! .collect::<Vec<_>>();
289 //! assert_eq!(res, ["error!", "error!", "foo", "error!", "bar"]);
292 //! ## Comparison operators
294 //! If `T` implements [`PartialOrd`] then [`Option<T>`] will derive its
295 //! [`PartialOrd`] implementation. With this order, [`None`] compares as
296 //! less than any [`Some`], and two [`Some`] compare the same way as their
297 //! contained values would in `T`. If `T` also implements
298 //! [`Ord`], then so does [`Option<T>`].
301 //! assert!(None < Some(0));
302 //! assert!(Some(0) < Some(1));
305 //! ## Iterating over `Option`
307 //! An [`Option`] can be iterated over. This can be helpful if you need an
308 //! iterator that is conditionally empty. The iterator will either produce
309 //! a single value (when the [`Option`] is [`Some`]), or produce no values
310 //! (when the [`Option`] is [`None`]). For example, [`into_iter`] acts like
311 //! [`once(v)`] if the [`Option`] is [`Some(v)`], and like [`empty()`] if
312 //! the [`Option`] is [`None`].
314 //! [`Some(v)`]: Some
315 //! [`empty()`]: crate::iter::empty
316 //! [`once(v)`]: crate::iter::once
318 //! Iterators over [`Option<T>`] come in three types:
320 //! * [`into_iter`] consumes the [`Option`] and produces the contained
322 //! * [`iter`] produces an immutable reference of type `&T` to the
324 //! * [`iter_mut`] produces a mutable reference of type `&mut T` to the
327 //! [`into_iter`]: Option::into_iter
328 //! [`iter`]: Option::iter
329 //! [`iter_mut`]: Option::iter_mut
331 //! An iterator over [`Option`] can be useful when chaining iterators, for
332 //! example, to conditionally insert items. (It's not always necessary to
333 //! explicitly call an iterator constructor: many [`Iterator`] methods that
334 //! accept other iterators will also accept iterable types that implement
335 //! [`IntoIterator`], which includes [`Option`].)
338 //! let yep = Some(42);
340 //! // chain() already calls into_iter(), so we don't have to do so
341 //! let nums: Vec<i32> = (0..4).chain(yep).chain(4..8).collect();
342 //! assert_eq!(nums, [0, 1, 2, 3, 42, 4, 5, 6, 7]);
343 //! let nums: Vec<i32> = (0..4).chain(nope).chain(4..8).collect();
344 //! assert_eq!(nums, [0, 1, 2, 3, 4, 5, 6, 7]);
347 //! One reason to chain iterators in this way is that a function returning
348 //! `impl Iterator` must have all possible return values be of the same
349 //! concrete type. Chaining an iterated [`Option`] can help with that.
352 //! fn make_iter(do_insert: bool) -> impl Iterator<Item = i32> {
353 //! // Explicit returns to illustrate return types matching
354 //! match do_insert {
355 //! true => return (0..4).chain(Some(42)).chain(4..8),
356 //! false => return (0..4).chain(None).chain(4..8),
359 //! println!("{:?}", make_iter(true).collect::<Vec<_>>());
360 //! println!("{:?}", make_iter(false).collect::<Vec<_>>());
363 //! If we try to do the same thing, but using [`once()`] and [`empty()`],
364 //! we can't return `impl Iterator` anymore because the concrete types of
365 //! the return values differ.
367 //! [`empty()`]: crate::iter::empty
368 //! [`once()`]: crate::iter::once
370 //! ```compile_fail,E0308
371 //! # use std::iter::{empty, once};
372 //! // This won't compile because all possible returns from the function
373 //! // must have the same concrete type.
374 //! fn make_iter(do_insert: bool) -> impl Iterator<Item = i32> {
375 //! // Explicit returns to illustrate return types not matching
376 //! match do_insert {
377 //! true => return (0..4).chain(once(42)).chain(4..8),
378 //! false => return (0..4).chain(empty()).chain(4..8),
383 //! ## Collecting into `Option`
385 //! [`Option`] implements the [`FromIterator`][impl-FromIterator] trait,
386 //! which allows an iterator over [`Option`] values to be collected into an
387 //! [`Option`] of a collection of each contained value of the original
388 //! [`Option`] values, or [`None`] if any of the elements was [`None`].
390 //! [impl-FromIterator]: Option#impl-FromIterator%3COption%3CA%3E%3E
393 //! let v = vec![Some(2), Some(4), None, Some(8)];
394 //! let res: Option<Vec<_>> = v.into_iter().collect();
395 //! assert_eq!(res, None);
396 //! let v = vec![Some(2), Some(4), Some(8)];
397 //! let res: Option<Vec<_>> = v.into_iter().collect();
398 //! assert_eq!(res, Some(vec![2, 4, 8]));
401 //! [`Option`] also implements the [`Product`][impl-Product] and
402 //! [`Sum`][impl-Sum] traits, allowing an iterator over [`Option`] values
403 //! to provide the [`product`][Iterator::product] and
404 //! [`sum`][Iterator::sum] methods.
406 //! [impl-Product]: Option#impl-Product%3COption%3CU%3E%3E
407 //! [impl-Sum]: Option#impl-Sum%3COption%3CU%3E%3E
410 //! let v = vec![None, Some(1), Some(2), Some(3)];
411 //! let res: Option<i32> = v.into_iter().sum();
412 //! assert_eq!(res, None);
413 //! let v = vec![Some(1), Some(2), Some(21)];
414 //! let res: Option<i32> = v.into_iter().product();
415 //! assert_eq!(res, Some(42));
418 //! ## Modifying an [`Option`] in-place
420 //! These methods return a mutable reference to the contained value of an
423 //! * [`insert`] inserts a value, dropping any old contents
424 //! * [`get_or_insert`] gets the current value, inserting a provided
425 //! default value if it is [`None`]
426 //! * [`get_or_insert_default`] gets the current value, inserting the
427 //! default value of type `T` (which must implement [`Default`]) if it is
429 //! * [`get_or_insert_with`] gets the current value, inserting a default
430 //! computed by the provided function if it is [`None`]
432 //! [`get_or_insert`]: Option::get_or_insert
433 //! [`get_or_insert_default`]: Option::get_or_insert_default
434 //! [`get_or_insert_with`]: Option::get_or_insert_with
435 //! [`insert`]: Option::insert
437 //! These methods transfer ownership of the contained value of an
440 //! * [`take`] takes ownership of the contained value of an [`Option`], if
441 //! any, replacing the [`Option`] with [`None`]
442 //! * [`replace`] takes ownership of the contained value of an [`Option`],
443 //! if any, replacing the [`Option`] with a [`Some`] containing the
446 //! [`replace`]: Option::replace
447 //! [`take`]: Option::take
451 //! Basic pattern matching on [`Option`]:
454 //! let msg = Some("howdy");
456 //! // Take a reference to the contained string
457 //! if let Some(m) = &msg {
458 //! println!("{}", *m);
461 //! // Remove the contained string, destroying the Option
462 //! let unwrapped_msg = msg.unwrap_or("default message");
465 //! Initialize a result to [`None`] before a loop:
468 //! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) }
470 //! // A list of data to search through.
471 //! let all_the_big_things = [
472 //! Kingdom::Plant(250, "redwood"),
473 //! Kingdom::Plant(230, "noble fir"),
474 //! Kingdom::Plant(229, "sugar pine"),
475 //! Kingdom::Animal(25, "blue whale"),
476 //! Kingdom::Animal(19, "fin whale"),
477 //! Kingdom::Animal(15, "north pacific right whale"),
480 //! // We're going to search for the name of the biggest animal,
481 //! // but to start with we've just got `None`.
482 //! let mut name_of_biggest_animal = None;
483 //! let mut size_of_biggest_animal = 0;
484 //! for big_thing in &all_the_big_things {
485 //! match *big_thing {
486 //! Kingdom::Animal(size, name) if size > size_of_biggest_animal => {
487 //! // Now we've found the name of some big animal
488 //! size_of_biggest_animal = size;
489 //! name_of_biggest_animal = Some(name);
491 //! Kingdom::Animal(..) | Kingdom::Plant(..) => ()
495 //! match name_of_biggest_animal {
496 //! Some(name) => println!("the biggest animal is {}", name),
497 //! None => println!("there are no animals :("),
501 #![stable(feature = "rust1", since = "1.0.0")]
503 use crate::iter::{FromIterator, FusedIterator, TrustedLen};
507 ops::{self, ControlFlow, Deref, DerefMut},
510 /// The `Option` type. See [the module level documentation](self) for more.
511 #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
512 #[rustc_diagnostic_item = "Option"]
513 #[stable(feature = "rust1", since = "1.0.0")]
517 #[stable(feature = "rust1", since = "1.0.0")]
519 /// Some value of type `T`.
521 #[stable(feature = "rust1", since = "1.0.0")]
522 Some(#[stable(feature = "rust1", since = "1.0.0")] T),
525 /////////////////////////////////////////////////////////////////////////////
526 // Type implementation
527 /////////////////////////////////////////////////////////////////////////////
530 /////////////////////////////////////////////////////////////////////////
531 // Querying the contained values
532 /////////////////////////////////////////////////////////////////////////
534 /// Returns `true` if the option is a [`Some`] value.
539 /// let x: Option<u32> = Some(2);
540 /// assert_eq!(x.is_some(), true);
542 /// let x: Option<u32> = None;
543 /// assert_eq!(x.is_some(), false);
545 #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"]
547 #[stable(feature = "rust1", since = "1.0.0")]
548 #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
549 pub const fn is_some(&self) -> bool {
550 matches!(*self, Some(_))
553 /// Returns `true` if the option is a [`None`] value.
558 /// let x: Option<u32> = Some(2);
559 /// assert_eq!(x.is_none(), false);
561 /// let x: Option<u32> = None;
562 /// assert_eq!(x.is_none(), true);
564 #[must_use = "if you intended to assert that this doesn't have a value, consider \
565 `.and_then(|_| panic!(\"`Option` had a value when expected `None`\"))` instead"]
567 #[stable(feature = "rust1", since = "1.0.0")]
568 #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
569 pub const fn is_none(&self) -> bool {
573 /// Returns `true` if the option is a [`Some`] value containing the given value.
578 /// #![feature(option_result_contains)]
580 /// let x: Option<u32> = Some(2);
581 /// assert_eq!(x.contains(&2), true);
583 /// let x: Option<u32> = Some(3);
584 /// assert_eq!(x.contains(&2), false);
586 /// let x: Option<u32> = None;
587 /// assert_eq!(x.contains(&2), false);
591 #[unstable(feature = "option_result_contains", issue = "62358")]
592 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
593 pub const fn contains<U>(&self, x: &U) -> bool
595 U: ~const PartialEq<T>,
603 /////////////////////////////////////////////////////////////////////////
604 // Adapter for working with references
605 /////////////////////////////////////////////////////////////////////////
607 /// Converts from `&Option<T>` to `Option<&T>`.
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.
616 /// [`map`]: Option::map
617 /// [String]: ../../std/string/struct.String.html "String"
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);
627 #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
628 #[stable(feature = "rust1", since = "1.0.0")]
629 pub const fn as_ref(&self) -> Option<&T> {
631 Some(ref x) => Some(x),
636 /// Converts from `&mut Option<T>` to `Option<&mut T>`.
641 /// let mut x = Some(2);
642 /// match x.as_mut() {
643 /// Some(v) => *v = 42,
646 /// assert_eq!(x, Some(42));
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> {
653 Some(ref mut x) => Some(x),
658 /// Converts from <code>[Pin]<[&]Option\<T>></code> to <code>Option<[Pin]<[&]T>></code>.
660 /// [&]: reference "shared reference"
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`
669 Some(x) => unsafe { Some(Pin::new_unchecked(x)) },
674 /// Converts from <code>[Pin]<[&mut] Option\<T>></code> to <code>Option<[Pin]<[&mut] T>></code>.
676 /// [&mut]: reference "mutable reference"
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.
685 match Pin::get_unchecked_mut(self).as_mut() {
686 Some(x) => Some(Pin::new_unchecked(x)),
692 /////////////////////////////////////////////////////////////////////////
693 // Getting to contained values
694 /////////////////////////////////////////////////////////////////////////
696 /// Returns the contained [`Some`] value, consuming the `self` value.
700 /// Panics if the value is a [`None`] with a custom panic message provided by
706 /// let x = Some("value");
707 /// assert_eq!(x.expect("fruits are healthy"), "value");
711 /// let x: Option<&str> = None;
712 /// x.expect("fruits are healthy"); // panics with `fruits are healthy`
716 #[stable(feature = "rust1", since = "1.0.0")]
717 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
718 pub const fn expect(self, msg: &str) -> T {
721 None => expect_failed(msg),
725 /// Returns the contained [`Some`] value, consuming the `self` value.
727 /// Because this function may panic, its use is generally discouraged.
728 /// Instead, prefer to use pattern matching and handle the [`None`]
729 /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
730 /// [`unwrap_or_default`].
732 /// [`unwrap_or`]: Option::unwrap_or
733 /// [`unwrap_or_else`]: Option::unwrap_or_else
734 /// [`unwrap_or_default`]: Option::unwrap_or_default
738 /// Panics if the self value equals [`None`].
743 /// let x = Some("air");
744 /// assert_eq!(x.unwrap(), "air");
748 /// let x: Option<&str> = None;
749 /// assert_eq!(x.unwrap(), "air"); // fails
753 #[stable(feature = "rust1", since = "1.0.0")]
754 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
755 pub const fn unwrap(self) -> T {
758 None => panic!("called `Option::unwrap()` on a `None` value"),
762 /// Returns the contained [`Some`] value or a provided default.
764 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
765 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
766 /// which is lazily evaluated.
768 /// [`unwrap_or_else`]: Option::unwrap_or_else
773 /// assert_eq!(Some("car").unwrap_or("bike"), "car");
774 /// assert_eq!(None.unwrap_or("bike"), "bike");
777 #[stable(feature = "rust1", since = "1.0.0")]
778 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
779 pub const fn unwrap_or(self, default: T) -> T
789 /// Returns the contained [`Some`] value or computes it from a closure.
795 /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
796 /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
799 #[stable(feature = "rust1", since = "1.0.0")]
800 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
801 pub const fn unwrap_or_else<F>(self, f: F) -> T
803 F: ~const FnOnce() -> T,
812 /// Returns the contained [`Some`] value, consuming the `self` value,
813 /// without checking that the value is not [`None`].
817 /// Calling this method on [`None`] is *[undefined behavior]*.
819 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
824 /// let x = Some("air");
825 /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air");
829 /// let x: Option<&str> = None;
830 /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air"); // Undefined behavior!
834 #[stable(feature = "option_result_unwrap_unchecked", since = "1.58.0")]
835 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
836 pub const unsafe fn unwrap_unchecked(self) -> T {
837 debug_assert!(self.is_some());
840 // SAFETY: the safety contract must be upheld by the caller.
841 None => unsafe { hint::unreachable_unchecked() },
845 /////////////////////////////////////////////////////////////////////////
846 // Transforming contained values
847 /////////////////////////////////////////////////////////////////////////
849 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
853 /// Converts an <code>Option<[String]></code> into an <code>Option<[usize]></code>, consuming
856 /// [String]: ../../std/string/struct.String.html "String"
858 /// let maybe_some_string = Some(String::from("Hello, World!"));
859 /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
860 /// let maybe_some_len = maybe_some_string.map(|s| s.len());
862 /// assert_eq!(maybe_some_len, Some(13));
865 #[stable(feature = "rust1", since = "1.0.0")]
866 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
867 pub const fn map<U, F>(self, f: F) -> Option<U>
869 F: ~const FnOnce(T) -> U,
873 Some(x) => Some(f(x)),
878 /// Calls the provided closure with a reference to the contained value (if [`Some`]).
883 /// #![feature(result_option_inspect)]
885 /// let v = vec![1, 2, 3, 4, 5];
887 /// // prints "got: 4"
888 /// let x: Option<&usize> = v.get(3).inspect(|x| println!("got: {}", x));
890 /// // prints nothing
891 /// let x: Option<&usize> = v.get(5).inspect(|x| println!("got: {}", x));
894 #[unstable(feature = "result_option_inspect", issue = "91345")]
895 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
896 pub const fn inspect<F>(self, f: F) -> Self
898 F: ~const FnOnce(&T),
901 if let Some(ref x) = self {
908 /// Returns the provided default result (if none),
909 /// or applies a function to the contained value (if any).
911 /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
912 /// the result of a function call, it is recommended to use [`map_or_else`],
913 /// which is lazily evaluated.
915 /// [`map_or_else`]: Option::map_or_else
920 /// let x = Some("foo");
921 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
923 /// let x: Option<&str> = None;
924 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
927 #[stable(feature = "rust1", since = "1.0.0")]
928 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
929 pub const fn map_or<U, F>(self, default: U, f: F) -> U
931 F: ~const FnOnce(T) -> U,
941 /// Computes a default function result (if none), or
942 /// applies a different function to the contained value (if any).
949 /// let x = Some("foo");
950 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
952 /// let x: Option<&str> = None;
953 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
956 #[stable(feature = "rust1", since = "1.0.0")]
957 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
958 pub const fn map_or_else<U, D, F>(self, default: D, f: F) -> U
960 D: ~const FnOnce() -> U,
962 F: ~const FnOnce(T) -> U,
971 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
972 /// [`Ok(v)`] and [`None`] to [`Err(err)`].
974 /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
975 /// result of a function call, it is recommended to use [`ok_or_else`], which is
976 /// lazily evaluated.
979 /// [`Err(err)`]: Err
980 /// [`Some(v)`]: Some
981 /// [`ok_or_else`]: Option::ok_or_else
986 /// let x = Some("foo");
987 /// assert_eq!(x.ok_or(0), Ok("foo"));
989 /// let x: Option<&str> = None;
990 /// assert_eq!(x.ok_or(0), Err(0));
993 #[stable(feature = "rust1", since = "1.0.0")]
994 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
995 pub const fn ok_or<E>(self, err: E) -> Result<T, E>
1005 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
1006 /// [`Ok(v)`] and [`None`] to [`Err(err())`].
1009 /// [`Err(err())`]: Err
1010 /// [`Some(v)`]: Some
1015 /// let x = Some("foo");
1016 /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
1018 /// let x: Option<&str> = None;
1019 /// assert_eq!(x.ok_or_else(|| 0), Err(0));
1022 #[stable(feature = "rust1", since = "1.0.0")]
1023 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1024 pub const fn ok_or_else<E, F>(self, err: F) -> Result<T, E>
1026 F: ~const FnOnce() -> E,
1035 /////////////////////////////////////////////////////////////////////////
1036 // Iterator constructors
1037 /////////////////////////////////////////////////////////////////////////
1039 /// Returns an iterator over the possibly contained value.
1044 /// let x = Some(4);
1045 /// assert_eq!(x.iter().next(), Some(&4));
1047 /// let x: Option<u32> = None;
1048 /// assert_eq!(x.iter().next(), None);
1051 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1052 #[stable(feature = "rust1", since = "1.0.0")]
1053 pub const fn iter(&self) -> Iter<'_, T> {
1054 Iter { inner: Item { opt: self.as_ref() } }
1057 /// Returns a mutable iterator over the possibly contained value.
1062 /// let mut x = Some(4);
1063 /// match x.iter_mut().next() {
1064 /// Some(v) => *v = 42,
1067 /// assert_eq!(x, Some(42));
1069 /// let mut x: Option<u32> = None;
1070 /// assert_eq!(x.iter_mut().next(), None);
1073 #[stable(feature = "rust1", since = "1.0.0")]
1074 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1075 IterMut { inner: Item { opt: self.as_mut() } }
1078 /////////////////////////////////////////////////////////////////////////
1079 // Boolean operations on the values, eager and lazy
1080 /////////////////////////////////////////////////////////////////////////
1082 /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
1087 /// let x = Some(2);
1088 /// let y: Option<&str> = None;
1089 /// assert_eq!(x.and(y), None);
1091 /// let x: Option<u32> = None;
1092 /// let y = Some("foo");
1093 /// assert_eq!(x.and(y), None);
1095 /// let x = Some(2);
1096 /// let y = Some("foo");
1097 /// assert_eq!(x.and(y), Some("foo"));
1099 /// let x: Option<u32> = None;
1100 /// let y: Option<&str> = None;
1101 /// assert_eq!(x.and(y), None);
1104 #[stable(feature = "rust1", since = "1.0.0")]
1105 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1106 pub const fn and<U>(self, optb: Option<U>) -> Option<U>
1117 /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
1118 /// wrapped value and returns the result.
1120 /// Some languages call this operation flatmap.
1125 /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
1126 /// fn nope(_: u32) -> Option<u32> { None }
1128 /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
1129 /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
1130 /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
1131 /// assert_eq!(None.and_then(sq).and_then(sq), None);
1134 #[stable(feature = "rust1", since = "1.0.0")]
1135 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1136 pub const fn and_then<U, F>(self, f: F) -> Option<U>
1138 F: ~const FnOnce(T) -> Option<U>,
1147 /// Returns [`None`] if the option is [`None`], otherwise calls `predicate`
1148 /// with the wrapped value and returns:
1150 /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped
1152 /// - [`None`] if `predicate` returns `false`.
1154 /// This function works similar to [`Iterator::filter()`]. You can imagine
1155 /// the `Option<T>` being an iterator over one or zero elements. `filter()`
1156 /// lets you decide which elements to keep.
1161 /// fn is_even(n: &i32) -> bool {
1165 /// assert_eq!(None.filter(is_even), None);
1166 /// assert_eq!(Some(3).filter(is_even), None);
1167 /// assert_eq!(Some(4).filter(is_even), Some(4));
1170 /// [`Some(t)`]: Some
1172 #[stable(feature = "option_filter", since = "1.27.0")]
1173 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1174 pub const fn filter<P>(self, predicate: P) -> Self
1177 P: ~const FnOnce(&T) -> bool,
1180 if let Some(x) = self {
1188 /// Returns the option if it contains a value, otherwise returns `optb`.
1190 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
1191 /// result of a function call, it is recommended to use [`or_else`], which is
1192 /// lazily evaluated.
1194 /// [`or_else`]: Option::or_else
1199 /// let x = Some(2);
1201 /// assert_eq!(x.or(y), Some(2));
1204 /// let y = Some(100);
1205 /// assert_eq!(x.or(y), Some(100));
1207 /// let x = Some(2);
1208 /// let y = Some(100);
1209 /// assert_eq!(x.or(y), Some(2));
1211 /// let x: Option<u32> = None;
1213 /// assert_eq!(x.or(y), None);
1216 #[stable(feature = "rust1", since = "1.0.0")]
1217 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1218 pub const fn or(self, optb: Option<T>) -> Option<T>
1228 /// Returns the option if it contains a value, otherwise calls `f` and
1229 /// returns the result.
1234 /// fn nobody() -> Option<&'static str> { None }
1235 /// fn vikings() -> Option<&'static str> { Some("vikings") }
1237 /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
1238 /// assert_eq!(None.or_else(vikings), Some("vikings"));
1239 /// assert_eq!(None.or_else(nobody), None);
1242 #[stable(feature = "rust1", since = "1.0.0")]
1243 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1244 pub const fn or_else<F>(self, f: F) -> Option<T>
1246 F: ~const FnOnce() -> Option<T>,
1255 /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`].
1260 /// let x = Some(2);
1261 /// let y: Option<u32> = None;
1262 /// assert_eq!(x.xor(y), Some(2));
1264 /// let x: Option<u32> = None;
1265 /// let y = Some(2);
1266 /// assert_eq!(x.xor(y), Some(2));
1268 /// let x = Some(2);
1269 /// let y = Some(2);
1270 /// assert_eq!(x.xor(y), None);
1272 /// let x: Option<u32> = None;
1273 /// let y: Option<u32> = None;
1274 /// assert_eq!(x.xor(y), None);
1277 #[stable(feature = "option_xor", since = "1.37.0")]
1278 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1279 pub const fn xor(self, optb: Option<T>) -> Option<T>
1283 match (self, optb) {
1284 (Some(a), None) => Some(a),
1285 (None, Some(b)) => Some(b),
1290 /////////////////////////////////////////////////////////////////////////
1291 // Entry-like operations to insert a value and return a reference
1292 /////////////////////////////////////////////////////////////////////////
1294 /// Inserts `value` into the option, then returns a mutable reference to it.
1296 /// If the option already contains a value, the old value is dropped.
1298 /// See also [`Option::get_or_insert`], which doesn't update the value if
1299 /// the option already contains [`Some`].
1304 /// let mut opt = None;
1305 /// let val = opt.insert(1);
1306 /// assert_eq!(*val, 1);
1307 /// assert_eq!(opt.unwrap(), 1);
1308 /// let val = opt.insert(2);
1309 /// assert_eq!(*val, 2);
1311 /// assert_eq!(opt.unwrap(), 3);
1313 #[must_use = "if you intended to set a value, consider assignment instead"]
1315 #[stable(feature = "option_insert", since = "1.53.0")]
1316 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1317 pub const fn insert(&mut self, value: T) -> &mut T
1321 *self = Some(value);
1323 // SAFETY: the code above just filled the option
1324 unsafe { self.as_mut().unwrap_unchecked() }
1327 /// Inserts `value` into the option if it is [`None`], then
1328 /// returns a mutable reference to the contained value.
1330 /// See also [`Option::insert`], which updates the value even if
1331 /// the option already contains [`Some`].
1336 /// let mut x = None;
1339 /// let y: &mut u32 = x.get_or_insert(5);
1340 /// assert_eq!(y, &5);
1345 /// assert_eq!(x, Some(7));
1348 #[stable(feature = "option_entry", since = "1.20.0")]
1349 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1350 pub const fn get_or_insert(&mut self, value: T) -> &mut T
1354 if let None = *self {
1355 *self = Some(value);
1358 // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
1359 // variant in the code above.
1360 unsafe { self.as_mut().unwrap_unchecked() }
1363 /// Inserts the default value into the option if it is [`None`], then
1364 /// returns a mutable reference to the contained value.
1369 /// #![feature(option_get_or_insert_default)]
1371 /// let mut x = None;
1374 /// let y: &mut u32 = x.get_or_insert_default();
1375 /// assert_eq!(y, &0);
1380 /// assert_eq!(x, Some(7));
1383 #[unstable(feature = "option_get_or_insert_default", issue = "82901")]
1384 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1385 pub const fn get_or_insert_default(&mut self) -> &mut T
1389 #[rustc_allow_const_fn_unstable(const_fn_trait_bound)]
1390 const fn default<T: ~const Default>() -> T {
1394 self.get_or_insert_with(default)
1397 /// Inserts a value computed from `f` into the option if it is [`None`],
1398 /// then returns a mutable reference to the contained value.
1403 /// let mut x = None;
1406 /// let y: &mut u32 = x.get_or_insert_with(|| 5);
1407 /// assert_eq!(y, &5);
1412 /// assert_eq!(x, Some(7));
1415 #[stable(feature = "option_entry", since = "1.20.0")]
1416 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1417 pub const fn get_or_insert_with<F>(&mut self, f: F) -> &mut T
1419 F: ~const FnOnce() -> T,
1422 if let None = *self {
1423 // the compiler isn't smart enough to know that we are not dropping a `T`
1424 // here and wants us to ensure `T` can be dropped at compile time.
1425 mem::forget(mem::replace(self, Some(f())))
1428 // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
1429 // variant in the code above.
1430 unsafe { self.as_mut().unwrap_unchecked() }
1433 /////////////////////////////////////////////////////////////////////////
1435 /////////////////////////////////////////////////////////////////////////
1437 /// Takes the value out of the option, leaving a [`None`] in its place.
1442 /// let mut x = Some(2);
1443 /// let y = x.take();
1444 /// assert_eq!(x, None);
1445 /// assert_eq!(y, Some(2));
1447 /// let mut x: Option<u32> = None;
1448 /// let y = x.take();
1449 /// assert_eq!(x, None);
1450 /// assert_eq!(y, None);
1453 #[stable(feature = "rust1", since = "1.0.0")]
1454 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1455 pub const fn take(&mut self) -> Option<T> {
1456 // FIXME replace `mem::replace` by `mem::take` when the latter is const ready
1457 mem::replace(self, None)
1460 /// Replaces the actual value in the option by the value given in parameter,
1461 /// returning the old value if present,
1462 /// leaving a [`Some`] in its place without deinitializing either one.
1467 /// let mut x = Some(2);
1468 /// let old = x.replace(5);
1469 /// assert_eq!(x, Some(5));
1470 /// assert_eq!(old, Some(2));
1472 /// let mut x = None;
1473 /// let old = x.replace(3);
1474 /// assert_eq!(x, Some(3));
1475 /// assert_eq!(old, None);
1478 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1479 #[stable(feature = "option_replace", since = "1.31.0")]
1480 pub const fn replace(&mut self, value: T) -> Option<T> {
1481 mem::replace(self, Some(value))
1484 /// Zips `self` with another `Option`.
1486 /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some((s, o))`.
1487 /// Otherwise, `None` is returned.
1492 /// let x = Some(1);
1493 /// let y = Some("hi");
1494 /// let z = None::<u8>;
1496 /// assert_eq!(x.zip(y), Some((1, "hi")));
1497 /// assert_eq!(x.zip(z), None);
1499 #[stable(feature = "option_zip_option", since = "1.46.0")]
1500 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1501 pub const fn zip<U>(self, other: Option<U>) -> Option<(T, U)>
1506 match (self, other) {
1507 (Some(a), Some(b)) => Some((a, b)),
1512 /// Zips `self` and another `Option` with function `f`.
1514 /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
1515 /// Otherwise, `None` is returned.
1520 /// #![feature(option_zip)]
1522 /// #[derive(Debug, PartialEq)]
1529 /// fn new(x: f64, y: f64) -> Self {
1534 /// let x = Some(17.5);
1535 /// let y = Some(42.7);
1537 /// assert_eq!(x.zip_with(y, Point::new), Some(Point { x: 17.5, y: 42.7 }));
1538 /// assert_eq!(x.zip_with(None, Point::new), None);
1540 #[unstable(feature = "option_zip", issue = "70086")]
1541 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1542 pub const fn zip_with<U, F, R>(self, other: Option<U>, f: F) -> Option<R>
1544 F: ~const FnOnce(T, U) -> R,
1549 match (self, other) {
1550 (Some(a), Some(b)) => Some(f(a, b)),
1556 impl<T, U> Option<(T, U)> {
1557 /// Unzips an option containing a tuple of two options.
1559 /// If `self` is `Some((a, b))` this method returns `(Some(a), Some(b))`.
1560 /// Otherwise, `(None, None)` is returned.
1565 /// #![feature(unzip_option)]
1567 /// let x = Some((1, "hi"));
1568 /// let y = None::<(u8, u32)>;
1570 /// assert_eq!(x.unzip(), (Some(1), Some("hi")));
1571 /// assert_eq!(y.unzip(), (None, None));
1574 #[unstable(feature = "unzip_option", issue = "87800", reason = "recently added")]
1575 pub const fn unzip(self) -> (Option<T>, Option<U>) {
1577 Some((a, b)) => (Some(a), Some(b)),
1578 None => (None, None),
1583 impl<T: Copy> Option<&T> {
1584 /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
1591 /// let opt_x = Some(&x);
1592 /// assert_eq!(opt_x, Some(&12));
1593 /// let copied = opt_x.copied();
1594 /// assert_eq!(copied, Some(12));
1596 #[must_use = "`self` will be dropped if the result is not used"]
1597 #[stable(feature = "copied", since = "1.35.0")]
1598 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1599 pub const fn copied(self) -> Option<T> {
1600 // FIXME: this implementation, which sidesteps using `Option::map` since it's not const
1601 // ready yet, should be reverted when possible to avoid code repetition
1603 Some(&v) => Some(v),
1609 impl<T: Copy> Option<&mut T> {
1610 /// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the
1617 /// let opt_x = Some(&mut x);
1618 /// assert_eq!(opt_x, Some(&mut 12));
1619 /// let copied = opt_x.copied();
1620 /// assert_eq!(copied, Some(12));
1622 #[must_use = "`self` will be dropped if the result is not used"]
1623 #[stable(feature = "copied", since = "1.35.0")]
1624 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1625 pub const fn copied(self) -> Option<T> {
1627 Some(&mut t) => Some(t),
1633 impl<T: Clone> Option<&T> {
1634 /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
1641 /// let opt_x = Some(&x);
1642 /// assert_eq!(opt_x, Some(&12));
1643 /// let cloned = opt_x.cloned();
1644 /// assert_eq!(cloned, Some(12));
1646 #[must_use = "`self` will be dropped if the result is not used"]
1647 #[stable(feature = "rust1", since = "1.0.0")]
1648 #[rustc_const_unstable(feature = "const_option_cloned", issue = "91582")]
1649 pub const fn cloned(self) -> Option<T>
1654 Some(t) => Some(t.clone()),
1660 impl<T: Clone> Option<&mut T> {
1661 /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
1668 /// let opt_x = Some(&mut x);
1669 /// assert_eq!(opt_x, Some(&mut 12));
1670 /// let cloned = opt_x.cloned();
1671 /// assert_eq!(cloned, Some(12));
1673 #[must_use = "`self` will be dropped if the result is not used"]
1674 #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
1675 #[rustc_const_unstable(feature = "const_option_cloned", issue = "91582")]
1676 pub const fn cloned(self) -> Option<T>
1681 Some(t) => Some(t.clone()),
1687 impl<T: Default> Option<T> {
1688 /// Returns the contained [`Some`] value or a default.
1690 /// Consumes the `self` argument then, if [`Some`], returns the contained
1691 /// value, otherwise if [`None`], returns the [default value] for that
1696 /// Converts a string to an integer, turning poorly-formed strings
1697 /// into 0 (the default value for integers). [`parse`] converts
1698 /// a string to any other type that implements [`FromStr`], returning
1699 /// [`None`] on error.
1702 /// let good_year_from_input = "1909";
1703 /// let bad_year_from_input = "190blarg";
1704 /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
1705 /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
1707 /// assert_eq!(1909, good_year);
1708 /// assert_eq!(0, bad_year);
1711 /// [default value]: Default::default
1712 /// [`parse`]: str::parse
1713 /// [`FromStr`]: crate::str::FromStr
1715 #[stable(feature = "rust1", since = "1.0.0")]
1716 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1717 pub const fn unwrap_or_default(self) -> T
1723 None => Default::default(),
1728 impl<T: Deref> Option<T> {
1729 /// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.
1731 /// Leaves the original Option in-place, creating a new one with a reference
1732 /// to the original one, additionally coercing the contents via [`Deref`].
1737 /// let x: Option<String> = Some("hey".to_owned());
1738 /// assert_eq!(x.as_deref(), Some("hey"));
1740 /// let x: Option<String> = None;
1741 /// assert_eq!(x.as_deref(), None);
1743 #[stable(feature = "option_deref", since = "1.40.0")]
1744 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1745 pub const fn as_deref(&self) -> Option<&T::Target>
1749 match self.as_ref() {
1750 Some(t) => Some(t.deref()),
1756 impl<T: DerefMut> Option<T> {
1757 /// Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`.
1759 /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to
1760 /// the inner type's [`Deref::Target`] type.
1765 /// let mut x: Option<String> = Some("hey".to_owned());
1766 /// assert_eq!(x.as_deref_mut().map(|x| {
1767 /// x.make_ascii_uppercase();
1769 /// }), Some("HEY".to_owned().as_mut_str()));
1771 #[stable(feature = "option_deref", since = "1.40.0")]
1772 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1773 pub const fn as_deref_mut(&mut self) -> Option<&mut T::Target>
1777 match self.as_mut() {
1778 Some(t) => Some(t.deref_mut()),
1784 impl<T, E> Option<Result<T, E>> {
1785 /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`.
1787 /// [`None`] will be mapped to <code>[Ok]\([None])</code>.
1788 /// <code>[Some]\([Ok]\(\_))</code> and <code>[Some]\([Err]\(\_))</code> will be mapped to
1789 /// <code>[Ok]\([Some]\(\_))</code> and <code>[Err]\(\_)</code>.
1794 /// #[derive(Debug, Eq, PartialEq)]
1797 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1798 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1799 /// assert_eq!(x, y.transpose());
1802 #[stable(feature = "transpose_result", since = "1.33.0")]
1803 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1804 pub const fn transpose(self) -> Result<Option<T>, E> {
1806 Some(Ok(x)) => Ok(Some(x)),
1807 Some(Err(e)) => Err(e),
1813 // This is a separate function to reduce the code size of .expect() itself.
1814 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
1815 #[cfg_attr(feature = "panic_immediate_abort", inline)]
1818 const fn expect_failed(msg: &str) -> ! {
1822 /////////////////////////////////////////////////////////////////////////////
1823 // Trait implementations
1824 /////////////////////////////////////////////////////////////////////////////
1826 #[stable(feature = "rust1", since = "1.0.0")]
1827 impl<T: Clone> Clone for Option<T> {
1829 fn clone(&self) -> Self {
1831 Some(x) => Some(x.clone()),
1837 fn clone_from(&mut self, source: &Self) {
1838 match (self, source) {
1839 (Some(to), Some(from)) => to.clone_from(from),
1840 (to, from) => *to = from.clone(),
1845 #[stable(feature = "rust1", since = "1.0.0")]
1846 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1847 impl<T> const Default for Option<T> {
1848 /// Returns [`None`][Option::None].
1853 /// let opt: Option<u32> = Option::default();
1854 /// assert!(opt.is_none());
1857 fn default() -> Option<T> {
1862 #[stable(feature = "rust1", since = "1.0.0")]
1863 impl<T> IntoIterator for Option<T> {
1865 type IntoIter = IntoIter<T>;
1867 /// Returns a consuming iterator over the possibly contained value.
1872 /// let x = Some("string");
1873 /// let v: Vec<&str> = x.into_iter().collect();
1874 /// assert_eq!(v, ["string"]);
1877 /// let v: Vec<&str> = x.into_iter().collect();
1878 /// assert!(v.is_empty());
1881 fn into_iter(self) -> IntoIter<T> {
1882 IntoIter { inner: Item { opt: self } }
1886 #[stable(since = "1.4.0", feature = "option_iter")]
1887 impl<'a, T> IntoIterator for &'a Option<T> {
1889 type IntoIter = Iter<'a, T>;
1891 fn into_iter(self) -> Iter<'a, T> {
1896 #[stable(since = "1.4.0", feature = "option_iter")]
1897 impl<'a, T> IntoIterator for &'a mut Option<T> {
1898 type Item = &'a mut T;
1899 type IntoIter = IterMut<'a, T>;
1901 fn into_iter(self) -> IterMut<'a, T> {
1906 #[stable(since = "1.12.0", feature = "option_from")]
1907 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
1908 impl<T> const From<T> for Option<T> {
1909 /// Moves `val` into a new [`Some`].
1914 /// let o: Option<u8> = Option::from(67);
1916 /// assert_eq!(Some(67), o);
1918 fn from(val: T) -> Option<T> {
1923 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1924 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
1925 impl<'a, T> const From<&'a Option<T>> for Option<&'a T> {
1926 /// Converts from `&Option<T>` to `Option<&T>`.
1930 /// Converts an <code>[Option]<[String]></code> into an <code>[Option]<[usize]></code>, preserving
1931 /// the original. The [`map`] method takes the `self` argument by value, consuming the original,
1932 /// so this technique uses `from` to first take an [`Option`] to a reference
1933 /// to the value inside the original.
1935 /// [`map`]: Option::map
1936 /// [String]: ../../std/string/struct.String.html "String"
1939 /// let s: Option<String> = Some(String::from("Hello, Rustaceans!"));
1940 /// let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());
1942 /// println!("Can still print s: {:?}", s);
1944 /// assert_eq!(o, Some(18));
1946 fn from(o: &'a Option<T>) -> Option<&'a T> {
1951 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1952 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
1953 impl<'a, T> const From<&'a mut Option<T>> for Option<&'a mut T> {
1954 /// Converts from `&mut Option<T>` to `Option<&mut T>`
1959 /// let mut s = Some(String::from("Hello"));
1960 /// let o: Option<&mut String> = Option::from(&mut s);
1963 /// Some(t) => *t = String::from("Hello, Rustaceans!"),
1967 /// assert_eq!(s, Some(String::from("Hello, Rustaceans!")));
1969 fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
1974 /////////////////////////////////////////////////////////////////////////////
1975 // The Option Iterators
1976 /////////////////////////////////////////////////////////////////////////////
1978 #[derive(Clone, Debug)]
1983 impl<A> Iterator for Item<A> {
1987 fn next(&mut self) -> Option<A> {
1992 fn size_hint(&self) -> (usize, Option<usize>) {
1994 Some(_) => (1, Some(1)),
1995 None => (0, Some(0)),
2000 impl<A> DoubleEndedIterator for Item<A> {
2002 fn next_back(&mut self) -> Option<A> {
2007 impl<A> ExactSizeIterator for Item<A> {}
2008 impl<A> FusedIterator for Item<A> {}
2009 unsafe impl<A> TrustedLen for Item<A> {}
2011 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
2013 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
2015 /// This `struct` is created by the [`Option::iter`] function.
2016 #[stable(feature = "rust1", since = "1.0.0")]
2018 pub struct Iter<'a, A: 'a> {
2022 #[stable(feature = "rust1", since = "1.0.0")]
2023 impl<'a, A> Iterator for Iter<'a, A> {
2027 fn next(&mut self) -> Option<&'a A> {
2031 fn size_hint(&self) -> (usize, Option<usize>) {
2032 self.inner.size_hint()
2036 #[stable(feature = "rust1", since = "1.0.0")]
2037 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
2039 fn next_back(&mut self) -> Option<&'a A> {
2040 self.inner.next_back()
2044 #[stable(feature = "rust1", since = "1.0.0")]
2045 impl<A> ExactSizeIterator for Iter<'_, A> {}
2047 #[stable(feature = "fused", since = "1.26.0")]
2048 impl<A> FusedIterator for Iter<'_, A> {}
2050 #[unstable(feature = "trusted_len", issue = "37572")]
2051 unsafe impl<A> TrustedLen for Iter<'_, A> {}
2053 #[stable(feature = "rust1", since = "1.0.0")]
2054 impl<A> Clone for Iter<'_, A> {
2056 fn clone(&self) -> Self {
2057 Iter { inner: self.inner.clone() }
2061 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
2063 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
2065 /// This `struct` is created by the [`Option::iter_mut`] function.
2066 #[stable(feature = "rust1", since = "1.0.0")]
2068 pub struct IterMut<'a, A: 'a> {
2069 inner: Item<&'a mut A>,
2072 #[stable(feature = "rust1", since = "1.0.0")]
2073 impl<'a, A> Iterator for IterMut<'a, A> {
2074 type Item = &'a mut A;
2077 fn next(&mut self) -> Option<&'a mut A> {
2081 fn size_hint(&self) -> (usize, Option<usize>) {
2082 self.inner.size_hint()
2086 #[stable(feature = "rust1", since = "1.0.0")]
2087 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
2089 fn next_back(&mut self) -> Option<&'a mut A> {
2090 self.inner.next_back()
2094 #[stable(feature = "rust1", since = "1.0.0")]
2095 impl<A> ExactSizeIterator for IterMut<'_, A> {}
2097 #[stable(feature = "fused", since = "1.26.0")]
2098 impl<A> FusedIterator for IterMut<'_, A> {}
2099 #[unstable(feature = "trusted_len", issue = "37572")]
2100 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
2102 /// An iterator over the value in [`Some`] variant of an [`Option`].
2104 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
2106 /// This `struct` is created by the [`Option::into_iter`] function.
2107 #[derive(Clone, Debug)]
2108 #[stable(feature = "rust1", since = "1.0.0")]
2109 pub struct IntoIter<A> {
2113 #[stable(feature = "rust1", since = "1.0.0")]
2114 impl<A> Iterator for IntoIter<A> {
2118 fn next(&mut self) -> Option<A> {
2122 fn size_hint(&self) -> (usize, Option<usize>) {
2123 self.inner.size_hint()
2127 #[stable(feature = "rust1", since = "1.0.0")]
2128 impl<A> DoubleEndedIterator for IntoIter<A> {
2130 fn next_back(&mut self) -> Option<A> {
2131 self.inner.next_back()
2135 #[stable(feature = "rust1", since = "1.0.0")]
2136 impl<A> ExactSizeIterator for IntoIter<A> {}
2138 #[stable(feature = "fused", since = "1.26.0")]
2139 impl<A> FusedIterator for IntoIter<A> {}
2141 #[unstable(feature = "trusted_len", issue = "37572")]
2142 unsafe impl<A> TrustedLen for IntoIter<A> {}
2144 /////////////////////////////////////////////////////////////////////////////
2146 /////////////////////////////////////////////////////////////////////////////
2148 #[stable(feature = "rust1", since = "1.0.0")]
2149 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
2150 /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
2151 /// no further elements are taken, and the [`None`][Option::None] is
2152 /// returned. Should no [`None`][Option::None] occur, a container of type
2153 /// `V` containing the values of each [`Option`] is returned.
2157 /// Here is an example which increments every integer in a vector.
2158 /// We use the checked variant of `add` that returns `None` when the
2159 /// calculation would result in an overflow.
2162 /// let items = vec![0_u16, 1, 2];
2164 /// let res: Option<Vec<u16>> = items
2166 /// .map(|x| x.checked_add(1))
2169 /// assert_eq!(res, Some(vec![1, 2, 3]));
2172 /// As you can see, this will return the expected, valid items.
2174 /// Here is another example that tries to subtract one from another list
2175 /// of integers, this time checking for underflow:
2178 /// let items = vec![2_u16, 1, 0];
2180 /// let res: Option<Vec<u16>> = items
2182 /// .map(|x| x.checked_sub(1))
2185 /// assert_eq!(res, None);
2188 /// Since the last element is zero, it would underflow. Thus, the resulting
2189 /// value is `None`.
2191 /// Here is a variation on the previous example, showing that no
2192 /// further elements are taken from `iter` after the first `None`.
2195 /// let items = vec![3_u16, 2, 1, 10];
2197 /// let mut shared = 0;
2199 /// let res: Option<Vec<u16>> = items
2201 /// .map(|x| { shared += x; x.checked_sub(2) })
2204 /// assert_eq!(res, None);
2205 /// assert_eq!(shared, 6);
2208 /// Since the third element caused an underflow, no further elements were taken,
2209 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
2211 fn from_iter<I: IntoIterator<Item = Option<A>>>(iter: I) -> Option<V> {
2212 // FIXME(#11084): This could be replaced with Iterator::scan when this
2213 // performance bug is closed.
2215 iter.into_iter().map(|x| x.ok_or(())).collect::<Result<_, _>>().ok()
2219 #[unstable(feature = "try_trait_v2", issue = "84277")]
2220 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
2221 impl<T> const ops::Try for Option<T> {
2223 type Residual = Option<convert::Infallible>;
2226 fn from_output(output: Self::Output) -> Self {
2231 fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
2233 Some(v) => ControlFlow::Continue(v),
2234 None => ControlFlow::Break(None),
2239 #[unstable(feature = "try_trait_v2", issue = "84277")]
2240 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
2241 impl<T> const ops::FromResidual for Option<T> {
2243 fn from_residual(residual: Option<convert::Infallible>) -> Self {
2250 #[unstable(feature = "try_trait_v2_residual", issue = "91285")]
2251 impl<T> ops::Residual<T> for Option<convert::Infallible> {
2252 type TryType = Option<T>;
2255 impl<T> Option<Option<T>> {
2256 /// Converts from `Option<Option<T>>` to `Option<T>`.
2263 /// let x: Option<Option<u32>> = Some(Some(6));
2264 /// assert_eq!(Some(6), x.flatten());
2266 /// let x: Option<Option<u32>> = Some(None);
2267 /// assert_eq!(None, x.flatten());
2269 /// let x: Option<Option<u32>> = None;
2270 /// assert_eq!(None, x.flatten());
2273 /// Flattening only removes one level of nesting at a time:
2276 /// let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
2277 /// assert_eq!(Some(Some(6)), x.flatten());
2278 /// assert_eq!(Some(6), x.flatten().flatten());
2281 #[stable(feature = "option_flattening", since = "1.40.0")]
2282 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
2283 pub const fn flatten(self) -> Option<T> {
2285 Some(inner) => inner,