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, [`Option`]`<`[`Box<T>`]`>`.
52 //! The following example uses [`Option`] to create an optional box of
53 //! [`i32`]. Notice that in order to use the inner [`i32`] value first, the
54 //! `check_optional` function needs to use pattern matching to
55 //! determine whether the box has a value (i.e., it is [`Some(...)`][`Some`]) or
59 //! let optional = None;
60 //! check_optional(optional);
62 //! let optional = Some(Box::new(9000));
63 //! check_optional(optional);
65 //! fn check_optional(optional: Option<Box<i32>>) {
67 //! Some(p) => println!("has value {}", p),
68 //! None => println!("has no value"),
75 //! Rust guarantees to optimize the following types `T` such that
76 //! [`Option<T>`] has the same size as `T`:
81 //! * `fn`, `extern "C" fn`
82 //! * [`num::NonZero*`]
83 //! * [`ptr::NonNull<U>`]
84 //! * `#[repr(transparent)]` struct around one of the types in this list.
86 //! This is called the "null pointer optimization" or NPO.
88 //! It is further guaranteed that, for the cases above, one can
89 //! [`mem::transmute`] from all valid values of `T` to `Option<T>` and
90 //! from `Some::<T>(_)` to `T` (but transmuting `None::<T>` to `T`
91 //! is undefined behaviour).
95 //! Basic pattern matching on [`Option`]:
98 //! let msg = Some("howdy");
100 //! // Take a reference to the contained string
101 //! if let Some(m) = &msg {
102 //! println!("{}", *m);
105 //! // Remove the contained string, destroying the Option
106 //! let unwrapped_msg = msg.unwrap_or("default message");
109 //! Initialize a result to [`None`] before a loop:
112 //! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) }
114 //! // A list of data to search through.
115 //! let all_the_big_things = [
116 //! Kingdom::Plant(250, "redwood"),
117 //! Kingdom::Plant(230, "noble fir"),
118 //! Kingdom::Plant(229, "sugar pine"),
119 //! Kingdom::Animal(25, "blue whale"),
120 //! Kingdom::Animal(19, "fin whale"),
121 //! Kingdom::Animal(15, "north pacific right whale"),
124 //! // We're going to search for the name of the biggest animal,
125 //! // but to start with we've just got `None`.
126 //! let mut name_of_biggest_animal = None;
127 //! let mut size_of_biggest_animal = 0;
128 //! for big_thing in &all_the_big_things {
129 //! match *big_thing {
130 //! Kingdom::Animal(size, name) if size > size_of_biggest_animal => {
131 //! // Now we've found the name of some big animal
132 //! size_of_biggest_animal = size;
133 //! name_of_biggest_animal = Some(name);
135 //! Kingdom::Animal(..) | Kingdom::Plant(..) => ()
139 //! match name_of_biggest_animal {
140 //! Some(name) => println!("the biggest animal is {}", name),
141 //! None => println!("there are no animals :("),
145 //! [`Box<T>`]: ../../std/boxed/struct.Box.html
146 //! [`Box<U>`]: ../../std/boxed/struct.Box.html
147 //! [`num::NonZero*`]: crate::num
148 //! [`ptr::NonNull<U>`]: crate::ptr::NonNull
150 #![stable(feature = "rust1", since = "1.0.0")]
152 use crate::iter::{FromIterator, FusedIterator, TrustedLen};
156 ops::{self, ControlFlow, Deref, DerefMut},
159 /// The `Option` type. See [the module level documentation](self) for more.
160 #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
161 #[rustc_diagnostic_item = "option_type"]
162 #[stable(feature = "rust1", since = "1.0.0")]
166 #[stable(feature = "rust1", since = "1.0.0")]
170 #[stable(feature = "rust1", since = "1.0.0")]
171 Some(#[stable(feature = "rust1", since = "1.0.0")] T),
174 /////////////////////////////////////////////////////////////////////////////
175 // Type implementation
176 /////////////////////////////////////////////////////////////////////////////
179 /////////////////////////////////////////////////////////////////////////
180 // Querying the contained values
181 /////////////////////////////////////////////////////////////////////////
183 /// Returns `true` if the option is a [`Some`] value.
188 /// let x: Option<u32> = Some(2);
189 /// assert_eq!(x.is_some(), true);
191 /// let x: Option<u32> = None;
192 /// assert_eq!(x.is_some(), false);
194 #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"]
196 #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
197 #[stable(feature = "rust1", since = "1.0.0")]
198 pub const fn is_some(&self) -> bool {
199 matches!(*self, Some(_))
202 /// Returns `true` if the option is a [`None`] value.
207 /// let x: Option<u32> = Some(2);
208 /// assert_eq!(x.is_none(), false);
210 /// let x: Option<u32> = None;
211 /// assert_eq!(x.is_none(), true);
213 #[must_use = "if you intended to assert that this doesn't have a value, consider \
214 `.and_then(|_| panic!(\"`Option` had a value when expected `None`\"))` instead"]
216 #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
217 #[stable(feature = "rust1", since = "1.0.0")]
218 pub const fn is_none(&self) -> bool {
222 /// Returns `true` if the option is a [`Some`] value containing the given value.
227 /// #![feature(option_result_contains)]
229 /// let x: Option<u32> = Some(2);
230 /// assert_eq!(x.contains(&2), true);
232 /// let x: Option<u32> = Some(3);
233 /// assert_eq!(x.contains(&2), false);
235 /// let x: Option<u32> = None;
236 /// assert_eq!(x.contains(&2), false);
240 #[unstable(feature = "option_result_contains", issue = "62358")]
241 pub fn contains<U>(&self, x: &U) -> bool
251 /////////////////////////////////////////////////////////////////////////
252 // Adapter for working with references
253 /////////////////////////////////////////////////////////////////////////
255 /// Converts from `&Option<T>` to `Option<&T>`.
259 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
260 /// The [`map`] method takes the `self` argument by value, consuming the original,
261 /// so this technique uses `as_ref` to first take an `Option` to a reference
262 /// to the value inside the original.
264 /// [`map`]: Option::map
265 /// [`String`]: ../../std/string/struct.String.html
268 /// let text: Option<String> = Some("Hello, world!".to_string());
269 /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
270 /// // then consume *that* with `map`, leaving `text` on the stack.
271 /// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
272 /// println!("still can print text: {:?}", text);
275 #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
276 #[stable(feature = "rust1", since = "1.0.0")]
277 pub const fn as_ref(&self) -> Option<&T> {
279 Some(ref x) => Some(x),
284 /// Converts from `&mut Option<T>` to `Option<&mut T>`.
289 /// let mut x = Some(2);
290 /// match x.as_mut() {
291 /// Some(v) => *v = 42,
294 /// assert_eq!(x, Some(42));
297 #[stable(feature = "rust1", since = "1.0.0")]
298 pub fn as_mut(&mut self) -> Option<&mut T> {
300 Some(ref mut x) => Some(x),
305 /// Converts from [`Pin`]`<&Option<T>>` to `Option<`[`Pin`]`<&T>>`.
307 #[stable(feature = "pin", since = "1.33.0")]
308 pub fn as_pin_ref(self: Pin<&Self>) -> Option<Pin<&T>> {
309 // SAFETY: `x` is guaranteed to be pinned because it comes from `self`
311 unsafe { Pin::get_ref(self).as_ref().map(|x| Pin::new_unchecked(x)) }
314 /// Converts from [`Pin`]`<&mut Option<T>>` to `Option<`[`Pin`]`<&mut T>>`.
316 #[stable(feature = "pin", since = "1.33.0")]
317 pub fn as_pin_mut(self: Pin<&mut Self>) -> Option<Pin<&mut T>> {
318 // SAFETY: `get_unchecked_mut` is never used to move the `Option` inside `self`.
319 // `x` is guaranteed to be pinned because it comes from `self` which is pinned.
320 unsafe { Pin::get_unchecked_mut(self).as_mut().map(|x| Pin::new_unchecked(x)) }
323 /////////////////////////////////////////////////////////////////////////
324 // Getting to contained values
325 /////////////////////////////////////////////////////////////////////////
327 /// Returns the contained [`Some`] value, consuming the `self` value.
331 /// Panics if the value is a [`None`] with a custom panic message provided by
337 /// let x = Some("value");
338 /// assert_eq!(x.expect("fruits are healthy"), "value");
342 /// let x: Option<&str> = None;
343 /// x.expect("fruits are healthy"); // panics with `fruits are healthy`
347 #[stable(feature = "rust1", since = "1.0.0")]
348 pub fn expect(self, msg: &str) -> T {
351 None => expect_failed(msg),
355 /// Returns the contained [`Some`] value, consuming the `self` value.
357 /// Because this function may panic, its use is generally discouraged.
358 /// Instead, prefer to use pattern matching and handle the [`None`]
359 /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
360 /// [`unwrap_or_default`].
362 /// [`unwrap_or`]: Option::unwrap_or
363 /// [`unwrap_or_else`]: Option::unwrap_or_else
364 /// [`unwrap_or_default`]: Option::unwrap_or_default
368 /// Panics if the self value equals [`None`].
373 /// let x = Some("air");
374 /// assert_eq!(x.unwrap(), "air");
378 /// let x: Option<&str> = None;
379 /// assert_eq!(x.unwrap(), "air"); // fails
383 #[stable(feature = "rust1", since = "1.0.0")]
384 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
385 pub const fn unwrap(self) -> T {
388 None => panic!("called `Option::unwrap()` on a `None` value"),
392 /// Returns the contained [`Some`] value or a provided default.
394 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
395 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
396 /// which is lazily evaluated.
398 /// [`unwrap_or_else`]: Option::unwrap_or_else
403 /// assert_eq!(Some("car").unwrap_or("bike"), "car");
404 /// assert_eq!(None.unwrap_or("bike"), "bike");
407 #[stable(feature = "rust1", since = "1.0.0")]
408 pub fn unwrap_or(self, default: T) -> T {
415 /// Returns the contained [`Some`] value or computes it from a closure.
421 /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
422 /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
425 #[stable(feature = "rust1", since = "1.0.0")]
426 pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
433 /// Returns the contained [`Some`] value, consuming the `self` value,
434 /// without checking that the value is not [`None`].
438 /// Calling this method on [`None`] is *[undefined behavior]*.
440 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
445 /// #![feature(option_result_unwrap_unchecked)]
446 /// let x = Some("air");
447 /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air");
451 /// #![feature(option_result_unwrap_unchecked)]
452 /// let x: Option<&str> = None;
453 /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air"); // Undefined behavior!
457 #[unstable(feature = "option_result_unwrap_unchecked", reason = "newly added", issue = "81383")]
458 pub unsafe fn unwrap_unchecked(self) -> T {
459 debug_assert!(self.is_some());
462 // SAFETY: the safety contract must be upheld by the caller.
463 None => unsafe { hint::unreachable_unchecked() },
467 /////////////////////////////////////////////////////////////////////////
468 // Transforming contained values
469 /////////////////////////////////////////////////////////////////////////
471 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
475 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, consuming the original:
477 /// [`String`]: ../../std/string/struct.String.html
479 /// let maybe_some_string = Some(String::from("Hello, World!"));
480 /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
481 /// let maybe_some_len = maybe_some_string.map(|s| s.len());
483 /// assert_eq!(maybe_some_len, Some(13));
486 #[stable(feature = "rust1", since = "1.0.0")]
487 pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
489 Some(x) => Some(f(x)),
494 /// Returns the provided default result (if none),
495 /// or applies a function to the contained value (if any).
497 /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
498 /// the result of a function call, it is recommended to use [`map_or_else`],
499 /// which is lazily evaluated.
501 /// [`map_or_else`]: Option::map_or_else
506 /// let x = Some("foo");
507 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
509 /// let x: Option<&str> = None;
510 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
513 #[stable(feature = "rust1", since = "1.0.0")]
514 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
521 /// Computes a default function result (if none), or
522 /// applies a different function to the contained value (if any).
529 /// let x = Some("foo");
530 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
532 /// let x: Option<&str> = None;
533 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
536 #[stable(feature = "rust1", since = "1.0.0")]
537 pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
544 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
545 /// [`Ok(v)`] and [`None`] to [`Err(err)`].
547 /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
548 /// result of a function call, it is recommended to use [`ok_or_else`], which is
549 /// lazily evaluated.
552 /// [`Err(err)`]: Err
553 /// [`Some(v)`]: Some
554 /// [`ok_or_else`]: Option::ok_or_else
559 /// let x = Some("foo");
560 /// assert_eq!(x.ok_or(0), Ok("foo"));
562 /// let x: Option<&str> = None;
563 /// assert_eq!(x.ok_or(0), Err(0));
566 #[stable(feature = "rust1", since = "1.0.0")]
567 pub fn ok_or<E>(self, err: E) -> Result<T, E> {
574 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
575 /// [`Ok(v)`] and [`None`] to [`Err(err())`].
578 /// [`Err(err())`]: Err
579 /// [`Some(v)`]: Some
584 /// let x = Some("foo");
585 /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
587 /// let x: Option<&str> = None;
588 /// assert_eq!(x.ok_or_else(|| 0), Err(0));
591 #[stable(feature = "rust1", since = "1.0.0")]
592 pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
599 /////////////////////////////////////////////////////////////////////////
600 // Iterator constructors
601 /////////////////////////////////////////////////////////////////////////
603 /// Returns an iterator over the possibly contained value.
609 /// assert_eq!(x.iter().next(), Some(&4));
611 /// let x: Option<u32> = None;
612 /// assert_eq!(x.iter().next(), None);
615 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
616 #[stable(feature = "rust1", since = "1.0.0")]
617 pub const fn iter(&self) -> Iter<'_, T> {
618 Iter { inner: Item { opt: self.as_ref() } }
621 /// Returns a mutable iterator over the possibly contained value.
626 /// let mut x = Some(4);
627 /// match x.iter_mut().next() {
628 /// Some(v) => *v = 42,
631 /// assert_eq!(x, Some(42));
633 /// let mut x: Option<u32> = None;
634 /// assert_eq!(x.iter_mut().next(), None);
637 #[stable(feature = "rust1", since = "1.0.0")]
638 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
639 IterMut { inner: Item { opt: self.as_mut() } }
642 /////////////////////////////////////////////////////////////////////////
643 // Boolean operations on the values, eager and lazy
644 /////////////////////////////////////////////////////////////////////////
646 /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
652 /// let y: Option<&str> = None;
653 /// assert_eq!(x.and(y), None);
655 /// let x: Option<u32> = None;
656 /// let y = Some("foo");
657 /// assert_eq!(x.and(y), None);
660 /// let y = Some("foo");
661 /// assert_eq!(x.and(y), Some("foo"));
663 /// let x: Option<u32> = None;
664 /// let y: Option<&str> = None;
665 /// assert_eq!(x.and(y), None);
668 #[stable(feature = "rust1", since = "1.0.0")]
669 pub fn and<U>(self, optb: Option<U>) -> Option<U> {
676 /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
677 /// wrapped value and returns the result.
679 /// Some languages call this operation flatmap.
684 /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
685 /// fn nope(_: u32) -> Option<u32> { None }
687 /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
688 /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
689 /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
690 /// assert_eq!(None.and_then(sq).and_then(sq), None);
693 #[stable(feature = "rust1", since = "1.0.0")]
694 pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> {
701 /// Returns [`None`] if the option is [`None`], otherwise calls `predicate`
702 /// with the wrapped value and returns:
704 /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped
706 /// - [`None`] if `predicate` returns `false`.
708 /// This function works similar to [`Iterator::filter()`]. You can imagine
709 /// the `Option<T>` being an iterator over one or zero elements. `filter()`
710 /// lets you decide which elements to keep.
715 /// fn is_even(n: &i32) -> bool {
719 /// assert_eq!(None.filter(is_even), None);
720 /// assert_eq!(Some(3).filter(is_even), None);
721 /// assert_eq!(Some(4).filter(is_even), Some(4));
724 /// [`Some(t)`]: Some
726 #[stable(feature = "option_filter", since = "1.27.0")]
727 pub fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Self {
728 if let Some(x) = self {
736 /// Returns the option if it contains a value, otherwise returns `optb`.
738 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
739 /// result of a function call, it is recommended to use [`or_else`], which is
740 /// lazily evaluated.
742 /// [`or_else`]: Option::or_else
749 /// assert_eq!(x.or(y), Some(2));
752 /// let y = Some(100);
753 /// assert_eq!(x.or(y), Some(100));
756 /// let y = Some(100);
757 /// assert_eq!(x.or(y), Some(2));
759 /// let x: Option<u32> = None;
761 /// assert_eq!(x.or(y), None);
764 #[stable(feature = "rust1", since = "1.0.0")]
765 pub fn or(self, optb: Option<T>) -> Option<T> {
772 /// Returns the option if it contains a value, otherwise calls `f` and
773 /// returns the result.
778 /// fn nobody() -> Option<&'static str> { None }
779 /// fn vikings() -> Option<&'static str> { Some("vikings") }
781 /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
782 /// assert_eq!(None.or_else(vikings), Some("vikings"));
783 /// assert_eq!(None.or_else(nobody), None);
786 #[stable(feature = "rust1", since = "1.0.0")]
787 pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> {
794 /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`].
800 /// let y: Option<u32> = None;
801 /// assert_eq!(x.xor(y), Some(2));
803 /// let x: Option<u32> = None;
805 /// assert_eq!(x.xor(y), Some(2));
809 /// assert_eq!(x.xor(y), None);
811 /// let x: Option<u32> = None;
812 /// let y: Option<u32> = None;
813 /// assert_eq!(x.xor(y), None);
816 #[stable(feature = "option_xor", since = "1.37.0")]
817 pub fn xor(self, optb: Option<T>) -> Option<T> {
819 (Some(a), None) => Some(a),
820 (None, Some(b)) => Some(b),
825 /////////////////////////////////////////////////////////////////////////
826 // Entry-like operations to insert a value and return a reference
827 /////////////////////////////////////////////////////////////////////////
829 /// Inserts `value` into the option then returns a mutable reference to it.
831 /// If the option already contains a value, the old value is dropped.
833 /// See also [`Option::get_or_insert`], which doesn't update the value if
834 /// the option already contains [`Some`].
839 /// let mut opt = None;
840 /// let val = opt.insert(1);
841 /// assert_eq!(*val, 1);
842 /// assert_eq!(opt.unwrap(), 1);
843 /// let val = opt.insert(2);
844 /// assert_eq!(*val, 2);
846 /// assert_eq!(opt.unwrap(), 3);
849 #[stable(feature = "option_insert", since = "1.53.0")]
850 pub fn insert(&mut self, value: T) -> &mut T {
855 // SAFETY: the code above just filled the option
856 None => unsafe { hint::unreachable_unchecked() },
860 /// Inserts `value` into the option if it is [`None`], then
861 /// returns a mutable reference to the contained value.
863 /// See also [`Option::insert`], which updates the value even if
864 /// the option already contains [`Some`].
869 /// let mut x = None;
872 /// let y: &mut u32 = x.get_or_insert(5);
873 /// assert_eq!(y, &5);
878 /// assert_eq!(x, Some(7));
881 #[stable(feature = "option_entry", since = "1.20.0")]
882 pub fn get_or_insert(&mut self, value: T) -> &mut T {
883 self.get_or_insert_with(|| value)
886 /// Inserts the default value into the option if it is [`None`], then
887 /// returns a mutable reference to the contained value.
892 /// #![feature(option_get_or_insert_default)]
894 /// let mut x = None;
897 /// let y: &mut u32 = x.get_or_insert_default();
898 /// assert_eq!(y, &0);
903 /// assert_eq!(x, Some(7));
906 #[unstable(feature = "option_get_or_insert_default", issue = "82901")]
907 pub fn get_or_insert_default(&mut self) -> &mut T
911 self.get_or_insert_with(Default::default)
914 /// Inserts a value computed from `f` into the option if it is [`None`],
915 /// then returns a mutable reference to the contained value.
920 /// let mut x = None;
923 /// let y: &mut u32 = x.get_or_insert_with(|| 5);
924 /// assert_eq!(y, &5);
929 /// assert_eq!(x, Some(7));
932 #[stable(feature = "option_entry", since = "1.20.0")]
933 pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
934 if let None = *self {
940 // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
941 // variant in the code above.
942 None => unsafe { hint::unreachable_unchecked() },
946 /////////////////////////////////////////////////////////////////////////
948 /////////////////////////////////////////////////////////////////////////
950 /// Takes the value out of the option, leaving a [`None`] in its place.
955 /// let mut x = Some(2);
956 /// let y = x.take();
957 /// assert_eq!(x, None);
958 /// assert_eq!(y, Some(2));
960 /// let mut x: Option<u32> = None;
961 /// let y = x.take();
962 /// assert_eq!(x, None);
963 /// assert_eq!(y, None);
966 #[stable(feature = "rust1", since = "1.0.0")]
967 pub fn take(&mut self) -> Option<T> {
971 /// Replaces the actual value in the option by the value given in parameter,
972 /// returning the old value if present,
973 /// leaving a [`Some`] in its place without deinitializing either one.
978 /// let mut x = Some(2);
979 /// let old = x.replace(5);
980 /// assert_eq!(x, Some(5));
981 /// assert_eq!(old, Some(2));
983 /// let mut x = None;
984 /// let old = x.replace(3);
985 /// assert_eq!(x, Some(3));
986 /// assert_eq!(old, None);
989 #[stable(feature = "option_replace", since = "1.31.0")]
990 pub fn replace(&mut self, value: T) -> Option<T> {
991 mem::replace(self, Some(value))
994 /// Zips `self` with another `Option`.
996 /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some((s, o))`.
997 /// Otherwise, `None` is returned.
1002 /// let x = Some(1);
1003 /// let y = Some("hi");
1004 /// let z = None::<u8>;
1006 /// assert_eq!(x.zip(y), Some((1, "hi")));
1007 /// assert_eq!(x.zip(z), None);
1009 #[stable(feature = "option_zip_option", since = "1.46.0")]
1010 pub fn zip<U>(self, other: Option<U>) -> Option<(T, U)> {
1011 match (self, other) {
1012 (Some(a), Some(b)) => Some((a, b)),
1017 /// Zips `self` and another `Option` with function `f`.
1019 /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
1020 /// Otherwise, `None` is returned.
1025 /// #![feature(option_zip)]
1027 /// #[derive(Debug, PartialEq)]
1034 /// fn new(x: f64, y: f64) -> Self {
1039 /// let x = Some(17.5);
1040 /// let y = Some(42.7);
1042 /// assert_eq!(x.zip_with(y, Point::new), Some(Point { x: 17.5, y: 42.7 }));
1043 /// assert_eq!(x.zip_with(None, Point::new), None);
1045 #[unstable(feature = "option_zip", issue = "70086")]
1046 pub fn zip_with<U, F, R>(self, other: Option<U>, f: F) -> Option<R>
1048 F: FnOnce(T, U) -> R,
1050 Some(f(self?, other?))
1054 impl<T: Copy> Option<&T> {
1055 /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
1062 /// let opt_x = Some(&x);
1063 /// assert_eq!(opt_x, Some(&12));
1064 /// let copied = opt_x.copied();
1065 /// assert_eq!(copied, Some(12));
1067 #[stable(feature = "copied", since = "1.35.0")]
1068 pub fn copied(self) -> Option<T> {
1073 impl<T: Copy> Option<&mut T> {
1074 /// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the
1081 /// let opt_x = Some(&mut x);
1082 /// assert_eq!(opt_x, Some(&mut 12));
1083 /// let copied = opt_x.copied();
1084 /// assert_eq!(copied, Some(12));
1086 #[stable(feature = "copied", since = "1.35.0")]
1087 pub fn copied(self) -> Option<T> {
1088 self.map(|&mut t| t)
1092 impl<T: Clone> Option<&T> {
1093 /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
1100 /// let opt_x = Some(&x);
1101 /// assert_eq!(opt_x, Some(&12));
1102 /// let cloned = opt_x.cloned();
1103 /// assert_eq!(cloned, Some(12));
1105 #[stable(feature = "rust1", since = "1.0.0")]
1106 pub fn cloned(self) -> Option<T> {
1107 self.map(|t| t.clone())
1111 impl<T: Clone> Option<&mut T> {
1112 /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
1119 /// let opt_x = Some(&mut x);
1120 /// assert_eq!(opt_x, Some(&mut 12));
1121 /// let cloned = opt_x.cloned();
1122 /// assert_eq!(cloned, Some(12));
1124 #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
1125 pub fn cloned(self) -> Option<T> {
1126 self.map(|t| t.clone())
1130 impl<T: Default> Option<T> {
1131 /// Returns the contained [`Some`] value or a default
1133 /// Consumes the `self` argument then, if [`Some`], returns the contained
1134 /// value, otherwise if [`None`], returns the [default value] for that
1139 /// Converts a string to an integer, turning poorly-formed strings
1140 /// into 0 (the default value for integers). [`parse`] converts
1141 /// a string to any other type that implements [`FromStr`], returning
1142 /// [`None`] on error.
1145 /// let good_year_from_input = "1909";
1146 /// let bad_year_from_input = "190blarg";
1147 /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
1148 /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
1150 /// assert_eq!(1909, good_year);
1151 /// assert_eq!(0, bad_year);
1154 /// [default value]: Default::default
1155 /// [`parse`]: str::parse
1156 /// [`FromStr`]: crate::str::FromStr
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 pub fn unwrap_or_default(self) -> T {
1162 None => Default::default(),
1167 impl<T: Deref> Option<T> {
1168 /// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.
1170 /// Leaves the original Option in-place, creating a new one with a reference
1171 /// to the original one, additionally coercing the contents via [`Deref`].
1176 /// let x: Option<String> = Some("hey".to_owned());
1177 /// assert_eq!(x.as_deref(), Some("hey"));
1179 /// let x: Option<String> = None;
1180 /// assert_eq!(x.as_deref(), None);
1182 #[stable(feature = "option_deref", since = "1.40.0")]
1183 pub fn as_deref(&self) -> Option<&T::Target> {
1184 self.as_ref().map(|t| t.deref())
1188 impl<T: DerefMut> Option<T> {
1189 /// Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`.
1191 /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to
1192 /// the inner type's `Deref::Target` type.
1197 /// let mut x: Option<String> = Some("hey".to_owned());
1198 /// assert_eq!(x.as_deref_mut().map(|x| {
1199 /// x.make_ascii_uppercase();
1201 /// }), Some("HEY".to_owned().as_mut_str()));
1203 #[stable(feature = "option_deref", since = "1.40.0")]
1204 pub fn as_deref_mut(&mut self) -> Option<&mut T::Target> {
1205 self.as_mut().map(|t| t.deref_mut())
1209 impl<T, E> Option<Result<T, E>> {
1210 /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`.
1212 /// [`None`] will be mapped to [`Ok`]`(`[`None`]`)`.
1213 /// [`Some`]`(`[`Ok`]`(_))` and [`Some`]`(`[`Err`]`(_))` will be mapped to
1214 /// [`Ok`]`(`[`Some`]`(_))` and [`Err`]`(_)`.
1219 /// #[derive(Debug, Eq, PartialEq)]
1222 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1223 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1224 /// assert_eq!(x, y.transpose());
1227 #[stable(feature = "transpose_result", since = "1.33.0")]
1228 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1229 pub const fn transpose(self) -> Result<Option<T>, E> {
1231 Some(Ok(x)) => Ok(Some(x)),
1232 Some(Err(e)) => Err(e),
1238 // This is a separate function to reduce the code size of .expect() itself.
1242 fn expect_failed(msg: &str) -> ! {
1246 /////////////////////////////////////////////////////////////////////////////
1247 // Trait implementations
1248 /////////////////////////////////////////////////////////////////////////////
1250 #[stable(feature = "rust1", since = "1.0.0")]
1251 impl<T: Clone> Clone for Option<T> {
1253 fn clone(&self) -> Self {
1255 Some(x) => Some(x.clone()),
1261 fn clone_from(&mut self, source: &Self) {
1262 match (self, source) {
1263 (Some(to), Some(from)) => to.clone_from(from),
1264 (to, from) => *to = from.clone(),
1269 #[stable(feature = "rust1", since = "1.0.0")]
1270 impl<T> Default for Option<T> {
1271 /// Returns [`None`][Option::None].
1276 /// let opt: Option<u32> = Option::default();
1277 /// assert!(opt.is_none());
1280 fn default() -> Option<T> {
1285 #[stable(feature = "rust1", since = "1.0.0")]
1286 impl<T> IntoIterator for Option<T> {
1288 type IntoIter = IntoIter<T>;
1290 /// Returns a consuming iterator over the possibly contained value.
1295 /// let x = Some("string");
1296 /// let v: Vec<&str> = x.into_iter().collect();
1297 /// assert_eq!(v, ["string"]);
1300 /// let v: Vec<&str> = x.into_iter().collect();
1301 /// assert!(v.is_empty());
1304 fn into_iter(self) -> IntoIter<T> {
1305 IntoIter { inner: Item { opt: self } }
1309 #[stable(since = "1.4.0", feature = "option_iter")]
1310 impl<'a, T> IntoIterator for &'a Option<T> {
1312 type IntoIter = Iter<'a, T>;
1314 fn into_iter(self) -> Iter<'a, T> {
1319 #[stable(since = "1.4.0", feature = "option_iter")]
1320 impl<'a, T> IntoIterator for &'a mut Option<T> {
1321 type Item = &'a mut T;
1322 type IntoIter = IterMut<'a, T>;
1324 fn into_iter(self) -> IterMut<'a, T> {
1329 #[stable(since = "1.12.0", feature = "option_from")]
1330 impl<T> From<T> for Option<T> {
1331 /// Copies `val` into a new `Some`.
1336 /// let o: Option<u8> = Option::from(67);
1338 /// assert_eq!(Some(67), o);
1340 fn from(val: T) -> Option<T> {
1345 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1346 impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
1347 /// Converts from `&Option<T>` to `Option<&T>`.
1351 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
1352 /// The [`map`] method takes the `self` argument by value, consuming the original,
1353 /// so this technique uses `as_ref` to first take an `Option` to a reference
1354 /// to the value inside the original.
1356 /// [`map`]: Option::map
1357 /// [`String`]: ../../std/string/struct.String.html
1360 /// let s: Option<String> = Some(String::from("Hello, Rustaceans!"));
1361 /// let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());
1363 /// println!("Can still print s: {:?}", s);
1365 /// assert_eq!(o, Some(18));
1367 fn from(o: &'a Option<T>) -> Option<&'a T> {
1372 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1373 impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> {
1374 /// Converts from `&mut Option<T>` to `Option<&mut T>`
1379 /// let mut s = Some(String::from("Hello"));
1380 /// let o: Option<&mut String> = Option::from(&mut s);
1383 /// Some(t) => *t = String::from("Hello, Rustaceans!"),
1387 /// assert_eq!(s, Some(String::from("Hello, Rustaceans!")));
1389 fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
1394 /////////////////////////////////////////////////////////////////////////////
1395 // The Option Iterators
1396 /////////////////////////////////////////////////////////////////////////////
1398 #[derive(Clone, Debug)]
1403 impl<A> Iterator for Item<A> {
1407 fn next(&mut self) -> Option<A> {
1412 fn size_hint(&self) -> (usize, Option<usize>) {
1414 Some(_) => (1, Some(1)),
1415 None => (0, Some(0)),
1420 impl<A> DoubleEndedIterator for Item<A> {
1422 fn next_back(&mut self) -> Option<A> {
1427 impl<A> ExactSizeIterator for Item<A> {}
1428 impl<A> FusedIterator for Item<A> {}
1429 unsafe impl<A> TrustedLen for Item<A> {}
1431 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
1433 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1435 /// This `struct` is created by the [`Option::iter`] function.
1436 #[stable(feature = "rust1", since = "1.0.0")]
1438 pub struct Iter<'a, A: 'a> {
1442 #[stable(feature = "rust1", since = "1.0.0")]
1443 impl<'a, A> Iterator for Iter<'a, A> {
1447 fn next(&mut self) -> Option<&'a A> {
1451 fn size_hint(&self) -> (usize, Option<usize>) {
1452 self.inner.size_hint()
1456 #[stable(feature = "rust1", since = "1.0.0")]
1457 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
1459 fn next_back(&mut self) -> Option<&'a A> {
1460 self.inner.next_back()
1464 #[stable(feature = "rust1", since = "1.0.0")]
1465 impl<A> ExactSizeIterator for Iter<'_, A> {}
1467 #[stable(feature = "fused", since = "1.26.0")]
1468 impl<A> FusedIterator for Iter<'_, A> {}
1470 #[unstable(feature = "trusted_len", issue = "37572")]
1471 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1473 #[stable(feature = "rust1", since = "1.0.0")]
1474 impl<A> Clone for Iter<'_, A> {
1476 fn clone(&self) -> Self {
1477 Iter { inner: self.inner.clone() }
1481 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
1483 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1485 /// This `struct` is created by the [`Option::iter_mut`] function.
1486 #[stable(feature = "rust1", since = "1.0.0")]
1488 pub struct IterMut<'a, A: 'a> {
1489 inner: Item<&'a mut A>,
1492 #[stable(feature = "rust1", since = "1.0.0")]
1493 impl<'a, A> Iterator for IterMut<'a, A> {
1494 type Item = &'a mut A;
1497 fn next(&mut self) -> Option<&'a mut A> {
1501 fn size_hint(&self) -> (usize, Option<usize>) {
1502 self.inner.size_hint()
1506 #[stable(feature = "rust1", since = "1.0.0")]
1507 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
1509 fn next_back(&mut self) -> Option<&'a mut A> {
1510 self.inner.next_back()
1514 #[stable(feature = "rust1", since = "1.0.0")]
1515 impl<A> ExactSizeIterator for IterMut<'_, A> {}
1517 #[stable(feature = "fused", since = "1.26.0")]
1518 impl<A> FusedIterator for IterMut<'_, A> {}
1519 #[unstable(feature = "trusted_len", issue = "37572")]
1520 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1522 /// An iterator over the value in [`Some`] variant of an [`Option`].
1524 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1526 /// This `struct` is created by the [`Option::into_iter`] function.
1527 #[derive(Clone, Debug)]
1528 #[stable(feature = "rust1", since = "1.0.0")]
1529 pub struct IntoIter<A> {
1533 #[stable(feature = "rust1", since = "1.0.0")]
1534 impl<A> Iterator for IntoIter<A> {
1538 fn next(&mut self) -> Option<A> {
1542 fn size_hint(&self) -> (usize, Option<usize>) {
1543 self.inner.size_hint()
1547 #[stable(feature = "rust1", since = "1.0.0")]
1548 impl<A> DoubleEndedIterator for IntoIter<A> {
1550 fn next_back(&mut self) -> Option<A> {
1551 self.inner.next_back()
1555 #[stable(feature = "rust1", since = "1.0.0")]
1556 impl<A> ExactSizeIterator for IntoIter<A> {}
1558 #[stable(feature = "fused", since = "1.26.0")]
1559 impl<A> FusedIterator for IntoIter<A> {}
1561 #[unstable(feature = "trusted_len", issue = "37572")]
1562 unsafe impl<A> TrustedLen for IntoIter<A> {}
1564 /////////////////////////////////////////////////////////////////////////////
1566 /////////////////////////////////////////////////////////////////////////////
1568 #[stable(feature = "rust1", since = "1.0.0")]
1569 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
1570 /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
1571 /// no further elements are taken, and the [`None`][Option::None] is
1572 /// returned. Should no [`None`][Option::None] occur, a container with the
1573 /// values of each [`Option`] is returned.
1577 /// Here is an example which increments every integer in a vector.
1578 /// We use the checked variant of `add` that returns `None` when the
1579 /// calculation would result in an overflow.
1582 /// let items = vec![0_u16, 1, 2];
1584 /// let res: Option<Vec<u16>> = items
1586 /// .map(|x| x.checked_add(1))
1589 /// assert_eq!(res, Some(vec![1, 2, 3]));
1592 /// As you can see, this will return the expected, valid items.
1594 /// Here is another example that tries to subtract one from another list
1595 /// of integers, this time checking for underflow:
1598 /// let items = vec![2_u16, 1, 0];
1600 /// let res: Option<Vec<u16>> = items
1602 /// .map(|x| x.checked_sub(1))
1605 /// assert_eq!(res, None);
1608 /// Since the last element is zero, it would underflow. Thus, the resulting
1609 /// value is `None`.
1611 /// Here is a variation on the previous example, showing that no
1612 /// further elements are taken from `iter` after the first `None`.
1615 /// let items = vec![3_u16, 2, 1, 10];
1617 /// let mut shared = 0;
1619 /// let res: Option<Vec<u16>> = items
1621 /// .map(|x| { shared += x; x.checked_sub(2) })
1624 /// assert_eq!(res, None);
1625 /// assert_eq!(shared, 6);
1628 /// Since the third element caused an underflow, no further elements were taken,
1629 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1631 fn from_iter<I: IntoIterator<Item = Option<A>>>(iter: I) -> Option<V> {
1632 // FIXME(#11084): This could be replaced with Iterator::scan when this
1633 // performance bug is closed.
1635 iter.into_iter().map(|x| x.ok_or(())).collect::<Result<_, _>>().ok()
1639 /// The error type that results from applying the try operator (`?`) to a `None` value. If you wish
1640 /// to allow `x?` (where `x` is an `Option<T>`) to be converted into your error type, you can
1641 /// implement `impl From<NoneError>` for `YourErrorType`. In that case, `x?` within a function that
1642 /// returns `Result<_, YourErrorType>` will translate a `None` value into an `Err` result.
1643 #[rustc_diagnostic_item = "none_error"]
1644 #[unstable(feature = "try_trait", issue = "42327")]
1645 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
1647 pub struct NoneError;
1649 #[unstable(feature = "try_trait", issue = "42327")]
1651 impl<T> ops::TryV1 for Option<T> {
1653 type Error = NoneError;
1656 fn into_result(self) -> Result<T, NoneError> {
1657 self.ok_or(NoneError)
1661 fn from_ok(v: T) -> Self {
1666 fn from_error(_: NoneError) -> Self {
1671 #[unstable(feature = "try_trait_v2", issue = "84277")]
1672 impl<T> ops::TryV2 for Option<T> {
1674 type Residual = Option<convert::Infallible>;
1677 fn from_output(output: Self::Output) -> Self {
1682 fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
1684 Some(v) => ControlFlow::Continue(v),
1685 None => ControlFlow::Break(None),
1690 #[unstable(feature = "try_trait_v2", issue = "84277")]
1691 impl<T> ops::FromResidual for Option<T> {
1693 fn from_residual(residual: Option<convert::Infallible>) -> Self {
1700 impl<T> Option<Option<T>> {
1701 /// Converts from `Option<Option<T>>` to `Option<T>`
1708 /// let x: Option<Option<u32>> = Some(Some(6));
1709 /// assert_eq!(Some(6), x.flatten());
1711 /// let x: Option<Option<u32>> = Some(None);
1712 /// assert_eq!(None, x.flatten());
1714 /// let x: Option<Option<u32>> = None;
1715 /// assert_eq!(None, x.flatten());
1718 /// Flattening only removes one level of nesting at a time:
1721 /// let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
1722 /// assert_eq!(Some(Some(6)), x.flatten());
1723 /// assert_eq!(Some(6), x.flatten().flatten());
1726 #[stable(feature = "option_flattening", since = "1.40.0")]
1727 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1728 pub const fn flatten(self) -> Option<T> {
1730 Some(inner) => inner,