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};
139 use crate::{convert, fmt, hint, mem, ops::{self, Deref, DerefMut}};
142 // Note that this is not a lang item per se, but it has a hidden dependency on
143 // `Iterator`, which is one. The compiler assumes that the `next` method of
144 // `Iterator` is an enumeration with one type parameter and two variants,
145 // which basically means it must be `Option`.
147 /// The `Option` type. See [the module level documentation](index.html) for more.
148 #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
149 #[stable(feature = "rust1", since = "1.0.0")]
152 #[stable(feature = "rust1", since = "1.0.0")]
155 #[stable(feature = "rust1", since = "1.0.0")]
156 Some(#[stable(feature = "rust1", since = "1.0.0")] T),
159 /////////////////////////////////////////////////////////////////////////////
160 // Type implementation
161 /////////////////////////////////////////////////////////////////////////////
164 /////////////////////////////////////////////////////////////////////////
165 // Querying the contained values
166 /////////////////////////////////////////////////////////////////////////
168 /// Returns `true` if the option is a [`Some`] value.
173 /// let x: Option<u32> = Some(2);
174 /// assert_eq!(x.is_some(), true);
176 /// let x: Option<u32> = None;
177 /// assert_eq!(x.is_some(), false);
180 /// [`Some`]: #variant.Some
181 #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"]
183 #[stable(feature = "rust1", since = "1.0.0")]
184 pub fn is_some(&self) -> bool {
191 /// Returns `true` if the option is a [`None`] value.
196 /// let x: Option<u32> = Some(2);
197 /// assert_eq!(x.is_none(), false);
199 /// let x: Option<u32> = None;
200 /// assert_eq!(x.is_none(), true);
203 /// [`None`]: #variant.None
204 #[must_use = "if you intended to assert that this doesn't have a value, consider \
205 `.and_then(|| panic!(\"`Option` had a value when expected `None`\"))` instead"]
207 #[stable(feature = "rust1", since = "1.0.0")]
208 pub fn is_none(&self) -> bool {
212 /// Returns `true` if the option is a [`Some`] value containing the given value.
217 /// #![feature(option_result_contains)]
219 /// let x: Option<u32> = Some(2);
220 /// assert_eq!(x.contains(&2), true);
222 /// let x: Option<u32> = Some(3);
223 /// assert_eq!(x.contains(&2), false);
225 /// let x: Option<u32> = None;
226 /// assert_eq!(x.contains(&2), false);
230 #[unstable(feature = "option_result_contains", issue = "62358")]
231 pub fn contains<U>(&self, x: &U) -> bool where U: PartialEq<T> {
238 /////////////////////////////////////////////////////////////////////////
239 // Adapter for working with references
240 /////////////////////////////////////////////////////////////////////////
242 /// Converts from `&Option<T>` to `Option<&T>`.
246 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
247 /// The [`map`] method takes the `self` argument by value, consuming the original,
248 /// so this technique uses `as_ref` to first take an `Option` to a reference
249 /// to the value inside the original.
251 /// [`map`]: enum.Option.html#method.map
252 /// [`String`]: ../../std/string/struct.String.html
253 /// [`usize`]: ../../std/primitive.usize.html
256 /// let text: Option<String> = Some("Hello, world!".to_string());
257 /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
258 /// // then consume *that* with `map`, leaving `text` on the stack.
259 /// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
260 /// println!("still can print text: {:?}", text);
263 #[stable(feature = "rust1", since = "1.0.0")]
264 pub fn as_ref(&self) -> Option<&T> {
266 Some(ref x) => Some(x),
271 /// Converts from `&mut Option<T>` to `Option<&mut T>`.
276 /// let mut x = Some(2);
277 /// match x.as_mut() {
278 /// Some(v) => *v = 42,
281 /// assert_eq!(x, Some(42));
284 #[stable(feature = "rust1", since = "1.0.0")]
285 pub fn as_mut(&mut self) -> Option<&mut T> {
287 Some(ref mut x) => Some(x),
293 /// Converts from [`Pin`]`<&Option<T>>` to `Option<`[`Pin`]`<&T>>`.
295 /// [`Pin`]: ../pin/struct.Pin.html
297 #[stable(feature = "pin", since = "1.33.0")]
298 pub fn as_pin_ref(self: Pin<&Self>) -> Option<Pin<&T>> {
300 Pin::get_ref(self).as_ref().map(|x| Pin::new_unchecked(x))
304 /// Converts from [`Pin`]`<&mut Option<T>>` to `Option<`[`Pin`]`<&mut T>>`.
306 /// [`Pin`]: ../pin/struct.Pin.html
308 #[stable(feature = "pin", since = "1.33.0")]
309 pub fn as_pin_mut(self: Pin<&mut Self>) -> Option<Pin<&mut T>> {
311 Pin::get_unchecked_mut(self).as_mut().map(|x| Pin::new_unchecked(x))
315 /////////////////////////////////////////////////////////////////////////
316 // Getting to contained values
317 /////////////////////////////////////////////////////////////////////////
319 /// Unwraps an option, yielding the content of a [`Some`].
323 /// Panics if the value is a [`None`] with a custom panic message provided by
326 /// [`Some`]: #variant.Some
327 /// [`None`]: #variant.None
332 /// let x = Some("value");
333 /// assert_eq!(x.expect("the world is ending"), "value");
336 /// ```{.should_panic}
337 /// let x: Option<&str> = None;
338 /// x.expect("the world is ending"); // panics with `the world is ending`
341 #[stable(feature = "rust1", since = "1.0.0")]
342 pub fn expect(self, msg: &str) -> T {
345 None => expect_failed(msg),
349 /// Moves the value `v` out of the `Option<T>` if it is [`Some(v)`].
351 /// In general, because this function may panic, its use is discouraged.
352 /// Instead, prefer to use pattern matching and handle the [`None`]
357 /// Panics if the self value equals [`None`].
359 /// [`Some(v)`]: #variant.Some
360 /// [`None`]: #variant.None
365 /// let x = Some("air");
366 /// assert_eq!(x.unwrap(), "air");
369 /// ```{.should_panic}
370 /// let x: Option<&str> = None;
371 /// assert_eq!(x.unwrap(), "air"); // fails
374 #[stable(feature = "rust1", since = "1.0.0")]
375 pub fn unwrap(self) -> T {
378 None => panic!("called `Option::unwrap()` on a `None` value"),
382 /// Returns the contained value or a default.
384 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
385 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
386 /// which is lazily evaluated.
388 /// [`unwrap_or_else`]: #method.unwrap_or_else
393 /// assert_eq!(Some("car").unwrap_or("bike"), "car");
394 /// assert_eq!(None.unwrap_or("bike"), "bike");
397 #[stable(feature = "rust1", since = "1.0.0")]
398 pub fn unwrap_or(self, default: T) -> T {
405 /// Returns the contained value or computes it from a closure.
411 /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
412 /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
415 #[stable(feature = "rust1", since = "1.0.0")]
416 pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
423 /////////////////////////////////////////////////////////////////////////
424 // Transforming contained values
425 /////////////////////////////////////////////////////////////////////////
427 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
431 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, consuming the original:
433 /// [`String`]: ../../std/string/struct.String.html
434 /// [`usize`]: ../../std/primitive.usize.html
437 /// let maybe_some_string = Some(String::from("Hello, World!"));
438 /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
439 /// let maybe_some_len = maybe_some_string.map(|s| s.len());
441 /// assert_eq!(maybe_some_len, Some(13));
444 #[stable(feature = "rust1", since = "1.0.0")]
445 pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
447 Some(x) => Some(f(x)),
452 /// Applies a function to the contained value (if any),
453 /// or returns the provided default (if not).
458 /// let x = Some("foo");
459 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
461 /// let x: Option<&str> = None;
462 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
465 #[stable(feature = "rust1", since = "1.0.0")]
466 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
473 /// Applies a function to the contained value (if any),
474 /// or computes a default (if not).
481 /// let x = Some("foo");
482 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
484 /// let x: Option<&str> = None;
485 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
488 #[stable(feature = "rust1", since = "1.0.0")]
489 pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
496 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
497 /// [`Ok(v)`] and [`None`] to [`Err(err)`].
499 /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
500 /// result of a function call, it is recommended to use [`ok_or_else`], which is
501 /// lazily evaluated.
503 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
504 /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
505 /// [`Err(err)`]: ../../std/result/enum.Result.html#variant.Err
506 /// [`None`]: #variant.None
507 /// [`Some(v)`]: #variant.Some
508 /// [`ok_or_else`]: #method.ok_or_else
513 /// let x = Some("foo");
514 /// assert_eq!(x.ok_or(0), Ok("foo"));
516 /// let x: Option<&str> = None;
517 /// assert_eq!(x.ok_or(0), Err(0));
520 #[stable(feature = "rust1", since = "1.0.0")]
521 pub fn ok_or<E>(self, err: E) -> Result<T, E> {
528 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
529 /// [`Ok(v)`] and [`None`] to [`Err(err())`].
531 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
532 /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
533 /// [`Err(err())`]: ../../std/result/enum.Result.html#variant.Err
534 /// [`None`]: #variant.None
535 /// [`Some(v)`]: #variant.Some
540 /// let x = Some("foo");
541 /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
543 /// let x: Option<&str> = None;
544 /// assert_eq!(x.ok_or_else(|| 0), Err(0));
547 #[stable(feature = "rust1", since = "1.0.0")]
548 pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
555 /////////////////////////////////////////////////////////////////////////
556 // Iterator constructors
557 /////////////////////////////////////////////////////////////////////////
559 /// Returns an iterator over the possibly contained value.
565 /// assert_eq!(x.iter().next(), Some(&4));
567 /// let x: Option<u32> = None;
568 /// assert_eq!(x.iter().next(), None);
571 #[stable(feature = "rust1", since = "1.0.0")]
572 pub fn iter(&self) -> Iter<'_, T> {
573 Iter { inner: Item { opt: self.as_ref() } }
576 /// Returns a mutable iterator over the possibly contained value.
581 /// let mut x = Some(4);
582 /// match x.iter_mut().next() {
583 /// Some(v) => *v = 42,
586 /// assert_eq!(x, Some(42));
588 /// let mut x: Option<u32> = None;
589 /// assert_eq!(x.iter_mut().next(), None);
592 #[stable(feature = "rust1", since = "1.0.0")]
593 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
594 IterMut { inner: Item { opt: self.as_mut() } }
597 /////////////////////////////////////////////////////////////////////////
598 // Boolean operations on the values, eager and lazy
599 /////////////////////////////////////////////////////////////////////////
601 /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
603 /// [`None`]: #variant.None
609 /// let y: Option<&str> = None;
610 /// assert_eq!(x.and(y), None);
612 /// let x: Option<u32> = None;
613 /// let y = Some("foo");
614 /// assert_eq!(x.and(y), None);
617 /// let y = Some("foo");
618 /// assert_eq!(x.and(y), Some("foo"));
620 /// let x: Option<u32> = None;
621 /// let y: Option<&str> = None;
622 /// assert_eq!(x.and(y), None);
625 #[stable(feature = "rust1", since = "1.0.0")]
626 pub fn and<U>(self, optb: Option<U>) -> Option<U> {
633 /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
634 /// wrapped value and returns the result.
636 /// Some languages call this operation flatmap.
638 /// [`None`]: #variant.None
643 /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
644 /// fn nope(_: u32) -> Option<u32> { None }
646 /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
647 /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
648 /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
649 /// assert_eq!(None.and_then(sq).and_then(sq), None);
652 #[stable(feature = "rust1", since = "1.0.0")]
653 pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> {
660 /// Returns [`None`] if the option is [`None`], otherwise calls `predicate`
661 /// with the wrapped value and returns:
663 /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped
665 /// - [`None`] if `predicate` returns `false`.
667 /// This function works similar to [`Iterator::filter()`]. You can imagine
668 /// the `Option<T>` being an iterator over one or zero elements. `filter()`
669 /// lets you decide which elements to keep.
674 /// fn is_even(n: &i32) -> bool {
678 /// assert_eq!(None.filter(is_even), None);
679 /// assert_eq!(Some(3).filter(is_even), None);
680 /// assert_eq!(Some(4).filter(is_even), Some(4));
683 /// [`None`]: #variant.None
684 /// [`Some(t)`]: #variant.Some
685 /// [`Iterator::filter()`]: ../../std/iter/trait.Iterator.html#method.filter
687 #[stable(feature = "option_filter", since = "1.27.0")]
688 pub fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Self {
689 if let Some(x) = self {
697 /// Returns the option if it contains a value, otherwise returns `optb`.
699 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
700 /// result of a function call, it is recommended to use [`or_else`], which is
701 /// lazily evaluated.
703 /// [`or_else`]: #method.or_else
710 /// assert_eq!(x.or(y), Some(2));
713 /// let y = Some(100);
714 /// assert_eq!(x.or(y), Some(100));
717 /// let y = Some(100);
718 /// assert_eq!(x.or(y), Some(2));
720 /// let x: Option<u32> = None;
722 /// assert_eq!(x.or(y), None);
725 #[stable(feature = "rust1", since = "1.0.0")]
726 pub fn or(self, optb: Option<T>) -> Option<T> {
733 /// Returns the option if it contains a value, otherwise calls `f` and
734 /// returns the result.
739 /// fn nobody() -> Option<&'static str> { None }
740 /// fn vikings() -> Option<&'static str> { Some("vikings") }
742 /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
743 /// assert_eq!(None.or_else(vikings), Some("vikings"));
744 /// assert_eq!(None.or_else(nobody), None);
747 #[stable(feature = "rust1", since = "1.0.0")]
748 pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> {
755 /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`].
757 /// [`Some`]: #variant.Some
758 /// [`None`]: #variant.None
764 /// let y: Option<u32> = None;
765 /// assert_eq!(x.xor(y), Some(2));
767 /// let x: Option<u32> = None;
769 /// assert_eq!(x.xor(y), Some(2));
773 /// assert_eq!(x.xor(y), None);
775 /// let x: Option<u32> = None;
776 /// let y: Option<u32> = None;
777 /// assert_eq!(x.xor(y), None);
780 #[stable(feature = "option_xor", since = "1.37.0")]
781 pub fn xor(self, optb: Option<T>) -> Option<T> {
783 (Some(a), None) => Some(a),
784 (None, Some(b)) => Some(b),
789 /////////////////////////////////////////////////////////////////////////
790 // Entry-like operations to insert if None and return a reference
791 /////////////////////////////////////////////////////////////////////////
793 /// Inserts `v` into the option if it is [`None`], then
794 /// returns a mutable reference to the contained value.
796 /// [`None`]: #variant.None
801 /// let mut x = None;
804 /// let y: &mut u32 = x.get_or_insert(5);
805 /// assert_eq!(y, &5);
810 /// assert_eq!(x, Some(7));
813 #[stable(feature = "option_entry", since = "1.20.0")]
814 pub fn get_or_insert(&mut self, v: T) -> &mut T {
815 self.get_or_insert_with(|| v)
818 /// Inserts a value computed from `f` into the option if it is [`None`], then
819 /// returns a mutable reference to the contained value.
821 /// [`None`]: #variant.None
826 /// let mut x = None;
829 /// let y: &mut u32 = x.get_or_insert_with(|| 5);
830 /// assert_eq!(y, &5);
835 /// assert_eq!(x, Some(7));
838 #[stable(feature = "option_entry", since = "1.20.0")]
839 pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
840 if let None = *self {
845 Some(ref mut v) => v,
846 None => unsafe { hint::unreachable_unchecked() },
850 /////////////////////////////////////////////////////////////////////////
852 /////////////////////////////////////////////////////////////////////////
854 /// Takes the value out of the option, leaving a [`None`] in its place.
856 /// [`None`]: #variant.None
861 /// let mut x = Some(2);
862 /// let y = x.take();
863 /// assert_eq!(x, None);
864 /// assert_eq!(y, Some(2));
866 /// let mut x: Option<u32> = None;
867 /// let y = x.take();
868 /// assert_eq!(x, None);
869 /// assert_eq!(y, None);
872 #[stable(feature = "rust1", since = "1.0.0")]
873 pub fn take(&mut self) -> Option<T> {
877 /// Replaces the actual value in the option by the value given in parameter,
878 /// returning the old value if present,
879 /// leaving a [`Some`] in its place without deinitializing either one.
881 /// [`Some`]: #variant.Some
886 /// let mut x = Some(2);
887 /// let old = x.replace(5);
888 /// assert_eq!(x, Some(5));
889 /// assert_eq!(old, Some(2));
891 /// let mut x = None;
892 /// let old = x.replace(3);
893 /// assert_eq!(x, Some(3));
894 /// assert_eq!(old, None);
897 #[stable(feature = "option_replace", since = "1.31.0")]
898 pub fn replace(&mut self, value: T) -> Option<T> {
899 mem::replace(self, Some(value))
903 impl<T: Copy> Option<&T> {
904 /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
911 /// let opt_x = Some(&x);
912 /// assert_eq!(opt_x, Some(&12));
913 /// let copied = opt_x.copied();
914 /// assert_eq!(copied, Some(12));
916 #[stable(feature = "copied", since = "1.35.0")]
917 pub fn copied(self) -> Option<T> {
922 impl<T: Copy> Option<&mut T> {
923 /// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the
930 /// let opt_x = Some(&mut x);
931 /// assert_eq!(opt_x, Some(&mut 12));
932 /// let copied = opt_x.copied();
933 /// assert_eq!(copied, Some(12));
935 #[stable(feature = "copied", since = "1.35.0")]
936 pub fn copied(self) -> Option<T> {
941 impl<T: Clone> Option<&T> {
942 /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
949 /// let opt_x = Some(&x);
950 /// assert_eq!(opt_x, Some(&12));
951 /// let cloned = opt_x.cloned();
952 /// assert_eq!(cloned, Some(12));
954 #[stable(feature = "rust1", since = "1.0.0")]
955 pub fn cloned(self) -> Option<T> {
956 self.map(|t| t.clone())
960 impl<T: Clone> Option<&mut T> {
961 /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
968 /// let opt_x = Some(&mut x);
969 /// assert_eq!(opt_x, Some(&mut 12));
970 /// let cloned = opt_x.cloned();
971 /// assert_eq!(cloned, Some(12));
973 #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
974 pub fn cloned(self) -> Option<T> {
975 self.map(|t| t.clone())
979 impl<T: fmt::Debug> Option<T> {
980 /// Unwraps an option, expecting [`None`] and returning nothing.
984 /// Panics if the value is a [`Some`], with a panic message including the
985 /// passed message, and the content of the [`Some`].
987 /// [`Some`]: #variant.Some
988 /// [`None`]: #variant.None
993 /// #![feature(option_expect_none)]
995 /// use std::collections::HashMap;
996 /// let mut squares = HashMap::new();
997 /// for i in -10..=10 {
998 /// // This will not panic, since all keys are unique.
999 /// squares.insert(i, i * i).expect_none("duplicate key");
1003 /// ```{.should_panic}
1004 /// #![feature(option_expect_none)]
1006 /// use std::collections::HashMap;
1007 /// let mut sqrts = HashMap::new();
1008 /// for i in -10..=10 {
1009 /// // This will panic, since both negative and positive `i` will
1010 /// // insert the same `i * i` key, returning the old `Some(i)`.
1011 /// sqrts.insert(i * i, i).expect_none("duplicate key");
1015 #[unstable(feature = "option_expect_none", reason = "newly added", issue = "62633")]
1016 pub fn expect_none(self, msg: &str) {
1017 if let Some(val) = self {
1018 expect_none_failed(msg, &val);
1022 /// Unwraps an option, expecting [`None`] and returning nothing.
1026 /// Panics if the value is a [`Some`], with a custom panic message provided
1027 /// by the [`Some`]'s value.
1029 /// [`Some(v)`]: #variant.Some
1030 /// [`None`]: #variant.None
1035 /// #![feature(option_unwrap_none)]
1037 /// use std::collections::HashMap;
1038 /// let mut squares = HashMap::new();
1039 /// for i in -10..=10 {
1040 /// // This will not panic, since all keys are unique.
1041 /// squares.insert(i, i * i).unwrap_none();
1045 /// ```{.should_panic}
1046 /// #![feature(option_unwrap_none)]
1048 /// use std::collections::HashMap;
1049 /// let mut sqrts = HashMap::new();
1050 /// for i in -10..=10 {
1051 /// // This will panic, since both negative and positive `i` will
1052 /// // insert the same `i * i` key, returning the old `Some(i)`.
1053 /// sqrts.insert(i * i, i).unwrap_none();
1057 #[unstable(feature = "option_unwrap_none", reason = "newly added", issue = "62633")]
1058 pub fn unwrap_none(self) {
1059 if let Some(val) = self {
1060 expect_none_failed("called `Option::unwrap_none()` on a `Some` value", &val);
1065 impl<T: Default> Option<T> {
1066 /// Returns the contained value or a default
1068 /// Consumes the `self` argument then, if [`Some`], returns the contained
1069 /// value, otherwise if [`None`], returns the [default value] for that
1074 /// Converts a string to an integer, turning poorly-formed strings
1075 /// into 0 (the default value for integers). [`parse`] converts
1076 /// a string to any other type that implements [`FromStr`], returning
1077 /// [`None`] on error.
1080 /// let good_year_from_input = "1909";
1081 /// let bad_year_from_input = "190blarg";
1082 /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
1083 /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
1085 /// assert_eq!(1909, good_year);
1086 /// assert_eq!(0, bad_year);
1089 /// [`Some`]: #variant.Some
1090 /// [`None`]: #variant.None
1091 /// [default value]: ../default/trait.Default.html#tymethod.default
1092 /// [`parse`]: ../../std/primitive.str.html#method.parse
1093 /// [`FromStr`]: ../../std/str/trait.FromStr.html
1095 #[stable(feature = "rust1", since = "1.0.0")]
1096 pub fn unwrap_or_default(self) -> T {
1099 None => Default::default(),
1104 impl<T: Deref> Option<T> {
1105 /// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.
1107 /// Leaves the original Option in-place, creating a new one with a reference
1108 /// to the original one, additionally coercing the contents via [`Deref`].
1110 /// [`Deref`]: ../../std/ops/trait.Deref.html
1115 /// let x: Option<String> = Some("hey".to_owned());
1116 /// assert_eq!(x.as_deref(), Some("hey"));
1118 /// let x: Option<String> = None;
1119 /// assert_eq!(x.as_deref(), None);
1121 #[stable(feature = "option_deref", since = "1.40.0")]
1122 pub fn as_deref(&self) -> Option<&T::Target> {
1123 self.as_ref().map(|t| t.deref())
1127 impl<T: DerefMut> Option<T> {
1128 /// Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`.
1130 /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to
1131 /// the inner type's `Deref::Target` type.
1136 /// let mut x: Option<String> = Some("hey".to_owned());
1137 /// assert_eq!(x.as_deref_mut().map(|x| {
1138 /// x.make_ascii_uppercase();
1140 /// }), Some("HEY".to_owned().as_mut_str()));
1142 #[stable(feature = "option_deref", since = "1.40.0")]
1143 pub fn as_deref_mut(&mut self) -> Option<&mut T::Target> {
1144 self.as_mut().map(|t| t.deref_mut())
1148 impl<T, E> Option<Result<T, E>> {
1149 /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`.
1151 /// [`None`] will be mapped to [`Ok`]`(`[`None`]`)`.
1152 /// [`Some`]`(`[`Ok`]`(_))` and [`Some`]`(`[`Err`]`(_))` will be mapped to
1153 /// [`Ok`]`(`[`Some`]`(_))` and [`Err`]`(_)`.
1155 /// [`None`]: #variant.None
1156 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
1157 /// [`Some`]: #variant.Some
1158 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
1163 /// #[derive(Debug, Eq, PartialEq)]
1166 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1167 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1168 /// assert_eq!(x, y.transpose());
1171 #[stable(feature = "transpose_result", since = "1.33.0")]
1172 pub fn transpose(self) -> Result<Option<T>, E> {
1174 Some(Ok(x)) => Ok(Some(x)),
1175 Some(Err(e)) => Err(e),
1181 // This is a separate function to reduce the code size of .expect() itself.
1184 fn expect_failed(msg: &str) -> ! {
1188 // This is a separate function to reduce the code size of .expect_none() itself.
1191 fn expect_none_failed(msg: &str, value: &dyn fmt::Debug) -> ! {
1192 panic!("{}: {:?}", msg, value)
1195 /////////////////////////////////////////////////////////////////////////////
1196 // Trait implementations
1197 /////////////////////////////////////////////////////////////////////////////
1199 #[stable(feature = "rust1", since = "1.0.0")]
1200 impl<T: Clone> Clone for Option<T> {
1202 fn clone(&self) -> Self {
1204 Some(x) => Some(x.clone()),
1210 fn clone_from(&mut self, source: &Self) {
1211 match (self, source) {
1212 (Some(to), Some(from)) => to.clone_from(from),
1213 (to, from) => *to = from.clone(),
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 impl<T> Default for Option<T> {
1220 /// Returns [`None`][Option::None].
1225 /// let opt: Option<u32> = Option::default();
1226 /// assert!(opt.is_none());
1229 fn default() -> Option<T> { None }
1232 #[stable(feature = "rust1", since = "1.0.0")]
1233 impl<T> IntoIterator for Option<T> {
1235 type IntoIter = IntoIter<T>;
1237 /// Returns a consuming iterator over the possibly contained value.
1242 /// let x = Some("string");
1243 /// let v: Vec<&str> = x.into_iter().collect();
1244 /// assert_eq!(v, ["string"]);
1247 /// let v: Vec<&str> = x.into_iter().collect();
1248 /// assert!(v.is_empty());
1251 fn into_iter(self) -> IntoIter<T> {
1252 IntoIter { inner: Item { opt: self } }
1256 #[stable(since = "1.4.0", feature = "option_iter")]
1257 impl<'a, T> IntoIterator for &'a Option<T> {
1259 type IntoIter = Iter<'a, T>;
1261 fn into_iter(self) -> Iter<'a, T> {
1266 #[stable(since = "1.4.0", feature = "option_iter")]
1267 impl<'a, T> IntoIterator for &'a mut Option<T> {
1268 type Item = &'a mut T;
1269 type IntoIter = IterMut<'a, T>;
1271 fn into_iter(self) -> IterMut<'a, T> {
1276 #[stable(since = "1.12.0", feature = "option_from")]
1277 impl<T> From<T> for Option<T> {
1278 fn from(val: T) -> Option<T> {
1283 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1284 impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
1285 fn from(o: &'a Option<T>) -> Option<&'a T> {
1290 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1291 impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> {
1292 fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
1297 /////////////////////////////////////////////////////////////////////////////
1298 // The Option Iterators
1299 /////////////////////////////////////////////////////////////////////////////
1301 #[derive(Clone, Debug)]
1306 impl<A> Iterator for Item<A> {
1310 fn next(&mut self) -> Option<A> {
1315 fn size_hint(&self) -> (usize, Option<usize>) {
1317 Some(_) => (1, Some(1)),
1318 None => (0, Some(0)),
1323 impl<A> DoubleEndedIterator for Item<A> {
1325 fn next_back(&mut self) -> Option<A> {
1330 impl<A> ExactSizeIterator for Item<A> {}
1331 impl<A> FusedIterator for Item<A> {}
1332 unsafe impl<A> TrustedLen for Item<A> {}
1334 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
1336 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1338 /// This `struct` is created by the [`Option::iter`] function.
1340 /// [`Option`]: enum.Option.html
1341 /// [`Some`]: enum.Option.html#variant.Some
1342 /// [`Option::iter`]: enum.Option.html#method.iter
1343 #[stable(feature = "rust1", since = "1.0.0")]
1345 pub struct Iter<'a, A: 'a> { inner: Item<&'a A> }
1347 #[stable(feature = "rust1", since = "1.0.0")]
1348 impl<'a, A> Iterator for Iter<'a, A> {
1352 fn next(&mut self) -> Option<&'a A> { self.inner.next() }
1354 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1357 #[stable(feature = "rust1", since = "1.0.0")]
1358 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
1360 fn next_back(&mut self) -> Option<&'a A> { self.inner.next_back() }
1363 #[stable(feature = "rust1", since = "1.0.0")]
1364 impl<A> ExactSizeIterator for Iter<'_, A> {}
1366 #[stable(feature = "fused", since = "1.26.0")]
1367 impl<A> FusedIterator for Iter<'_, A> {}
1369 #[unstable(feature = "trusted_len", issue = "37572")]
1370 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 impl<A> Clone for Iter<'_, A> {
1375 fn clone(&self) -> Self {
1376 Iter { inner: self.inner.clone() }
1380 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
1382 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1384 /// This `struct` is created by the [`Option::iter_mut`] function.
1386 /// [`Option`]: enum.Option.html
1387 /// [`Some`]: enum.Option.html#variant.Some
1388 /// [`Option::iter_mut`]: enum.Option.html#method.iter_mut
1389 #[stable(feature = "rust1", since = "1.0.0")]
1391 pub struct IterMut<'a, A: 'a> { inner: Item<&'a mut A> }
1393 #[stable(feature = "rust1", since = "1.0.0")]
1394 impl<'a, A> Iterator for IterMut<'a, A> {
1395 type Item = &'a mut A;
1398 fn next(&mut self) -> Option<&'a mut A> { self.inner.next() }
1400 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1403 #[stable(feature = "rust1", since = "1.0.0")]
1404 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
1406 fn next_back(&mut self) -> Option<&'a mut A> { self.inner.next_back() }
1409 #[stable(feature = "rust1", since = "1.0.0")]
1410 impl<A> ExactSizeIterator for IterMut<'_, A> {}
1412 #[stable(feature = "fused", since = "1.26.0")]
1413 impl<A> FusedIterator for IterMut<'_, A> {}
1414 #[unstable(feature = "trusted_len", issue = "37572")]
1415 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1417 /// An iterator over the value in [`Some`] variant of an [`Option`].
1419 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1421 /// This `struct` is created by the [`Option::into_iter`] function.
1423 /// [`Option`]: enum.Option.html
1424 /// [`Some`]: enum.Option.html#variant.Some
1425 /// [`Option::into_iter`]: enum.Option.html#method.into_iter
1426 #[derive(Clone, Debug)]
1427 #[stable(feature = "rust1", since = "1.0.0")]
1428 pub struct IntoIter<A> { inner: Item<A> }
1430 #[stable(feature = "rust1", since = "1.0.0")]
1431 impl<A> Iterator for IntoIter<A> {
1435 fn next(&mut self) -> Option<A> { self.inner.next() }
1437 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1440 #[stable(feature = "rust1", since = "1.0.0")]
1441 impl<A> DoubleEndedIterator for IntoIter<A> {
1443 fn next_back(&mut self) -> Option<A> { self.inner.next_back() }
1446 #[stable(feature = "rust1", since = "1.0.0")]
1447 impl<A> ExactSizeIterator for IntoIter<A> {}
1449 #[stable(feature = "fused", since = "1.26.0")]
1450 impl<A> FusedIterator for IntoIter<A> {}
1452 #[unstable(feature = "trusted_len", issue = "37572")]
1453 unsafe impl<A> TrustedLen for IntoIter<A> {}
1455 /////////////////////////////////////////////////////////////////////////////
1457 /////////////////////////////////////////////////////////////////////////////
1459 #[stable(feature = "rust1", since = "1.0.0")]
1460 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
1461 /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
1462 /// no further elements are taken, and the [`None`][Option::None] is
1463 /// returned. Should no [`None`][Option::None] occur, a container with the
1464 /// values of each [`Option`] is returned.
1468 /// Here is an example which increments every integer in a vector.
1469 /// We use the checked variant of `add` that returns `None` when the
1470 /// calculation would result in an overflow.
1473 /// let items = vec![0_u16, 1, 2];
1475 /// let res: Option<Vec<u16>> = items
1477 /// .map(|x| x.checked_add(1))
1480 /// assert_eq!(res, Some(vec![1, 2, 3]));
1483 /// As you can see, this will return the expected, valid items.
1485 /// Here is another example that tries to subtract one from another list
1486 /// of integers, this time checking for underflow:
1489 /// let items = vec![2_u16, 1, 0];
1491 /// let res: Option<Vec<u16>> = items
1493 /// .map(|x| x.checked_sub(1))
1496 /// assert_eq!(res, None);
1499 /// Since the last element is zero, it would underflow. Thus, the resulting
1500 /// value is `None`.
1502 /// Here is a variation on the previous example, showing that no
1503 /// further elements are taken from `iter` after the first `None`.
1506 /// let items = vec![3_u16, 2, 1, 10];
1508 /// let mut shared = 0;
1510 /// let res: Option<Vec<u16>> = items
1512 /// .map(|x| { shared += x; x.checked_sub(2) })
1515 /// assert_eq!(res, None);
1516 /// assert_eq!(shared, 6);
1519 /// Since the third element caused an underflow, no further elements were taken,
1520 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1522 /// [`Iterator`]: ../iter/trait.Iterator.html
1524 fn from_iter<I: IntoIterator<Item=Option<A>>>(iter: I) -> Option<V> {
1525 // FIXME(#11084): This could be replaced with Iterator::scan when this
1526 // performance bug is closed.
1529 .map(|x| x.ok_or(()))
1530 .collect::<Result<_, _>>()
1535 /// The error type that results from applying the try operator (`?`) to a `None` value. If you wish
1536 /// to allow `x?` (where `x` is an `Option<T>`) to be converted into your error type, you can
1537 /// implement `impl From<NoneError>` for `YourErrorType`. In that case, `x?` within a function that
1538 /// returns `Result<_, YourErrorType>` will translate a `None` value into an `Err` result.
1539 #[unstable(feature = "try_trait", issue = "42327")]
1540 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
1541 pub struct NoneError;
1543 #[unstable(feature = "try_trait", issue = "42327")]
1544 impl<T> ops::Try for Option<T> {
1546 type Error = NoneError;
1549 fn into_result(self) -> Result<T, NoneError> {
1550 self.ok_or(NoneError)
1554 fn from_ok(v: T) -> Self {
1559 fn from_error(_: NoneError) -> Self {
1564 impl<T> Option<Option<T>> {
1565 /// Converts from `Option<Option<T>>` to `Option<T>`
1570 /// let x: Option<Option<u32>> = Some(Some(6));
1571 /// assert_eq!(Some(6), x.flatten());
1573 /// let x: Option<Option<u32>> = Some(None);
1574 /// assert_eq!(None, x.flatten());
1576 /// let x: Option<Option<u32>> = None;
1577 /// assert_eq!(None, x.flatten());
1579 /// Flattening once only removes one level of nesting:
1581 /// let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
1582 /// assert_eq!(Some(Some(6)), x.flatten());
1583 /// assert_eq!(Some(6), x.flatten().flatten());
1586 #[stable(feature = "option_flattening", since = "1.40.0")]
1587 pub fn flatten(self) -> Option<T> {
1588 self.and_then(convert::identity)