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"),
73 //! This usage of [`Option`] to create safe nullable pointers is so
74 //! common that Rust does special optimizations to make the
75 //! representation of [`Option`]`<`[`Box<T>`]`>` a single pointer. Optional pointers
76 //! in Rust are stored as efficiently as any other pointer type.
80 //! Basic pattern matching on [`Option`]:
83 //! let msg = Some("howdy");
85 //! // Take a reference to the contained string
86 //! if let Some(m) = &msg {
87 //! println!("{}", *m);
90 //! // Remove the contained string, destroying the Option
91 //! let unwrapped_msg = msg.unwrap_or("default message");
94 //! Initialize a result to [`None`] before a loop:
97 //! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) }
99 //! // A list of data to search through.
100 //! let all_the_big_things = [
101 //! Kingdom::Plant(250, "redwood"),
102 //! Kingdom::Plant(230, "noble fir"),
103 //! Kingdom::Plant(229, "sugar pine"),
104 //! Kingdom::Animal(25, "blue whale"),
105 //! Kingdom::Animal(19, "fin whale"),
106 //! Kingdom::Animal(15, "north pacific right whale"),
109 //! // We're going to search for the name of the biggest animal,
110 //! // but to start with we've just got `None`.
111 //! let mut name_of_biggest_animal = None;
112 //! let mut size_of_biggest_animal = 0;
113 //! for big_thing in &all_the_big_things {
114 //! match *big_thing {
115 //! Kingdom::Animal(size, name) if size > size_of_biggest_animal => {
116 //! // Now we've found the name of some big animal
117 //! size_of_biggest_animal = size;
118 //! name_of_biggest_animal = Some(name);
120 //! Kingdom::Animal(..) | Kingdom::Plant(..) => ()
124 //! match name_of_biggest_animal {
125 //! Some(name) => println!("the biggest animal is {}", name),
126 //! None => println!("there are no animals :("),
130 //! [`Option`]: enum.Option.html
131 //! [`Some`]: enum.Option.html#variant.Some
132 //! [`None`]: enum.Option.html#variant.None
133 //! [`Box<T>`]: ../../std/boxed/struct.Box.html
134 //! [`i32`]: ../../std/primitive.i32.html
136 #![stable(feature = "rust1", since = "1.0.0")]
138 use crate::iter::{FromIterator, FusedIterator, TrustedLen};
141 convert, fmt, hint, mem,
142 ops::{self, Deref, DerefMut},
145 // Note that this is not a lang item per se, but it has a hidden dependency on
146 // `Iterator`, which is one. The compiler assumes that the `next` method of
147 // `Iterator` is an enumeration with one type parameter and two variants,
148 // which basically means it must be `Option`.
150 /// The `Option` type. See [the module level documentation](index.html) for more.
151 #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
152 #[rustc_diagnostic_item = "option_type"]
153 #[stable(feature = "rust1", since = "1.0.0")]
156 #[stable(feature = "rust1", since = "1.0.0")]
159 #[stable(feature = "rust1", since = "1.0.0")]
160 Some(#[stable(feature = "rust1", since = "1.0.0")] T),
163 /////////////////////////////////////////////////////////////////////////////
164 // Type implementation
165 /////////////////////////////////////////////////////////////////////////////
168 /////////////////////////////////////////////////////////////////////////
169 // Querying the contained values
170 /////////////////////////////////////////////////////////////////////////
172 /// Returns `true` if the option is a [`Some`] value.
177 /// let x: Option<u32> = Some(2);
178 /// assert_eq!(x.is_some(), true);
180 /// let x: Option<u32> = None;
181 /// assert_eq!(x.is_some(), false);
184 /// [`Some`]: #variant.Some
185 #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"]
187 #[stable(feature = "rust1", since = "1.0.0")]
188 pub fn is_some(&self) -> bool {
189 matches!(*self, Some(_))
192 /// Returns `true` if the option is a [`None`] value.
197 /// let x: Option<u32> = Some(2);
198 /// assert_eq!(x.is_none(), false);
200 /// let x: Option<u32> = None;
201 /// assert_eq!(x.is_none(), true);
204 /// [`None`]: #variant.None
205 #[must_use = "if you intended to assert that this doesn't have a value, consider \
206 `.and_then(|| panic!(\"`Option` had a value when expected `None`\"))` instead"]
208 #[stable(feature = "rust1", since = "1.0.0")]
209 pub fn is_none(&self) -> bool {
213 /// Returns `true` if the option is a [`Some`] value containing the given value.
218 /// #![feature(option_result_contains)]
220 /// let x: Option<u32> = Some(2);
221 /// assert_eq!(x.contains(&2), true);
223 /// let x: Option<u32> = Some(3);
224 /// assert_eq!(x.contains(&2), false);
226 /// let x: Option<u32> = None;
227 /// assert_eq!(x.contains(&2), false);
231 #[unstable(feature = "option_result_contains", issue = "62358")]
232 pub fn contains<U>(&self, x: &U) -> bool
242 /////////////////////////////////////////////////////////////////////////
243 // Adapter for working with references
244 /////////////////////////////////////////////////////////////////////////
246 /// Converts from `&Option<T>` to `Option<&T>`.
250 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
251 /// The [`map`] method takes the `self` argument by value, consuming the original,
252 /// so this technique uses `as_ref` to first take an `Option` to a reference
253 /// to the value inside the original.
255 /// [`map`]: enum.Option.html#method.map
256 /// [`String`]: ../../std/string/struct.String.html
257 /// [`usize`]: ../../std/primitive.usize.html
260 /// let text: Option<String> = Some("Hello, world!".to_string());
261 /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
262 /// // then consume *that* with `map`, leaving `text` on the stack.
263 /// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
264 /// println!("still can print text: {:?}", text);
267 #[stable(feature = "rust1", since = "1.0.0")]
268 pub fn as_ref(&self) -> Option<&T> {
270 Some(ref x) => Some(x),
275 /// Converts from `&mut Option<T>` to `Option<&mut T>`.
280 /// let mut x = Some(2);
281 /// match x.as_mut() {
282 /// Some(v) => *v = 42,
285 /// assert_eq!(x, Some(42));
288 #[stable(feature = "rust1", since = "1.0.0")]
289 pub fn as_mut(&mut self) -> Option<&mut T> {
291 Some(ref mut x) => Some(x),
296 /// Converts from [`Pin`]`<&Option<T>>` to `Option<`[`Pin`]`<&T>>`.
298 /// [`Pin`]: ../pin/struct.Pin.html
300 #[stable(feature = "pin", since = "1.33.0")]
301 pub fn as_pin_ref(self: Pin<&Self>) -> Option<Pin<&T>> {
302 // SAFETY: `x` is guaranteed to be pinned because it comes from `self`
304 unsafe { Pin::get_ref(self).as_ref().map(|x| Pin::new_unchecked(x)) }
307 /// Converts from [`Pin`]`<&mut Option<T>>` to `Option<`[`Pin`]`<&mut T>>`.
309 /// [`Pin`]: ../pin/struct.Pin.html
311 #[stable(feature = "pin", since = "1.33.0")]
312 pub fn as_pin_mut(self: Pin<&mut Self>) -> Option<Pin<&mut T>> {
313 // SAFETY: `get_unchecked_mut` is never used to move the `Option` inside `self`.
314 // `x` is guaranteed to be pinned because it comes from `self` which is pinned.
315 unsafe { Pin::get_unchecked_mut(self).as_mut().map(|x| Pin::new_unchecked(x)) }
318 /////////////////////////////////////////////////////////////////////////
319 // Getting to contained values
320 /////////////////////////////////////////////////////////////////////////
322 /// Returns the contained [`Some`] value, consuming the `self` value.
326 /// Panics if the value is a [`None`] with a custom panic message provided by
329 /// [`Some`]: #variant.Some
330 /// [`None`]: #variant.None
335 /// let x = Some("value");
336 /// assert_eq!(x.expect("fruits are healthy"), "value");
339 /// ```{.should_panic}
340 /// let x: Option<&str> = None;
341 /// x.expect("fruits are healthy"); // panics with `fruits are healthy`
345 #[stable(feature = "rust1", since = "1.0.0")]
346 pub fn expect(self, msg: &str) -> T {
349 None => expect_failed(msg),
353 /// Returns the contained [`Some`] value, consuming the `self` value.
355 /// Because this function may panic, its use is generally discouraged.
356 /// Instead, prefer to use pattern matching and handle the [`None`]
357 /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
358 /// [`unwrap_or_default`].
360 /// [`unwrap_or`]: #method.unwrap_or
361 /// [`unwrap_or_else`]: #method.unwrap_or_else
362 /// [`unwrap_or_default`]: #method.unwrap_or_default
366 /// Panics if the self value equals [`None`].
368 /// [`Some`]: #variant.Some
369 /// [`None`]: #variant.None
374 /// let x = Some("air");
375 /// assert_eq!(x.unwrap(), "air");
378 /// ```{.should_panic}
379 /// let x: Option<&str> = None;
380 /// assert_eq!(x.unwrap(), "air"); // fails
384 #[stable(feature = "rust1", since = "1.0.0")]
385 pub 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 /// [`Some`]: #variant.Some
399 /// [`unwrap_or_else`]: #method.unwrap_or_else
404 /// assert_eq!(Some("car").unwrap_or("bike"), "car");
405 /// assert_eq!(None.unwrap_or("bike"), "bike");
408 #[stable(feature = "rust1", since = "1.0.0")]
409 pub fn unwrap_or(self, default: T) -> T {
416 /// Returns the contained [`Some`] value or computes it from a closure.
422 /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
423 /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
426 #[stable(feature = "rust1", since = "1.0.0")]
427 pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
434 /////////////////////////////////////////////////////////////////////////
435 // Transforming contained values
436 /////////////////////////////////////////////////////////////////////////
438 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
442 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, consuming the original:
444 /// [`String`]: ../../std/string/struct.String.html
445 /// [`usize`]: ../../std/primitive.usize.html
448 /// let maybe_some_string = Some(String::from("Hello, World!"));
449 /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
450 /// let maybe_some_len = maybe_some_string.map(|s| s.len());
452 /// assert_eq!(maybe_some_len, Some(13));
455 #[stable(feature = "rust1", since = "1.0.0")]
456 pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
458 Some(x) => Some(f(x)),
463 /// Applies a function to the contained value (if any),
464 /// or returns the provided default (if not).
466 /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
467 /// the result of a function call, it is recommended to use [`map_or_else`],
468 /// which is lazily evaluated.
470 /// [`map_or_else`]: #method.map_or_else
475 /// let x = Some("foo");
476 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
478 /// let x: Option<&str> = None;
479 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
482 #[stable(feature = "rust1", since = "1.0.0")]
483 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
490 /// Applies a function to the contained value (if any),
491 /// or computes a default (if not).
498 /// let x = Some("foo");
499 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
501 /// let x: Option<&str> = None;
502 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
505 #[stable(feature = "rust1", since = "1.0.0")]
506 pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
513 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
514 /// [`Ok(v)`] and [`None`] to [`Err(err)`].
516 /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
517 /// result of a function call, it is recommended to use [`ok_or_else`], which is
518 /// lazily evaluated.
520 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
521 /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
522 /// [`Err(err)`]: ../../std/result/enum.Result.html#variant.Err
523 /// [`None`]: #variant.None
524 /// [`Some(v)`]: #variant.Some
525 /// [`ok_or_else`]: #method.ok_or_else
530 /// let x = Some("foo");
531 /// assert_eq!(x.ok_or(0), Ok("foo"));
533 /// let x: Option<&str> = None;
534 /// assert_eq!(x.ok_or(0), Err(0));
537 #[stable(feature = "rust1", since = "1.0.0")]
538 pub fn ok_or<E>(self, err: E) -> Result<T, E> {
545 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
546 /// [`Ok(v)`] and [`None`] to [`Err(err())`].
548 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
549 /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
550 /// [`Err(err())`]: ../../std/result/enum.Result.html#variant.Err
551 /// [`None`]: #variant.None
552 /// [`Some(v)`]: #variant.Some
557 /// let x = Some("foo");
558 /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
560 /// let x: Option<&str> = None;
561 /// assert_eq!(x.ok_or_else(|| 0), Err(0));
564 #[stable(feature = "rust1", since = "1.0.0")]
565 pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
572 /////////////////////////////////////////////////////////////////////////
573 // Iterator constructors
574 /////////////////////////////////////////////////////////////////////////
576 /// Returns an iterator over the possibly contained value.
582 /// assert_eq!(x.iter().next(), Some(&4));
584 /// let x: Option<u32> = None;
585 /// assert_eq!(x.iter().next(), None);
588 #[stable(feature = "rust1", since = "1.0.0")]
589 pub fn iter(&self) -> Iter<'_, T> {
590 Iter { inner: Item { opt: self.as_ref() } }
593 /// Returns a mutable iterator over the possibly contained value.
598 /// let mut x = Some(4);
599 /// match x.iter_mut().next() {
600 /// Some(v) => *v = 42,
603 /// assert_eq!(x, Some(42));
605 /// let mut x: Option<u32> = None;
606 /// assert_eq!(x.iter_mut().next(), None);
609 #[stable(feature = "rust1", since = "1.0.0")]
610 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
611 IterMut { inner: Item { opt: self.as_mut() } }
614 /////////////////////////////////////////////////////////////////////////
615 // Boolean operations on the values, eager and lazy
616 /////////////////////////////////////////////////////////////////////////
618 /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
620 /// [`None`]: #variant.None
626 /// let y: Option<&str> = None;
627 /// assert_eq!(x.and(y), None);
629 /// let x: Option<u32> = None;
630 /// let y = Some("foo");
631 /// assert_eq!(x.and(y), None);
634 /// let y = Some("foo");
635 /// assert_eq!(x.and(y), Some("foo"));
637 /// let x: Option<u32> = None;
638 /// let y: Option<&str> = None;
639 /// assert_eq!(x.and(y), None);
642 #[stable(feature = "rust1", since = "1.0.0")]
643 pub fn and<U>(self, optb: Option<U>) -> Option<U> {
650 /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
651 /// wrapped value and returns the result.
653 /// Some languages call this operation flatmap.
655 /// [`None`]: #variant.None
660 /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
661 /// fn nope(_: u32) -> Option<u32> { None }
663 /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
664 /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
665 /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
666 /// assert_eq!(None.and_then(sq).and_then(sq), None);
669 #[stable(feature = "rust1", since = "1.0.0")]
670 pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> {
677 /// Returns [`None`] if the option is [`None`], otherwise calls `predicate`
678 /// with the wrapped value and returns:
680 /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped
682 /// - [`None`] if `predicate` returns `false`.
684 /// This function works similar to [`Iterator::filter()`]. You can imagine
685 /// the `Option<T>` being an iterator over one or zero elements. `filter()`
686 /// lets you decide which elements to keep.
691 /// fn is_even(n: &i32) -> bool {
695 /// assert_eq!(None.filter(is_even), None);
696 /// assert_eq!(Some(3).filter(is_even), None);
697 /// assert_eq!(Some(4).filter(is_even), Some(4));
700 /// [`None`]: #variant.None
701 /// [`Some(t)`]: #variant.Some
702 /// [`Iterator::filter()`]: ../../std/iter/trait.Iterator.html#method.filter
704 #[stable(feature = "option_filter", since = "1.27.0")]
705 pub fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Self {
706 if let Some(x) = self {
714 /// Returns the option if it contains a value, otherwise returns `optb`.
716 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
717 /// result of a function call, it is recommended to use [`or_else`], which is
718 /// lazily evaluated.
720 /// [`or_else`]: #method.or_else
727 /// assert_eq!(x.or(y), Some(2));
730 /// let y = Some(100);
731 /// assert_eq!(x.or(y), Some(100));
734 /// let y = Some(100);
735 /// assert_eq!(x.or(y), Some(2));
737 /// let x: Option<u32> = None;
739 /// assert_eq!(x.or(y), None);
742 #[stable(feature = "rust1", since = "1.0.0")]
743 pub fn or(self, optb: Option<T>) -> Option<T> {
750 /// Returns the option if it contains a value, otherwise calls `f` and
751 /// returns the result.
756 /// fn nobody() -> Option<&'static str> { None }
757 /// fn vikings() -> Option<&'static str> { Some("vikings") }
759 /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
760 /// assert_eq!(None.or_else(vikings), Some("vikings"));
761 /// assert_eq!(None.or_else(nobody), None);
764 #[stable(feature = "rust1", since = "1.0.0")]
765 pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> {
772 /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`].
774 /// [`Some`]: #variant.Some
775 /// [`None`]: #variant.None
781 /// let y: Option<u32> = None;
782 /// assert_eq!(x.xor(y), Some(2));
784 /// let x: Option<u32> = None;
786 /// assert_eq!(x.xor(y), Some(2));
790 /// assert_eq!(x.xor(y), None);
792 /// let x: Option<u32> = None;
793 /// let y: Option<u32> = None;
794 /// assert_eq!(x.xor(y), None);
797 #[stable(feature = "option_xor", since = "1.37.0")]
798 pub fn xor(self, optb: Option<T>) -> Option<T> {
800 (Some(a), None) => Some(a),
801 (None, Some(b)) => Some(b),
806 /////////////////////////////////////////////////////////////////////////
807 // Entry-like operations to insert if None and return a reference
808 /////////////////////////////////////////////////////////////////////////
810 /// Inserts `v` into the option if it is [`None`], then
811 /// returns a mutable reference to the contained value.
813 /// [`None`]: #variant.None
818 /// let mut x = None;
821 /// let y: &mut u32 = x.get_or_insert(5);
822 /// assert_eq!(y, &5);
827 /// assert_eq!(x, Some(7));
830 #[stable(feature = "option_entry", since = "1.20.0")]
831 pub fn get_or_insert(&mut self, v: T) -> &mut T {
832 self.get_or_insert_with(|| v)
835 /// Inserts a value computed from `f` into the option if it is [`None`], then
836 /// returns a mutable reference to the contained value.
838 /// [`None`]: #variant.None
843 /// let mut x = None;
846 /// let y: &mut u32 = x.get_or_insert_with(|| 5);
847 /// assert_eq!(y, &5);
852 /// assert_eq!(x, Some(7));
855 #[stable(feature = "option_entry", since = "1.20.0")]
856 pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
857 if let None = *self {
862 Some(ref mut v) => v,
863 // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
864 // variant in the code above.
865 None => unsafe { hint::unreachable_unchecked() },
869 /////////////////////////////////////////////////////////////////////////
871 /////////////////////////////////////////////////////////////////////////
873 /// Takes the value out of the option, leaving a [`None`] in its place.
875 /// [`None`]: #variant.None
880 /// let mut x = Some(2);
881 /// let y = x.take();
882 /// assert_eq!(x, None);
883 /// assert_eq!(y, Some(2));
885 /// let mut x: Option<u32> = None;
886 /// let y = x.take();
887 /// assert_eq!(x, None);
888 /// assert_eq!(y, None);
891 #[stable(feature = "rust1", since = "1.0.0")]
892 pub fn take(&mut self) -> Option<T> {
896 /// Replaces the actual value in the option by the value given in parameter,
897 /// returning the old value if present,
898 /// leaving a [`Some`] in its place without deinitializing either one.
900 /// [`Some`]: #variant.Some
905 /// let mut x = Some(2);
906 /// let old = x.replace(5);
907 /// assert_eq!(x, Some(5));
908 /// assert_eq!(old, Some(2));
910 /// let mut x = None;
911 /// let old = x.replace(3);
912 /// assert_eq!(x, Some(3));
913 /// assert_eq!(old, None);
916 #[stable(feature = "option_replace", since = "1.31.0")]
917 pub fn replace(&mut self, value: T) -> Option<T> {
918 mem::replace(self, Some(value))
921 /// Zips `self` with another `Option`.
923 /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some((s, o))`.
924 /// Otherwise, `None` is returned.
929 /// #![feature(option_zip)]
931 /// let y = Some("hi");
932 /// let z = None::<u8>;
934 /// assert_eq!(x.zip(y), Some((1, "hi")));
935 /// assert_eq!(x.zip(z), None);
937 #[unstable(feature = "option_zip", issue = "70086")]
938 pub fn zip<U>(self, other: Option<U>) -> Option<(T, U)> {
939 self.zip_with(other, |a, b| (a, b))
942 /// Zips `self` and another `Option` with function `f`.
944 /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
945 /// Otherwise, `None` is returned.
950 /// #![feature(option_zip)]
952 /// #[derive(Debug, PartialEq)]
959 /// fn new(x: f64, y: f64) -> Self {
964 /// let x = Some(17.5);
965 /// let y = Some(42.7);
967 /// assert_eq!(x.zip_with(y, Point::new), Some(Point { x: 17.5, y: 42.7 }));
968 /// assert_eq!(x.zip_with(None, Point::new), None);
970 #[unstable(feature = "option_zip", issue = "70086")]
971 pub fn zip_with<U, F, R>(self, other: Option<U>, f: F) -> Option<R>
973 F: FnOnce(T, U) -> R,
975 Some(f(self?, other?))
979 impl<T: Copy> Option<&T> {
980 /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
987 /// let opt_x = Some(&x);
988 /// assert_eq!(opt_x, Some(&12));
989 /// let copied = opt_x.copied();
990 /// assert_eq!(copied, Some(12));
992 #[stable(feature = "copied", since = "1.35.0")]
993 pub fn copied(self) -> Option<T> {
998 impl<T: Copy> Option<&mut T> {
999 /// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the
1006 /// let opt_x = Some(&mut x);
1007 /// assert_eq!(opt_x, Some(&mut 12));
1008 /// let copied = opt_x.copied();
1009 /// assert_eq!(copied, Some(12));
1011 #[stable(feature = "copied", since = "1.35.0")]
1012 pub fn copied(self) -> Option<T> {
1013 self.map(|&mut t| t)
1017 impl<T: Clone> Option<&T> {
1018 /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
1025 /// let opt_x = Some(&x);
1026 /// assert_eq!(opt_x, Some(&12));
1027 /// let cloned = opt_x.cloned();
1028 /// assert_eq!(cloned, Some(12));
1030 #[stable(feature = "rust1", since = "1.0.0")]
1031 pub fn cloned(self) -> Option<T> {
1032 self.map(|t| t.clone())
1036 impl<T: Clone> Option<&mut T> {
1037 /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
1044 /// let opt_x = Some(&mut x);
1045 /// assert_eq!(opt_x, Some(&mut 12));
1046 /// let cloned = opt_x.cloned();
1047 /// assert_eq!(cloned, Some(12));
1049 #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
1050 pub fn cloned(self) -> Option<T> {
1051 self.map(|t| t.clone())
1055 impl<T: fmt::Debug> Option<T> {
1056 /// Consumes `self` while expecting [`None`] and returning nothing.
1060 /// Panics if the value is a [`Some`], with a panic message including the
1061 /// passed message, and the content of the [`Some`].
1063 /// [`Some`]: #variant.Some
1064 /// [`None`]: #variant.None
1069 /// #![feature(option_expect_none)]
1071 /// use std::collections::HashMap;
1072 /// let mut squares = HashMap::new();
1073 /// for i in -10..=10 {
1074 /// // This will not panic, since all keys are unique.
1075 /// squares.insert(i, i * i).expect_none("duplicate key");
1079 /// ```{.should_panic}
1080 /// #![feature(option_expect_none)]
1082 /// use std::collections::HashMap;
1083 /// let mut sqrts = HashMap::new();
1084 /// for i in -10..=10 {
1085 /// // This will panic, since both negative and positive `i` will
1086 /// // insert the same `i * i` key, returning the old `Some(i)`.
1087 /// sqrts.insert(i * i, i).expect_none("duplicate key");
1092 #[unstable(feature = "option_expect_none", reason = "newly added", issue = "62633")]
1093 pub fn expect_none(self, msg: &str) {
1094 if let Some(val) = self {
1095 expect_none_failed(msg, &val);
1099 /// Consumes `self` while expecting [`None`] and returning nothing.
1103 /// Panics if the value is a [`Some`], with a custom panic message provided
1104 /// by the [`Some`]'s value.
1106 /// [`Some(v)`]: #variant.Some
1107 /// [`None`]: #variant.None
1112 /// #![feature(option_unwrap_none)]
1114 /// use std::collections::HashMap;
1115 /// let mut squares = HashMap::new();
1116 /// for i in -10..=10 {
1117 /// // This will not panic, since all keys are unique.
1118 /// squares.insert(i, i * i).unwrap_none();
1122 /// ```{.should_panic}
1123 /// #![feature(option_unwrap_none)]
1125 /// use std::collections::HashMap;
1126 /// let mut sqrts = HashMap::new();
1127 /// for i in -10..=10 {
1128 /// // This will panic, since both negative and positive `i` will
1129 /// // insert the same `i * i` key, returning the old `Some(i)`.
1130 /// sqrts.insert(i * i, i).unwrap_none();
1135 #[unstable(feature = "option_unwrap_none", reason = "newly added", issue = "62633")]
1136 pub fn unwrap_none(self) {
1137 if let Some(val) = self {
1138 expect_none_failed("called `Option::unwrap_none()` on a `Some` value", &val);
1143 impl<T: Default> Option<T> {
1144 /// Returns the contained [`Some`] value or a default
1146 /// Consumes the `self` argument then, if [`Some`], returns the contained
1147 /// value, otherwise if [`None`], returns the [default value] for that
1152 /// Converts a string to an integer, turning poorly-formed strings
1153 /// into 0 (the default value for integers). [`parse`] converts
1154 /// a string to any other type that implements [`FromStr`], returning
1155 /// [`None`] on error.
1158 /// let good_year_from_input = "1909";
1159 /// let bad_year_from_input = "190blarg";
1160 /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
1161 /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
1163 /// assert_eq!(1909, good_year);
1164 /// assert_eq!(0, bad_year);
1167 /// [`Some`]: #variant.Some
1168 /// [`None`]: #variant.None
1169 /// [default value]: ../default/trait.Default.html#tymethod.default
1170 /// [`parse`]: ../../std/primitive.str.html#method.parse
1171 /// [`FromStr`]: ../../std/str/trait.FromStr.html
1173 #[stable(feature = "rust1", since = "1.0.0")]
1174 pub fn unwrap_or_default(self) -> T {
1177 None => Default::default(),
1182 impl<T: Deref> Option<T> {
1183 /// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.
1185 /// Leaves the original Option in-place, creating a new one with a reference
1186 /// to the original one, additionally coercing the contents via [`Deref`].
1188 /// [`Deref`]: ../../std/ops/trait.Deref.html
1193 /// let x: Option<String> = Some("hey".to_owned());
1194 /// assert_eq!(x.as_deref(), Some("hey"));
1196 /// let x: Option<String> = None;
1197 /// assert_eq!(x.as_deref(), None);
1199 #[stable(feature = "option_deref", since = "1.40.0")]
1200 pub fn as_deref(&self) -> Option<&T::Target> {
1201 self.as_ref().map(|t| t.deref())
1205 impl<T: DerefMut> Option<T> {
1206 /// Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`.
1208 /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to
1209 /// the inner type's `Deref::Target` type.
1214 /// let mut x: Option<String> = Some("hey".to_owned());
1215 /// assert_eq!(x.as_deref_mut().map(|x| {
1216 /// x.make_ascii_uppercase();
1218 /// }), Some("HEY".to_owned().as_mut_str()));
1220 #[stable(feature = "option_deref", since = "1.40.0")]
1221 pub fn as_deref_mut(&mut self) -> Option<&mut T::Target> {
1222 self.as_mut().map(|t| t.deref_mut())
1226 impl<T, E> Option<Result<T, E>> {
1227 /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`.
1229 /// [`None`] will be mapped to [`Ok`]`(`[`None`]`)`.
1230 /// [`Some`]`(`[`Ok`]`(_))` and [`Some`]`(`[`Err`]`(_))` will be mapped to
1231 /// [`Ok`]`(`[`Some`]`(_))` and [`Err`]`(_)`.
1233 /// [`None`]: #variant.None
1234 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
1235 /// [`Some`]: #variant.Some
1236 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1241 /// #[derive(Debug, Eq, PartialEq)]
1244 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1245 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1246 /// assert_eq!(x, y.transpose());
1249 #[stable(feature = "transpose_result", since = "1.33.0")]
1250 pub fn transpose(self) -> Result<Option<T>, E> {
1252 Some(Ok(x)) => Ok(Some(x)),
1253 Some(Err(e)) => Err(e),
1259 // This is a separate function to reduce the code size of .expect() itself.
1263 fn expect_failed(msg: &str) -> ! {
1267 // This is a separate function to reduce the code size of .expect_none() itself.
1271 fn expect_none_failed(msg: &str, value: &dyn fmt::Debug) -> ! {
1272 panic!("{}: {:?}", msg, value)
1275 /////////////////////////////////////////////////////////////////////////////
1276 // Trait implementations
1277 /////////////////////////////////////////////////////////////////////////////
1279 #[stable(feature = "rust1", since = "1.0.0")]
1280 impl<T: Clone> Clone for Option<T> {
1282 fn clone(&self) -> Self {
1284 Some(x) => Some(x.clone()),
1290 fn clone_from(&mut self, source: &Self) {
1291 match (self, source) {
1292 (Some(to), Some(from)) => to.clone_from(from),
1293 (to, from) => *to = from.clone(),
1298 #[stable(feature = "rust1", since = "1.0.0")]
1299 impl<T> Default for Option<T> {
1300 /// Returns [`None`][Option::None].
1305 /// let opt: Option<u32> = Option::default();
1306 /// assert!(opt.is_none());
1309 fn default() -> Option<T> {
1314 #[stable(feature = "rust1", since = "1.0.0")]
1315 impl<T> IntoIterator for Option<T> {
1317 type IntoIter = IntoIter<T>;
1319 /// Returns a consuming iterator over the possibly contained value.
1324 /// let x = Some("string");
1325 /// let v: Vec<&str> = x.into_iter().collect();
1326 /// assert_eq!(v, ["string"]);
1329 /// let v: Vec<&str> = x.into_iter().collect();
1330 /// assert!(v.is_empty());
1333 fn into_iter(self) -> IntoIter<T> {
1334 IntoIter { inner: Item { opt: self } }
1338 #[stable(since = "1.4.0", feature = "option_iter")]
1339 impl<'a, T> IntoIterator for &'a Option<T> {
1341 type IntoIter = Iter<'a, T>;
1343 fn into_iter(self) -> Iter<'a, T> {
1348 #[stable(since = "1.4.0", feature = "option_iter")]
1349 impl<'a, T> IntoIterator for &'a mut Option<T> {
1350 type Item = &'a mut T;
1351 type IntoIter = IterMut<'a, T>;
1353 fn into_iter(self) -> IterMut<'a, T> {
1358 #[stable(since = "1.12.0", feature = "option_from")]
1359 impl<T> From<T> for Option<T> {
1360 /// Copies `val` into a new `Some`.
1365 /// let o: Option<u8> = Option::from(67);
1367 /// assert_eq!(Some(67), o);
1369 fn from(val: T) -> Option<T> {
1374 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1375 impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
1376 /// Converts from `&Option<T>` to `Option<&T>`.
1380 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
1381 /// The [`map`] method takes the `self` argument by value, consuming the original,
1382 /// so this technique uses `as_ref` to first take an `Option` to a reference
1383 /// to the value inside the original.
1385 /// [`map`]: ../../std/option/enum.Option.html#method.map
1386 /// [`String`]: ../../std/string/struct.String.html
1387 /// [`usize`]: ../../std/primitive.usize.html
1390 /// let s: Option<String> = Some(String::from("Hello, Rustaceans!"));
1391 /// let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());
1393 /// println!("Can still print s: {:?}", s);
1395 /// assert_eq!(o, Some(18));
1397 fn from(o: &'a Option<T>) -> Option<&'a T> {
1402 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1403 impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> {
1404 /// Converts from `&mut Option<T>` to `Option<&mut T>`
1409 /// let mut s = Some(String::from("Hello"));
1410 /// let o: Option<&mut String> = Option::from(&mut s);
1413 /// Some(t) => *t = String::from("Hello, Rustaceans!"),
1417 /// assert_eq!(s, Some(String::from("Hello, Rustaceans!")));
1419 fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
1424 /////////////////////////////////////////////////////////////////////////////
1425 // The Option Iterators
1426 /////////////////////////////////////////////////////////////////////////////
1428 #[derive(Clone, Debug)]
1433 impl<A> Iterator for Item<A> {
1437 fn next(&mut self) -> Option<A> {
1442 fn size_hint(&self) -> (usize, Option<usize>) {
1444 Some(_) => (1, Some(1)),
1445 None => (0, Some(0)),
1450 impl<A> DoubleEndedIterator for Item<A> {
1452 fn next_back(&mut self) -> Option<A> {
1457 impl<A> ExactSizeIterator for Item<A> {}
1458 impl<A> FusedIterator for Item<A> {}
1459 unsafe impl<A> TrustedLen for Item<A> {}
1461 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
1463 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1465 /// This `struct` is created by the [`Option::iter`] function.
1467 /// [`Option`]: enum.Option.html
1468 /// [`Some`]: enum.Option.html#variant.Some
1469 /// [`Option::iter`]: enum.Option.html#method.iter
1470 #[stable(feature = "rust1", since = "1.0.0")]
1472 pub struct Iter<'a, A: 'a> {
1476 #[stable(feature = "rust1", since = "1.0.0")]
1477 impl<'a, A> Iterator for Iter<'a, A> {
1481 fn next(&mut self) -> Option<&'a A> {
1485 fn size_hint(&self) -> (usize, Option<usize>) {
1486 self.inner.size_hint()
1490 #[stable(feature = "rust1", since = "1.0.0")]
1491 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
1493 fn next_back(&mut self) -> Option<&'a A> {
1494 self.inner.next_back()
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 impl<A> ExactSizeIterator for Iter<'_, A> {}
1501 #[stable(feature = "fused", since = "1.26.0")]
1502 impl<A> FusedIterator for Iter<'_, A> {}
1504 #[unstable(feature = "trusted_len", issue = "37572")]
1505 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1507 #[stable(feature = "rust1", since = "1.0.0")]
1508 impl<A> Clone for Iter<'_, A> {
1510 fn clone(&self) -> Self {
1511 Iter { inner: self.inner.clone() }
1515 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
1517 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1519 /// This `struct` is created by the [`Option::iter_mut`] function.
1521 /// [`Option`]: enum.Option.html
1522 /// [`Some`]: enum.Option.html#variant.Some
1523 /// [`Option::iter_mut`]: enum.Option.html#method.iter_mut
1524 #[stable(feature = "rust1", since = "1.0.0")]
1526 pub struct IterMut<'a, A: 'a> {
1527 inner: Item<&'a mut A>,
1530 #[stable(feature = "rust1", since = "1.0.0")]
1531 impl<'a, A> Iterator for IterMut<'a, A> {
1532 type Item = &'a mut A;
1535 fn next(&mut self) -> Option<&'a mut A> {
1539 fn size_hint(&self) -> (usize, Option<usize>) {
1540 self.inner.size_hint()
1544 #[stable(feature = "rust1", since = "1.0.0")]
1545 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
1547 fn next_back(&mut self) -> Option<&'a mut A> {
1548 self.inner.next_back()
1552 #[stable(feature = "rust1", since = "1.0.0")]
1553 impl<A> ExactSizeIterator for IterMut<'_, A> {}
1555 #[stable(feature = "fused", since = "1.26.0")]
1556 impl<A> FusedIterator for IterMut<'_, A> {}
1557 #[unstable(feature = "trusted_len", issue = "37572")]
1558 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1560 /// An iterator over the value in [`Some`] variant of an [`Option`].
1562 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1564 /// This `struct` is created by the [`Option::into_iter`] function.
1566 /// [`Option`]: enum.Option.html
1567 /// [`Some`]: enum.Option.html#variant.Some
1568 /// [`Option::into_iter`]: enum.Option.html#method.into_iter
1569 #[derive(Clone, Debug)]
1570 #[stable(feature = "rust1", since = "1.0.0")]
1571 pub struct IntoIter<A> {
1575 #[stable(feature = "rust1", since = "1.0.0")]
1576 impl<A> Iterator for IntoIter<A> {
1580 fn next(&mut self) -> Option<A> {
1584 fn size_hint(&self) -> (usize, Option<usize>) {
1585 self.inner.size_hint()
1589 #[stable(feature = "rust1", since = "1.0.0")]
1590 impl<A> DoubleEndedIterator for IntoIter<A> {
1592 fn next_back(&mut self) -> Option<A> {
1593 self.inner.next_back()
1597 #[stable(feature = "rust1", since = "1.0.0")]
1598 impl<A> ExactSizeIterator for IntoIter<A> {}
1600 #[stable(feature = "fused", since = "1.26.0")]
1601 impl<A> FusedIterator for IntoIter<A> {}
1603 #[unstable(feature = "trusted_len", issue = "37572")]
1604 unsafe impl<A> TrustedLen for IntoIter<A> {}
1606 /////////////////////////////////////////////////////////////////////////////
1608 /////////////////////////////////////////////////////////////////////////////
1610 #[stable(feature = "rust1", since = "1.0.0")]
1611 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
1612 /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
1613 /// no further elements are taken, and the [`None`][Option::None] is
1614 /// returned. Should no [`None`][Option::None] occur, a container with the
1615 /// values of each [`Option`] is returned.
1619 /// Here is an example which increments every integer in a vector.
1620 /// We use the checked variant of `add` that returns `None` when the
1621 /// calculation would result in an overflow.
1624 /// let items = vec![0_u16, 1, 2];
1626 /// let res: Option<Vec<u16>> = items
1628 /// .map(|x| x.checked_add(1))
1631 /// assert_eq!(res, Some(vec![1, 2, 3]));
1634 /// As you can see, this will return the expected, valid items.
1636 /// Here is another example that tries to subtract one from another list
1637 /// of integers, this time checking for underflow:
1640 /// let items = vec![2_u16, 1, 0];
1642 /// let res: Option<Vec<u16>> = items
1644 /// .map(|x| x.checked_sub(1))
1647 /// assert_eq!(res, None);
1650 /// Since the last element is zero, it would underflow. Thus, the resulting
1651 /// value is `None`.
1653 /// Here is a variation on the previous example, showing that no
1654 /// further elements are taken from `iter` after the first `None`.
1657 /// let items = vec![3_u16, 2, 1, 10];
1659 /// let mut shared = 0;
1661 /// let res: Option<Vec<u16>> = items
1663 /// .map(|x| { shared += x; x.checked_sub(2) })
1666 /// assert_eq!(res, None);
1667 /// assert_eq!(shared, 6);
1670 /// Since the third element caused an underflow, no further elements were taken,
1671 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1673 /// [`Iterator`]: ../iter/trait.Iterator.html
1675 fn from_iter<I: IntoIterator<Item = Option<A>>>(iter: I) -> Option<V> {
1676 // FIXME(#11084): This could be replaced with Iterator::scan when this
1677 // performance bug is closed.
1679 iter.into_iter().map(|x| x.ok_or(())).collect::<Result<_, _>>().ok()
1683 /// The error type that results from applying the try operator (`?`) to a `None` value. If you wish
1684 /// to allow `x?` (where `x` is an `Option<T>`) to be converted into your error type, you can
1685 /// implement `impl From<NoneError>` for `YourErrorType`. In that case, `x?` within a function that
1686 /// returns `Result<_, YourErrorType>` will translate a `None` value into an `Err` result.
1687 #[unstable(feature = "try_trait", issue = "42327")]
1688 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
1689 pub struct NoneError;
1691 #[unstable(feature = "try_trait", issue = "42327")]
1692 impl<T> ops::Try for Option<T> {
1694 type Error = NoneError;
1697 fn into_result(self) -> Result<T, NoneError> {
1698 self.ok_or(NoneError)
1702 fn from_ok(v: T) -> Self {
1707 fn from_error(_: NoneError) -> Self {
1712 impl<T> Option<Option<T>> {
1713 /// Converts from `Option<Option<T>>` to `Option<T>`
1718 /// let x: Option<Option<u32>> = Some(Some(6));
1719 /// assert_eq!(Some(6), x.flatten());
1721 /// let x: Option<Option<u32>> = Some(None);
1722 /// assert_eq!(None, x.flatten());
1724 /// let x: Option<Option<u32>> = None;
1725 /// assert_eq!(None, x.flatten());
1727 /// Flattening once only removes one level of nesting:
1729 /// let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
1730 /// assert_eq!(Some(Some(6)), x.flatten());
1731 /// assert_eq!(Some(6), x.flatten().flatten());
1734 #[stable(feature = "option_flattening", since = "1.40.0")]
1735 pub fn flatten(self) -> Option<T> {
1736 self.and_then(convert::identity)