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 // ignore-tidy-undocumented-unsafe
138 #![stable(feature = "rust1", since = "1.0.0")]
140 use crate::iter::{FromIterator, FusedIterator, TrustedLen};
143 convert, fmt, hint, mem,
144 ops::{self, Deref, DerefMut},
147 // Note that this is not a lang item per se, but it has a hidden dependency on
148 // `Iterator`, which is one. The compiler assumes that the `next` method of
149 // `Iterator` is an enumeration with one type parameter and two variants,
150 // which basically means it must be `Option`.
152 /// The `Option` type. See [the module level documentation](index.html) for more.
153 #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
154 #[rustc_diagnostic_item = "option_type"]
155 #[stable(feature = "rust1", since = "1.0.0")]
158 #[stable(feature = "rust1", since = "1.0.0")]
161 #[stable(feature = "rust1", since = "1.0.0")]
162 Some(#[stable(feature = "rust1", since = "1.0.0")] T),
165 /////////////////////////////////////////////////////////////////////////////
166 // Type implementation
167 /////////////////////////////////////////////////////////////////////////////
170 /////////////////////////////////////////////////////////////////////////
171 // Querying the contained values
172 /////////////////////////////////////////////////////////////////////////
174 /// Returns `true` if the option is a [`Some`] value.
179 /// let x: Option<u32> = Some(2);
180 /// assert_eq!(x.is_some(), true);
182 /// let x: Option<u32> = None;
183 /// assert_eq!(x.is_some(), false);
186 /// [`Some`]: #variant.Some
187 #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"]
189 #[stable(feature = "rust1", since = "1.0.0")]
190 pub fn is_some(&self) -> bool {
191 matches!(*self, Some(_))
194 /// Returns `true` if the option is a [`None`] value.
199 /// let x: Option<u32> = Some(2);
200 /// assert_eq!(x.is_none(), false);
202 /// let x: Option<u32> = None;
203 /// assert_eq!(x.is_none(), true);
206 /// [`None`]: #variant.None
207 #[must_use = "if you intended to assert that this doesn't have a value, consider \
208 `.and_then(|| panic!(\"`Option` had a value when expected `None`\"))` instead"]
210 #[stable(feature = "rust1", since = "1.0.0")]
211 pub fn is_none(&self) -> bool {
215 /// Returns `true` if the option is a [`Some`] value containing the given value.
220 /// #![feature(option_result_contains)]
222 /// let x: Option<u32> = Some(2);
223 /// assert_eq!(x.contains(&2), true);
225 /// let x: Option<u32> = Some(3);
226 /// assert_eq!(x.contains(&2), false);
228 /// let x: Option<u32> = None;
229 /// assert_eq!(x.contains(&2), false);
233 #[unstable(feature = "option_result_contains", issue = "62358")]
234 pub fn contains<U>(&self, x: &U) -> bool
244 /////////////////////////////////////////////////////////////////////////
245 // Adapter for working with references
246 /////////////////////////////////////////////////////////////////////////
248 /// Converts from `&Option<T>` to `Option<&T>`.
252 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
253 /// The [`map`] method takes the `self` argument by value, consuming the original,
254 /// so this technique uses `as_ref` to first take an `Option` to a reference
255 /// to the value inside the original.
257 /// [`map`]: enum.Option.html#method.map
258 /// [`String`]: ../../std/string/struct.String.html
259 /// [`usize`]: ../../std/primitive.usize.html
262 /// let text: Option<String> = Some("Hello, world!".to_string());
263 /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
264 /// // then consume *that* with `map`, leaving `text` on the stack.
265 /// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
266 /// println!("still can print text: {:?}", text);
269 #[stable(feature = "rust1", since = "1.0.0")]
270 pub fn as_ref(&self) -> Option<&T> {
272 Some(ref x) => Some(x),
277 /// Converts from `&mut Option<T>` to `Option<&mut T>`.
282 /// let mut x = Some(2);
283 /// match x.as_mut() {
284 /// Some(v) => *v = 42,
287 /// assert_eq!(x, Some(42));
290 #[stable(feature = "rust1", since = "1.0.0")]
291 pub fn as_mut(&mut self) -> Option<&mut T> {
293 Some(ref mut x) => Some(x),
298 /// Converts from [`Pin`]`<&Option<T>>` to `Option<`[`Pin`]`<&T>>`.
300 /// [`Pin`]: ../pin/struct.Pin.html
302 #[stable(feature = "pin", since = "1.33.0")]
303 pub fn as_pin_ref(self: Pin<&Self>) -> Option<Pin<&T>> {
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 unsafe { Pin::get_unchecked_mut(self).as_mut().map(|x| Pin::new_unchecked(x)) }
316 /////////////////////////////////////////////////////////////////////////
317 // Getting to contained values
318 /////////////////////////////////////////////////////////////////////////
320 /// Returns the contained [`Some`] value, consuming the `self` value.
324 /// Panics if the value is a [`None`] with a custom panic message provided by
327 /// [`Some`]: #variant.Some
328 /// [`None`]: #variant.None
333 /// let x = Some("value");
334 /// assert_eq!(x.expect("fruits are healthy"), "value");
337 /// ```{.should_panic}
338 /// let x: Option<&str> = None;
339 /// x.expect("fruits are healthy"); // panics with `fruits are healthy`
343 #[stable(feature = "rust1", since = "1.0.0")]
344 pub fn expect(self, msg: &str) -> T {
347 None => expect_failed(msg),
351 /// Returns the contained [`Some`] value, consuming the `self` value.
353 /// Because this function may panic, its use is generally discouraged.
354 /// Instead, prefer to use pattern matching and handle the [`None`]
355 /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
356 /// [`unwrap_or_default`].
358 /// [`unwrap_or`]: #method.unwrap_or
359 /// [`unwrap_or_else`]: #method.unwrap_or_else
360 /// [`unwrap_or_default`]: #method.unwrap_or_default
364 /// Panics if the self value equals [`None`].
366 /// [`Some`]: #variant.Some
367 /// [`None`]: #variant.None
372 /// let x = Some("air");
373 /// assert_eq!(x.unwrap(), "air");
376 /// ```{.should_panic}
377 /// let x: Option<&str> = None;
378 /// assert_eq!(x.unwrap(), "air"); // fails
382 #[stable(feature = "rust1", since = "1.0.0")]
383 pub fn unwrap(self) -> T {
386 None => panic!("called `Option::unwrap()` on a `None` value"),
390 /// Returns the contained [`Some`] value or a provided default.
392 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
393 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
394 /// which is lazily evaluated.
396 /// [`Some`]: #variant.Some
397 /// [`unwrap_or_else`]: #method.unwrap_or_else
402 /// assert_eq!(Some("car").unwrap_or("bike"), "car");
403 /// assert_eq!(None.unwrap_or("bike"), "bike");
406 #[stable(feature = "rust1", since = "1.0.0")]
407 pub fn unwrap_or(self, default: T) -> T {
414 /// Returns the contained [`Some`] value or computes it from a closure.
420 /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
421 /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
424 #[stable(feature = "rust1", since = "1.0.0")]
425 pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
432 /////////////////////////////////////////////////////////////////////////
433 // Transforming contained values
434 /////////////////////////////////////////////////////////////////////////
436 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
440 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, consuming the original:
442 /// [`String`]: ../../std/string/struct.String.html
443 /// [`usize`]: ../../std/primitive.usize.html
446 /// let maybe_some_string = Some(String::from("Hello, World!"));
447 /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
448 /// let maybe_some_len = maybe_some_string.map(|s| s.len());
450 /// assert_eq!(maybe_some_len, Some(13));
453 #[stable(feature = "rust1", since = "1.0.0")]
454 pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
456 Some(x) => Some(f(x)),
461 /// Applies a function to the contained value (if any),
462 /// or returns the provided default (if not).
464 /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
465 /// the result of a function call, it is recommended to use [`map_or_else`],
466 /// which is lazily evaluated.
468 /// [`map_or_else`]: #method.map_or_else
473 /// let x = Some("foo");
474 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
476 /// let x: Option<&str> = None;
477 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
480 #[stable(feature = "rust1", since = "1.0.0")]
481 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
488 /// Applies a function to the contained value (if any),
489 /// or computes a default (if not).
496 /// let x = Some("foo");
497 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
499 /// let x: Option<&str> = None;
500 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
503 #[stable(feature = "rust1", since = "1.0.0")]
504 pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
511 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
512 /// [`Ok(v)`] and [`None`] to [`Err(err)`].
514 /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
515 /// result of a function call, it is recommended to use [`ok_or_else`], which is
516 /// lazily evaluated.
518 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
519 /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
520 /// [`Err(err)`]: ../../std/result/enum.Result.html#variant.Err
521 /// [`None`]: #variant.None
522 /// [`Some(v)`]: #variant.Some
523 /// [`ok_or_else`]: #method.ok_or_else
528 /// let x = Some("foo");
529 /// assert_eq!(x.ok_or(0), Ok("foo"));
531 /// let x: Option<&str> = None;
532 /// assert_eq!(x.ok_or(0), Err(0));
535 #[stable(feature = "rust1", since = "1.0.0")]
536 pub fn ok_or<E>(self, err: E) -> Result<T, E> {
543 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
544 /// [`Ok(v)`] and [`None`] to [`Err(err())`].
546 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
547 /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
548 /// [`Err(err())`]: ../../std/result/enum.Result.html#variant.Err
549 /// [`None`]: #variant.None
550 /// [`Some(v)`]: #variant.Some
555 /// let x = Some("foo");
556 /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
558 /// let x: Option<&str> = None;
559 /// assert_eq!(x.ok_or_else(|| 0), Err(0));
562 #[stable(feature = "rust1", since = "1.0.0")]
563 pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
570 /////////////////////////////////////////////////////////////////////////
571 // Iterator constructors
572 /////////////////////////////////////////////////////////////////////////
574 /// Returns an iterator over the possibly contained value.
580 /// assert_eq!(x.iter().next(), Some(&4));
582 /// let x: Option<u32> = None;
583 /// assert_eq!(x.iter().next(), None);
586 #[stable(feature = "rust1", since = "1.0.0")]
587 pub fn iter(&self) -> Iter<'_, T> {
588 Iter { inner: Item { opt: self.as_ref() } }
591 /// Returns a mutable iterator over the possibly contained value.
596 /// let mut x = Some(4);
597 /// match x.iter_mut().next() {
598 /// Some(v) => *v = 42,
601 /// assert_eq!(x, Some(42));
603 /// let mut x: Option<u32> = None;
604 /// assert_eq!(x.iter_mut().next(), None);
607 #[stable(feature = "rust1", since = "1.0.0")]
608 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
609 IterMut { inner: Item { opt: self.as_mut() } }
612 /////////////////////////////////////////////////////////////////////////
613 // Boolean operations on the values, eager and lazy
614 /////////////////////////////////////////////////////////////////////////
616 /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
618 /// [`None`]: #variant.None
624 /// let y: Option<&str> = None;
625 /// assert_eq!(x.and(y), None);
627 /// let x: Option<u32> = None;
628 /// let y = Some("foo");
629 /// assert_eq!(x.and(y), None);
632 /// let y = Some("foo");
633 /// assert_eq!(x.and(y), Some("foo"));
635 /// let x: Option<u32> = None;
636 /// let y: Option<&str> = None;
637 /// assert_eq!(x.and(y), None);
640 #[stable(feature = "rust1", since = "1.0.0")]
641 pub fn and<U>(self, optb: Option<U>) -> Option<U> {
648 /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
649 /// wrapped value and returns the result.
651 /// Some languages call this operation flatmap.
653 /// [`None`]: #variant.None
658 /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
659 /// fn nope(_: u32) -> Option<u32> { None }
661 /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
662 /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
663 /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
664 /// assert_eq!(None.and_then(sq).and_then(sq), None);
667 #[stable(feature = "rust1", since = "1.0.0")]
668 pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> {
675 /// Returns [`None`] if the option is [`None`], otherwise calls `predicate`
676 /// with the wrapped value and returns:
678 /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped
680 /// - [`None`] if `predicate` returns `false`.
682 /// This function works similar to [`Iterator::filter()`]. You can imagine
683 /// the `Option<T>` being an iterator over one or zero elements. `filter()`
684 /// lets you decide which elements to keep.
689 /// fn is_even(n: &i32) -> bool {
693 /// assert_eq!(None.filter(is_even), None);
694 /// assert_eq!(Some(3).filter(is_even), None);
695 /// assert_eq!(Some(4).filter(is_even), Some(4));
698 /// [`None`]: #variant.None
699 /// [`Some(t)`]: #variant.Some
700 /// [`Iterator::filter()`]: ../../std/iter/trait.Iterator.html#method.filter
702 #[stable(feature = "option_filter", since = "1.27.0")]
703 pub fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Self {
704 if let Some(x) = self {
712 /// Returns the option if it contains a value, otherwise returns `optb`.
714 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
715 /// result of a function call, it is recommended to use [`or_else`], which is
716 /// lazily evaluated.
718 /// [`or_else`]: #method.or_else
725 /// assert_eq!(x.or(y), Some(2));
728 /// let y = Some(100);
729 /// assert_eq!(x.or(y), Some(100));
732 /// let y = Some(100);
733 /// assert_eq!(x.or(y), Some(2));
735 /// let x: Option<u32> = None;
737 /// assert_eq!(x.or(y), None);
740 #[stable(feature = "rust1", since = "1.0.0")]
741 pub fn or(self, optb: Option<T>) -> Option<T> {
748 /// Returns the option if it contains a value, otherwise calls `f` and
749 /// returns the result.
754 /// fn nobody() -> Option<&'static str> { None }
755 /// fn vikings() -> Option<&'static str> { Some("vikings") }
757 /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
758 /// assert_eq!(None.or_else(vikings), Some("vikings"));
759 /// assert_eq!(None.or_else(nobody), None);
762 #[stable(feature = "rust1", since = "1.0.0")]
763 pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> {
770 /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`].
772 /// [`Some`]: #variant.Some
773 /// [`None`]: #variant.None
779 /// let y: Option<u32> = None;
780 /// assert_eq!(x.xor(y), Some(2));
782 /// let x: Option<u32> = None;
784 /// assert_eq!(x.xor(y), Some(2));
788 /// assert_eq!(x.xor(y), None);
790 /// let x: Option<u32> = None;
791 /// let y: Option<u32> = None;
792 /// assert_eq!(x.xor(y), None);
795 #[stable(feature = "option_xor", since = "1.37.0")]
796 pub fn xor(self, optb: Option<T>) -> Option<T> {
798 (Some(a), None) => Some(a),
799 (None, Some(b)) => Some(b),
804 /////////////////////////////////////////////////////////////////////////
805 // Entry-like operations to insert if None and return a reference
806 /////////////////////////////////////////////////////////////////////////
808 /// Inserts `v` into the option if it is [`None`], then
809 /// returns a mutable reference to the contained value.
811 /// [`None`]: #variant.None
816 /// let mut x = None;
819 /// let y: &mut u32 = x.get_or_insert(5);
820 /// assert_eq!(y, &5);
825 /// assert_eq!(x, Some(7));
828 #[stable(feature = "option_entry", since = "1.20.0")]
829 pub fn get_or_insert(&mut self, v: T) -> &mut T {
830 self.get_or_insert_with(|| v)
833 /// Inserts a value computed from `f` into the option if it is [`None`], then
834 /// returns a mutable reference to the contained value.
836 /// [`None`]: #variant.None
841 /// let mut x = None;
844 /// let y: &mut u32 = x.get_or_insert_with(|| 5);
845 /// assert_eq!(y, &5);
850 /// assert_eq!(x, Some(7));
853 #[stable(feature = "option_entry", since = "1.20.0")]
854 pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
855 if let None = *self {
860 Some(ref mut v) => v,
861 None => unsafe { hint::unreachable_unchecked() },
865 /////////////////////////////////////////////////////////////////////////
867 /////////////////////////////////////////////////////////////////////////
869 /// Takes the value out of the option, leaving a [`None`] in its place.
871 /// [`None`]: #variant.None
876 /// let mut x = Some(2);
877 /// let y = x.take();
878 /// assert_eq!(x, None);
879 /// assert_eq!(y, Some(2));
881 /// let mut x: Option<u32> = None;
882 /// let y = x.take();
883 /// assert_eq!(x, None);
884 /// assert_eq!(y, None);
887 #[stable(feature = "rust1", since = "1.0.0")]
888 pub fn take(&mut self) -> Option<T> {
892 /// Replaces the actual value in the option by the value given in parameter,
893 /// returning the old value if present,
894 /// leaving a [`Some`] in its place without deinitializing either one.
896 /// [`Some`]: #variant.Some
901 /// let mut x = Some(2);
902 /// let old = x.replace(5);
903 /// assert_eq!(x, Some(5));
904 /// assert_eq!(old, Some(2));
906 /// let mut x = None;
907 /// let old = x.replace(3);
908 /// assert_eq!(x, Some(3));
909 /// assert_eq!(old, None);
912 #[stable(feature = "option_replace", since = "1.31.0")]
913 pub fn replace(&mut self, value: T) -> Option<T> {
914 mem::replace(self, Some(value))
918 impl<T: Copy> Option<&T> {
919 /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
926 /// let opt_x = Some(&x);
927 /// assert_eq!(opt_x, Some(&12));
928 /// let copied = opt_x.copied();
929 /// assert_eq!(copied, Some(12));
931 #[stable(feature = "copied", since = "1.35.0")]
932 pub fn copied(self) -> Option<T> {
937 impl<T: Copy> Option<&mut T> {
938 /// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the
945 /// let opt_x = Some(&mut x);
946 /// assert_eq!(opt_x, Some(&mut 12));
947 /// let copied = opt_x.copied();
948 /// assert_eq!(copied, Some(12));
950 #[stable(feature = "copied", since = "1.35.0")]
951 pub fn copied(self) -> Option<T> {
956 impl<T: Clone> Option<&T> {
957 /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
964 /// let opt_x = Some(&x);
965 /// assert_eq!(opt_x, Some(&12));
966 /// let cloned = opt_x.cloned();
967 /// assert_eq!(cloned, Some(12));
969 #[stable(feature = "rust1", since = "1.0.0")]
970 pub fn cloned(self) -> Option<T> {
971 self.map(|t| t.clone())
975 impl<T: Clone> Option<&mut T> {
976 /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
983 /// let opt_x = Some(&mut x);
984 /// assert_eq!(opt_x, Some(&mut 12));
985 /// let cloned = opt_x.cloned();
986 /// assert_eq!(cloned, Some(12));
988 #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
989 pub fn cloned(self) -> Option<T> {
990 self.map(|t| t.clone())
994 impl<T: fmt::Debug> Option<T> {
995 /// Consumes `self` while expecting [`None`] and returning nothing.
999 /// Panics if the value is a [`Some`], with a panic message including the
1000 /// passed message, and the content of the [`Some`].
1002 /// [`Some`]: #variant.Some
1003 /// [`None`]: #variant.None
1008 /// #![feature(option_expect_none)]
1010 /// use std::collections::HashMap;
1011 /// let mut squares = HashMap::new();
1012 /// for i in -10..=10 {
1013 /// // This will not panic, since all keys are unique.
1014 /// squares.insert(i, i * i).expect_none("duplicate key");
1018 /// ```{.should_panic}
1019 /// #![feature(option_expect_none)]
1021 /// use std::collections::HashMap;
1022 /// let mut sqrts = HashMap::new();
1023 /// for i in -10..=10 {
1024 /// // This will panic, since both negative and positive `i` will
1025 /// // insert the same `i * i` key, returning the old `Some(i)`.
1026 /// sqrts.insert(i * i, i).expect_none("duplicate key");
1031 #[unstable(feature = "option_expect_none", reason = "newly added", issue = "62633")]
1032 pub fn expect_none(self, msg: &str) {
1033 if let Some(val) = self {
1034 expect_none_failed(msg, &val);
1038 /// Consumes `self` while expecting [`None`] and returning nothing.
1042 /// Panics if the value is a [`Some`], with a custom panic message provided
1043 /// by the [`Some`]'s value.
1045 /// [`Some(v)`]: #variant.Some
1046 /// [`None`]: #variant.None
1051 /// #![feature(option_unwrap_none)]
1053 /// use std::collections::HashMap;
1054 /// let mut squares = HashMap::new();
1055 /// for i in -10..=10 {
1056 /// // This will not panic, since all keys are unique.
1057 /// squares.insert(i, i * i).unwrap_none();
1061 /// ```{.should_panic}
1062 /// #![feature(option_unwrap_none)]
1064 /// use std::collections::HashMap;
1065 /// let mut sqrts = HashMap::new();
1066 /// for i in -10..=10 {
1067 /// // This will panic, since both negative and positive `i` will
1068 /// // insert the same `i * i` key, returning the old `Some(i)`.
1069 /// sqrts.insert(i * i, i).unwrap_none();
1074 #[unstable(feature = "option_unwrap_none", reason = "newly added", issue = "62633")]
1075 pub fn unwrap_none(self) {
1076 if let Some(val) = self {
1077 expect_none_failed("called `Option::unwrap_none()` on a `Some` value", &val);
1082 impl<T: Default> Option<T> {
1083 /// Returns the contained [`Some`] value or a default
1085 /// Consumes the `self` argument then, if [`Some`], returns the contained
1086 /// value, otherwise if [`None`], returns the [default value] for that
1091 /// Converts a string to an integer, turning poorly-formed strings
1092 /// into 0 (the default value for integers). [`parse`] converts
1093 /// a string to any other type that implements [`FromStr`], returning
1094 /// [`None`] on error.
1097 /// let good_year_from_input = "1909";
1098 /// let bad_year_from_input = "190blarg";
1099 /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
1100 /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
1102 /// assert_eq!(1909, good_year);
1103 /// assert_eq!(0, bad_year);
1106 /// [`Some`]: #variant.Some
1107 /// [`None`]: #variant.None
1108 /// [default value]: ../default/trait.Default.html#tymethod.default
1109 /// [`parse`]: ../../std/primitive.str.html#method.parse
1110 /// [`FromStr`]: ../../std/str/trait.FromStr.html
1112 #[stable(feature = "rust1", since = "1.0.0")]
1113 pub fn unwrap_or_default(self) -> T {
1116 None => Default::default(),
1121 impl<T: Deref> Option<T> {
1122 /// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.
1124 /// Leaves the original Option in-place, creating a new one with a reference
1125 /// to the original one, additionally coercing the contents via [`Deref`].
1127 /// [`Deref`]: ../../std/ops/trait.Deref.html
1132 /// let x: Option<String> = Some("hey".to_owned());
1133 /// assert_eq!(x.as_deref(), Some("hey"));
1135 /// let x: Option<String> = None;
1136 /// assert_eq!(x.as_deref(), None);
1138 #[stable(feature = "option_deref", since = "1.40.0")]
1139 pub fn as_deref(&self) -> Option<&T::Target> {
1140 self.as_ref().map(|t| t.deref())
1144 impl<T: DerefMut> Option<T> {
1145 /// Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`.
1147 /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to
1148 /// the inner type's `Deref::Target` type.
1153 /// let mut x: Option<String> = Some("hey".to_owned());
1154 /// assert_eq!(x.as_deref_mut().map(|x| {
1155 /// x.make_ascii_uppercase();
1157 /// }), Some("HEY".to_owned().as_mut_str()));
1159 #[stable(feature = "option_deref", since = "1.40.0")]
1160 pub fn as_deref_mut(&mut self) -> Option<&mut T::Target> {
1161 self.as_mut().map(|t| t.deref_mut())
1165 impl<T, E> Option<Result<T, E>> {
1166 /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`.
1168 /// [`None`] will be mapped to [`Ok`]`(`[`None`]`)`.
1169 /// [`Some`]`(`[`Ok`]`(_))` and [`Some`]`(`[`Err`]`(_))` will be mapped to
1170 /// [`Ok`]`(`[`Some`]`(_))` and [`Err`]`(_)`.
1172 /// [`None`]: #variant.None
1173 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
1174 /// [`Some`]: #variant.Some
1175 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1180 /// #[derive(Debug, Eq, PartialEq)]
1183 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1184 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1185 /// assert_eq!(x, y.transpose());
1188 #[stable(feature = "transpose_result", since = "1.33.0")]
1189 pub fn transpose(self) -> Result<Option<T>, E> {
1191 Some(Ok(x)) => Ok(Some(x)),
1192 Some(Err(e)) => Err(e),
1198 // This is a separate function to reduce the code size of .expect() itself.
1202 fn expect_failed(msg: &str) -> ! {
1206 // This is a separate function to reduce the code size of .expect_none() itself.
1210 fn expect_none_failed(msg: &str, value: &dyn fmt::Debug) -> ! {
1211 panic!("{}: {:?}", msg, value)
1214 /////////////////////////////////////////////////////////////////////////////
1215 // Trait implementations
1216 /////////////////////////////////////////////////////////////////////////////
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 impl<T: Clone> Clone for Option<T> {
1221 fn clone(&self) -> Self {
1223 Some(x) => Some(x.clone()),
1229 fn clone_from(&mut self, source: &Self) {
1230 match (self, source) {
1231 (Some(to), Some(from)) => to.clone_from(from),
1232 (to, from) => *to = from.clone(),
1237 #[stable(feature = "rust1", since = "1.0.0")]
1238 impl<T> Default for Option<T> {
1239 /// Returns [`None`][Option::None].
1244 /// let opt: Option<u32> = Option::default();
1245 /// assert!(opt.is_none());
1248 fn default() -> Option<T> {
1253 #[stable(feature = "rust1", since = "1.0.0")]
1254 impl<T> IntoIterator for Option<T> {
1256 type IntoIter = IntoIter<T>;
1258 /// Returns a consuming iterator over the possibly contained value.
1263 /// let x = Some("string");
1264 /// let v: Vec<&str> = x.into_iter().collect();
1265 /// assert_eq!(v, ["string"]);
1268 /// let v: Vec<&str> = x.into_iter().collect();
1269 /// assert!(v.is_empty());
1272 fn into_iter(self) -> IntoIter<T> {
1273 IntoIter { inner: Item { opt: self } }
1277 #[stable(since = "1.4.0", feature = "option_iter")]
1278 impl<'a, T> IntoIterator for &'a Option<T> {
1280 type IntoIter = Iter<'a, T>;
1282 fn into_iter(self) -> Iter<'a, T> {
1287 #[stable(since = "1.4.0", feature = "option_iter")]
1288 impl<'a, T> IntoIterator for &'a mut Option<T> {
1289 type Item = &'a mut T;
1290 type IntoIter = IterMut<'a, T>;
1292 fn into_iter(self) -> IterMut<'a, T> {
1297 #[stable(since = "1.12.0", feature = "option_from")]
1298 impl<T> From<T> for Option<T> {
1299 fn from(val: T) -> Option<T> {
1304 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1305 impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
1306 fn from(o: &'a Option<T>) -> Option<&'a T> {
1311 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1312 impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> {
1313 fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
1318 /////////////////////////////////////////////////////////////////////////////
1319 // The Option Iterators
1320 /////////////////////////////////////////////////////////////////////////////
1322 #[derive(Clone, Debug)]
1327 impl<A> Iterator for Item<A> {
1331 fn next(&mut self) -> Option<A> {
1336 fn size_hint(&self) -> (usize, Option<usize>) {
1338 Some(_) => (1, Some(1)),
1339 None => (0, Some(0)),
1344 impl<A> DoubleEndedIterator for Item<A> {
1346 fn next_back(&mut self) -> Option<A> {
1351 impl<A> ExactSizeIterator for Item<A> {}
1352 impl<A> FusedIterator for Item<A> {}
1353 unsafe impl<A> TrustedLen for Item<A> {}
1355 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
1357 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1359 /// This `struct` is created by the [`Option::iter`] function.
1361 /// [`Option`]: enum.Option.html
1362 /// [`Some`]: enum.Option.html#variant.Some
1363 /// [`Option::iter`]: enum.Option.html#method.iter
1364 #[stable(feature = "rust1", since = "1.0.0")]
1366 pub struct Iter<'a, A: 'a> {
1370 #[stable(feature = "rust1", since = "1.0.0")]
1371 impl<'a, A> Iterator for Iter<'a, A> {
1375 fn next(&mut self) -> Option<&'a A> {
1379 fn size_hint(&self) -> (usize, Option<usize>) {
1380 self.inner.size_hint()
1384 #[stable(feature = "rust1", since = "1.0.0")]
1385 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
1387 fn next_back(&mut self) -> Option<&'a A> {
1388 self.inner.next_back()
1392 #[stable(feature = "rust1", since = "1.0.0")]
1393 impl<A> ExactSizeIterator for Iter<'_, A> {}
1395 #[stable(feature = "fused", since = "1.26.0")]
1396 impl<A> FusedIterator for Iter<'_, A> {}
1398 #[unstable(feature = "trusted_len", issue = "37572")]
1399 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 impl<A> Clone for Iter<'_, A> {
1404 fn clone(&self) -> Self {
1405 Iter { inner: self.inner.clone() }
1409 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
1411 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1413 /// This `struct` is created by the [`Option::iter_mut`] function.
1415 /// [`Option`]: enum.Option.html
1416 /// [`Some`]: enum.Option.html#variant.Some
1417 /// [`Option::iter_mut`]: enum.Option.html#method.iter_mut
1418 #[stable(feature = "rust1", since = "1.0.0")]
1420 pub struct IterMut<'a, A: 'a> {
1421 inner: Item<&'a mut A>,
1424 #[stable(feature = "rust1", since = "1.0.0")]
1425 impl<'a, A> Iterator for IterMut<'a, A> {
1426 type Item = &'a mut A;
1429 fn next(&mut self) -> Option<&'a mut A> {
1433 fn size_hint(&self) -> (usize, Option<usize>) {
1434 self.inner.size_hint()
1438 #[stable(feature = "rust1", since = "1.0.0")]
1439 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
1441 fn next_back(&mut self) -> Option<&'a mut A> {
1442 self.inner.next_back()
1446 #[stable(feature = "rust1", since = "1.0.0")]
1447 impl<A> ExactSizeIterator for IterMut<'_, A> {}
1449 #[stable(feature = "fused", since = "1.26.0")]
1450 impl<A> FusedIterator for IterMut<'_, A> {}
1451 #[unstable(feature = "trusted_len", issue = "37572")]
1452 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1454 /// An iterator over the value in [`Some`] variant of an [`Option`].
1456 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1458 /// This `struct` is created by the [`Option::into_iter`] function.
1460 /// [`Option`]: enum.Option.html
1461 /// [`Some`]: enum.Option.html#variant.Some
1462 /// [`Option::into_iter`]: enum.Option.html#method.into_iter
1463 #[derive(Clone, Debug)]
1464 #[stable(feature = "rust1", since = "1.0.0")]
1465 pub struct IntoIter<A> {
1469 #[stable(feature = "rust1", since = "1.0.0")]
1470 impl<A> Iterator for IntoIter<A> {
1474 fn next(&mut self) -> Option<A> {
1478 fn size_hint(&self) -> (usize, Option<usize>) {
1479 self.inner.size_hint()
1483 #[stable(feature = "rust1", since = "1.0.0")]
1484 impl<A> DoubleEndedIterator for IntoIter<A> {
1486 fn next_back(&mut self) -> Option<A> {
1487 self.inner.next_back()
1491 #[stable(feature = "rust1", since = "1.0.0")]
1492 impl<A> ExactSizeIterator for IntoIter<A> {}
1494 #[stable(feature = "fused", since = "1.26.0")]
1495 impl<A> FusedIterator for IntoIter<A> {}
1497 #[unstable(feature = "trusted_len", issue = "37572")]
1498 unsafe impl<A> TrustedLen for IntoIter<A> {}
1500 /////////////////////////////////////////////////////////////////////////////
1502 /////////////////////////////////////////////////////////////////////////////
1504 #[stable(feature = "rust1", since = "1.0.0")]
1505 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
1506 /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
1507 /// no further elements are taken, and the [`None`][Option::None] is
1508 /// returned. Should no [`None`][Option::None] occur, a container with the
1509 /// values of each [`Option`] is returned.
1513 /// Here is an example which increments every integer in a vector.
1514 /// We use the checked variant of `add` that returns `None` when the
1515 /// calculation would result in an overflow.
1518 /// let items = vec![0_u16, 1, 2];
1520 /// let res: Option<Vec<u16>> = items
1522 /// .map(|x| x.checked_add(1))
1525 /// assert_eq!(res, Some(vec![1, 2, 3]));
1528 /// As you can see, this will return the expected, valid items.
1530 /// Here is another example that tries to subtract one from another list
1531 /// of integers, this time checking for underflow:
1534 /// let items = vec![2_u16, 1, 0];
1536 /// let res: Option<Vec<u16>> = items
1538 /// .map(|x| x.checked_sub(1))
1541 /// assert_eq!(res, None);
1544 /// Since the last element is zero, it would underflow. Thus, the resulting
1545 /// value is `None`.
1547 /// Here is a variation on the previous example, showing that no
1548 /// further elements are taken from `iter` after the first `None`.
1551 /// let items = vec![3_u16, 2, 1, 10];
1553 /// let mut shared = 0;
1555 /// let res: Option<Vec<u16>> = items
1557 /// .map(|x| { shared += x; x.checked_sub(2) })
1560 /// assert_eq!(res, None);
1561 /// assert_eq!(shared, 6);
1564 /// Since the third element caused an underflow, no further elements were taken,
1565 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1567 /// [`Iterator`]: ../iter/trait.Iterator.html
1569 fn from_iter<I: IntoIterator<Item = Option<A>>>(iter: I) -> Option<V> {
1570 // FIXME(#11084): This could be replaced with Iterator::scan when this
1571 // performance bug is closed.
1573 iter.into_iter().map(|x| x.ok_or(())).collect::<Result<_, _>>().ok()
1577 /// The error type that results from applying the try operator (`?`) to a `None` value. If you wish
1578 /// to allow `x?` (where `x` is an `Option<T>`) to be converted into your error type, you can
1579 /// implement `impl From<NoneError>` for `YourErrorType`. In that case, `x?` within a function that
1580 /// returns `Result<_, YourErrorType>` will translate a `None` value into an `Err` result.
1581 #[unstable(feature = "try_trait", issue = "42327")]
1582 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
1583 pub struct NoneError;
1585 #[unstable(feature = "try_trait", issue = "42327")]
1586 impl<T> ops::Try for Option<T> {
1588 type Error = NoneError;
1591 fn into_result(self) -> Result<T, NoneError> {
1592 self.ok_or(NoneError)
1596 fn from_ok(v: T) -> Self {
1601 fn from_error(_: NoneError) -> Self {
1606 impl<T> Option<Option<T>> {
1607 /// Converts from `Option<Option<T>>` to `Option<T>`
1612 /// let x: Option<Option<u32>> = Some(Some(6));
1613 /// assert_eq!(Some(6), x.flatten());
1615 /// let x: Option<Option<u32>> = Some(None);
1616 /// assert_eq!(None, x.flatten());
1618 /// let x: Option<Option<u32>> = None;
1619 /// assert_eq!(None, x.flatten());
1621 /// Flattening once only removes one level of nesting:
1623 /// let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
1624 /// assert_eq!(Some(Some(6)), x.flatten());
1625 /// assert_eq!(Some(6), x.flatten().flatten());
1628 #[stable(feature = "option_flattening", since = "1.40.0")]
1629 pub fn flatten(self) -> Option<T> {
1630 self.and_then(convert::identity)