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" pointers. 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(ref 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(ref 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, hint, mem, ops::{self, Deref}};
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(Clone, 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
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
206 #[stable(feature = "rust1", since = "1.0.0")]
207 pub fn is_none(&self) -> bool {
211 /////////////////////////////////////////////////////////////////////////
212 // Adapter for working with references
213 /////////////////////////////////////////////////////////////////////////
215 /// Converts from `&Option<T>` to `Option<&T>`.
219 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
220 /// The [`map`] method takes the `self` argument by value, consuming the original,
221 /// so this technique uses `as_ref` to first take an `Option` to a reference
222 /// to the value inside the original.
224 /// [`map`]: enum.Option.html#method.map
225 /// [`String`]: ../../std/string/struct.String.html
226 /// [`usize`]: ../../std/primitive.usize.html
229 /// let text: Option<String> = Some("Hello, world!".to_string());
230 /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
231 /// // then consume *that* with `map`, leaving `text` on the stack.
232 /// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
233 /// println!("still can print text: {:?}", text);
236 #[stable(feature = "rust1", since = "1.0.0")]
237 pub fn as_ref(&self) -> Option<&T> {
239 Some(ref x) => Some(x),
244 /// Converts from `&mut Option<T>` to `Option<&mut T>`.
249 /// let mut x = Some(2);
250 /// match x.as_mut() {
251 /// Some(v) => *v = 42,
254 /// assert_eq!(x, Some(42));
257 #[stable(feature = "rust1", since = "1.0.0")]
258 pub fn as_mut(&mut self) -> Option<&mut T> {
260 Some(ref mut x) => Some(x),
266 /// Converts from `Pin<&Option<T>>` to `Option<Pin<&T>>`
268 #[stable(feature = "pin", since = "1.33.0")]
269 pub fn as_pin_ref<'a>(self: Pin<&'a Option<T>>) -> Option<Pin<&'a T>> {
271 Pin::get_ref(self).as_ref().map(|x| Pin::new_unchecked(x))
275 /// Converts from `Pin<&mut Option<T>>` to `Option<Pin<&mut T>>`
277 #[stable(feature = "pin", since = "1.33.0")]
278 pub fn as_pin_mut<'a>(self: Pin<&'a mut Option<T>>) -> Option<Pin<&'a mut T>> {
280 Pin::get_unchecked_mut(self).as_mut().map(|x| Pin::new_unchecked(x))
284 /////////////////////////////////////////////////////////////////////////
285 // Getting to contained values
286 /////////////////////////////////////////////////////////////////////////
288 /// Unwraps an option, yielding the content of a [`Some`].
292 /// Panics if the value is a [`None`] with a custom panic message provided by
295 /// [`Some`]: #variant.Some
296 /// [`None`]: #variant.None
301 /// let x = Some("value");
302 /// assert_eq!(x.expect("the world is ending"), "value");
305 /// ```{.should_panic}
306 /// let x: Option<&str> = None;
307 /// x.expect("the world is ending"); // panics with `the world is ending`
310 #[stable(feature = "rust1", since = "1.0.0")]
311 pub fn expect(self, msg: &str) -> T {
314 None => expect_failed(msg),
318 /// Moves the value `v` out of the `Option<T>` if it is [`Some(v)`].
320 /// In general, because this function may panic, its use is discouraged.
321 /// Instead, prefer to use pattern matching and handle the [`None`]
326 /// Panics if the self value equals [`None`].
328 /// [`Some(v)`]: #variant.Some
329 /// [`None`]: #variant.None
334 /// let x = Some("air");
335 /// assert_eq!(x.unwrap(), "air");
338 /// ```{.should_panic}
339 /// let x: Option<&str> = None;
340 /// assert_eq!(x.unwrap(), "air"); // fails
343 #[stable(feature = "rust1", since = "1.0.0")]
344 pub fn unwrap(self) -> T {
347 None => panic!("called `Option::unwrap()` on a `None` value"),
351 /// Returns the contained value or a default.
353 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
354 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
355 /// which is lazily evaluated.
357 /// [`unwrap_or_else`]: #method.unwrap_or_else
362 /// assert_eq!(Some("car").unwrap_or("bike"), "car");
363 /// assert_eq!(None.unwrap_or("bike"), "bike");
366 #[stable(feature = "rust1", since = "1.0.0")]
367 pub fn unwrap_or(self, def: T) -> T {
374 /// Returns the contained value or computes it from a closure.
380 /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
381 /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
384 #[stable(feature = "rust1", since = "1.0.0")]
385 pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
392 /////////////////////////////////////////////////////////////////////////
393 // Transforming contained values
394 /////////////////////////////////////////////////////////////////////////
396 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
400 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, consuming the original:
402 /// [`String`]: ../../std/string/struct.String.html
403 /// [`usize`]: ../../std/primitive.usize.html
406 /// let maybe_some_string = Some(String::from("Hello, World!"));
407 /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
408 /// let maybe_some_len = maybe_some_string.map(|s| s.len());
410 /// assert_eq!(maybe_some_len, Some(13));
413 #[stable(feature = "rust1", since = "1.0.0")]
414 pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
416 Some(x) => Some(f(x)),
421 /// Applies a function to the contained value (if any),
422 /// or returns the provided default (if not).
427 /// let x = Some("foo");
428 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
430 /// let x: Option<&str> = None;
431 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
434 #[stable(feature = "rust1", since = "1.0.0")]
435 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
442 /// Applies a function to the contained value (if any),
443 /// or computes a default (if not).
450 /// let x = Some("foo");
451 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
453 /// let x: Option<&str> = None;
454 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
457 #[stable(feature = "rust1", since = "1.0.0")]
458 pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
465 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
466 /// [`Ok(v)`] and [`None`] to [`Err(err)`].
468 /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
469 /// result of a function call, it is recommended to use [`ok_or_else`], which is
470 /// lazily evaluated.
472 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
473 /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
474 /// [`Err(err)`]: ../../std/result/enum.Result.html#variant.Err
475 /// [`None`]: #variant.None
476 /// [`Some(v)`]: #variant.Some
477 /// [`ok_or_else`]: #method.ok_or_else
482 /// let x = Some("foo");
483 /// assert_eq!(x.ok_or(0), Ok("foo"));
485 /// let x: Option<&str> = None;
486 /// assert_eq!(x.ok_or(0), Err(0));
489 #[stable(feature = "rust1", since = "1.0.0")]
490 pub fn ok_or<E>(self, err: E) -> Result<T, E> {
497 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
498 /// [`Ok(v)`] and [`None`] to [`Err(err())`].
500 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
501 /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
502 /// [`Err(err())`]: ../../std/result/enum.Result.html#variant.Err
503 /// [`None`]: #variant.None
504 /// [`Some(v)`]: #variant.Some
509 /// let x = Some("foo");
510 /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
512 /// let x: Option<&str> = None;
513 /// assert_eq!(x.ok_or_else(|| 0), Err(0));
516 #[stable(feature = "rust1", since = "1.0.0")]
517 pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
524 /////////////////////////////////////////////////////////////////////////
525 // Iterator constructors
526 /////////////////////////////////////////////////////////////////////////
528 /// Returns an iterator over the possibly contained value.
534 /// assert_eq!(x.iter().next(), Some(&4));
536 /// let x: Option<u32> = None;
537 /// assert_eq!(x.iter().next(), None);
540 #[stable(feature = "rust1", since = "1.0.0")]
541 pub fn iter(&self) -> Iter<'_, T> {
542 Iter { inner: Item { opt: self.as_ref() } }
545 /// Returns a mutable iterator over the possibly contained value.
550 /// let mut x = Some(4);
551 /// match x.iter_mut().next() {
552 /// Some(v) => *v = 42,
555 /// assert_eq!(x, Some(42));
557 /// let mut x: Option<u32> = None;
558 /// assert_eq!(x.iter_mut().next(), None);
561 #[stable(feature = "rust1", since = "1.0.0")]
562 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
563 IterMut { inner: Item { opt: self.as_mut() } }
566 /////////////////////////////////////////////////////////////////////////
567 // Boolean operations on the values, eager and lazy
568 /////////////////////////////////////////////////////////////////////////
570 /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
572 /// [`None`]: #variant.None
578 /// let y: Option<&str> = None;
579 /// assert_eq!(x.and(y), None);
581 /// let x: Option<u32> = None;
582 /// let y = Some("foo");
583 /// assert_eq!(x.and(y), None);
586 /// let y = Some("foo");
587 /// assert_eq!(x.and(y), Some("foo"));
589 /// let x: Option<u32> = None;
590 /// let y: Option<&str> = None;
591 /// assert_eq!(x.and(y), None);
594 #[stable(feature = "rust1", since = "1.0.0")]
595 pub fn and<U>(self, optb: Option<U>) -> Option<U> {
602 /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
603 /// wrapped value and returns the result.
605 /// Some languages call this operation flatmap.
607 /// [`None`]: #variant.None
612 /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
613 /// fn nope(_: u32) -> Option<u32> { None }
615 /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
616 /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
617 /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
618 /// assert_eq!(None.and_then(sq).and_then(sq), None);
621 #[stable(feature = "rust1", since = "1.0.0")]
622 pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> {
629 /// Returns `None` if the option is `None`, otherwise calls `predicate`
630 /// with the wrapped value and returns:
632 /// - `Some(t)` if `predicate` returns `true` (where `t` is the wrapped
634 /// - `None` if `predicate` returns `false`.
636 /// This function works similar to `Iterator::filter()`. You can imagine
637 /// the `Option<T>` being an iterator over one or zero elements. `filter()`
638 /// lets you decide which elements to keep.
643 /// fn is_even(n: &i32) -> bool {
647 /// assert_eq!(None.filter(is_even), None);
648 /// assert_eq!(Some(3).filter(is_even), None);
649 /// assert_eq!(Some(4).filter(is_even), Some(4));
652 #[stable(feature = "option_filter", since = "1.27.0")]
653 pub fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Self {
654 if let Some(x) = self {
662 /// Returns the option if it contains a value, otherwise returns `optb`.
664 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
665 /// result of a function call, it is recommended to use [`or_else`], which is
666 /// lazily evaluated.
668 /// [`or_else`]: #method.or_else
675 /// assert_eq!(x.or(y), Some(2));
678 /// let y = Some(100);
679 /// assert_eq!(x.or(y), Some(100));
682 /// let y = Some(100);
683 /// assert_eq!(x.or(y), Some(2));
685 /// let x: Option<u32> = None;
687 /// assert_eq!(x.or(y), None);
690 #[stable(feature = "rust1", since = "1.0.0")]
691 pub fn or(self, optb: Option<T>) -> Option<T> {
698 /// Returns the option if it contains a value, otherwise calls `f` and
699 /// returns the result.
704 /// fn nobody() -> Option<&'static str> { None }
705 /// fn vikings() -> Option<&'static str> { Some("vikings") }
707 /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
708 /// assert_eq!(None.or_else(vikings), Some("vikings"));
709 /// assert_eq!(None.or_else(nobody), None);
712 #[stable(feature = "rust1", since = "1.0.0")]
713 pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> {
720 /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns `None`.
722 /// [`Some`]: #variant.Some
723 /// [`None`]: #variant.None
728 /// #![feature(option_xor)]
731 /// let y: Option<u32> = None;
732 /// assert_eq!(x.xor(y), Some(2));
734 /// let x: Option<u32> = None;
736 /// assert_eq!(x.xor(y), Some(2));
740 /// assert_eq!(x.xor(y), None);
742 /// let x: Option<u32> = None;
743 /// let y: Option<u32> = None;
744 /// assert_eq!(x.xor(y), None);
747 #[unstable(feature = "option_xor", issue = "50512")]
748 pub fn xor(self, optb: Option<T>) -> Option<T> {
750 (Some(a), None) => Some(a),
751 (None, Some(b)) => Some(b),
756 /////////////////////////////////////////////////////////////////////////
757 // Entry-like operations to insert if None and return a reference
758 /////////////////////////////////////////////////////////////////////////
760 /// Inserts `v` into the option if it is [`None`], then
761 /// returns a mutable reference to the contained value.
763 /// [`None`]: #variant.None
768 /// let mut x = None;
771 /// let y: &mut u32 = x.get_or_insert(5);
772 /// assert_eq!(y, &5);
777 /// assert_eq!(x, Some(7));
780 #[stable(feature = "option_entry", since = "1.20.0")]
781 pub fn get_or_insert(&mut self, v: T) -> &mut T {
783 None => *self = Some(v),
788 Some(ref mut v) => v,
789 None => unsafe { hint::unreachable_unchecked() },
793 /// Inserts a value computed from `f` 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_with(|| 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_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
816 None => *self = Some(f()),
821 Some(ref mut v) => v,
822 None => unsafe { hint::unreachable_unchecked() },
826 /////////////////////////////////////////////////////////////////////////
828 /////////////////////////////////////////////////////////////////////////
830 /// Takes the value out of the option, leaving a [`None`] in its place.
832 /// [`None`]: #variant.None
837 /// let mut x = Some(2);
838 /// let y = x.take();
839 /// assert_eq!(x, None);
840 /// assert_eq!(y, Some(2));
842 /// let mut x: Option<u32> = None;
843 /// let y = x.take();
844 /// assert_eq!(x, None);
845 /// assert_eq!(y, None);
848 #[stable(feature = "rust1", since = "1.0.0")]
849 pub fn take(&mut self) -> Option<T> {
850 mem::replace(self, None)
853 /// Replaces the actual value in the option by the value given in parameter,
854 /// returning the old value if present,
855 /// leaving a [`Some`] in its place without deinitializing either one.
857 /// [`Some`]: #variant.Some
862 /// let mut x = Some(2);
863 /// let old = x.replace(5);
864 /// assert_eq!(x, Some(5));
865 /// assert_eq!(old, Some(2));
867 /// let mut x = None;
868 /// let old = x.replace(3);
869 /// assert_eq!(x, Some(3));
870 /// assert_eq!(old, None);
873 #[stable(feature = "option_replace", since = "1.31.0")]
874 pub fn replace(&mut self, value: T) -> Option<T> {
875 mem::replace(self, Some(value))
879 impl<T: Copy> Option<&T> {
880 /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
887 /// let opt_x = Some(&x);
888 /// assert_eq!(opt_x, Some(&12));
889 /// let copied = opt_x.copied();
890 /// assert_eq!(copied, Some(12));
892 #[stable(feature = "copied", since = "1.35.0")]
893 pub fn copied(self) -> Option<T> {
898 impl<T: Copy> Option<&mut T> {
899 /// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the
906 /// let opt_x = Some(&mut x);
907 /// assert_eq!(opt_x, Some(&mut 12));
908 /// let copied = opt_x.copied();
909 /// assert_eq!(copied, Some(12));
911 #[stable(feature = "copied", since = "1.35.0")]
912 pub fn copied(self) -> Option<T> {
917 impl<T: Clone> Option<&T> {
918 /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
925 /// let opt_x = Some(&x);
926 /// assert_eq!(opt_x, Some(&12));
927 /// let cloned = opt_x.cloned();
928 /// assert_eq!(cloned, Some(12));
930 #[stable(feature = "rust1", since = "1.0.0")]
931 pub fn cloned(self) -> Option<T> {
932 self.map(|t| t.clone())
936 impl<T: Clone> Option<&mut T> {
937 /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
944 /// let opt_x = Some(&mut x);
945 /// assert_eq!(opt_x, Some(&mut 12));
946 /// let cloned = opt_x.cloned();
947 /// assert_eq!(cloned, Some(12));
949 #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
950 pub fn cloned(self) -> Option<T> {
951 self.map(|t| t.clone())
955 impl<T: Default> Option<T> {
956 /// Returns the contained value or a default
958 /// Consumes the `self` argument then, if [`Some`], returns the contained
959 /// value, otherwise if [`None`], returns the [default value] for that
964 /// Converts a string to an integer, turning poorly-formed strings
965 /// into 0 (the default value for integers). [`parse`] converts
966 /// a string to any other type that implements [`FromStr`], returning
967 /// [`None`] on error.
970 /// let good_year_from_input = "1909";
971 /// let bad_year_from_input = "190blarg";
972 /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
973 /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
975 /// assert_eq!(1909, good_year);
976 /// assert_eq!(0, bad_year);
979 /// [`Some`]: #variant.Some
980 /// [`None`]: #variant.None
981 /// [default value]: ../default/trait.Default.html#tymethod.default
982 /// [`parse`]: ../../std/primitive.str.html#method.parse
983 /// [`FromStr`]: ../../std/str/trait.FromStr.html
985 #[stable(feature = "rust1", since = "1.0.0")]
986 pub fn unwrap_or_default(self) -> T {
989 None => Default::default(),
994 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
995 impl<T: Deref> Option<T> {
996 /// Converts from `&Option<T>` to `Option<&T::Target>`.
998 /// Leaves the original Option in-place, creating a new one with a reference
999 /// to the original one, additionally coercing the contents via `Deref`.
1000 pub fn deref(&self) -> Option<&T::Target> {
1001 self.as_ref().map(|t| t.deref())
1005 impl<T, E> Option<Result<T, E>> {
1006 /// Transposes an `Option` of a `Result` into a `Result` of an `Option`.
1008 /// `None` will be mapped to `Ok(None)`.
1009 /// `Some(Ok(_))` and `Some(Err(_))` will be mapped to `Ok(Some(_))` and `Err(_)`.
1014 /// #[derive(Debug, Eq, PartialEq)]
1017 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1018 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1019 /// assert_eq!(x, y.transpose());
1022 #[stable(feature = "transpose_result", since = "1.33.0")]
1023 pub fn transpose(self) -> Result<Option<T>, E> {
1025 Some(Ok(x)) => Ok(Some(x)),
1026 Some(Err(e)) => Err(e),
1032 // This is a separate function to reduce the code size of .expect() itself.
1035 fn expect_failed(msg: &str) -> ! {
1039 /////////////////////////////////////////////////////////////////////////////
1040 // Trait implementations
1041 /////////////////////////////////////////////////////////////////////////////
1043 #[stable(feature = "rust1", since = "1.0.0")]
1044 impl<T> Default for Option<T> {
1045 /// Returns [`None`][Option::None].
1047 fn default() -> Option<T> { None }
1050 #[stable(feature = "rust1", since = "1.0.0")]
1051 impl<T> IntoIterator for Option<T> {
1053 type IntoIter = IntoIter<T>;
1055 /// Returns a consuming iterator over the possibly contained value.
1060 /// let x = Some("string");
1061 /// let v: Vec<&str> = x.into_iter().collect();
1062 /// assert_eq!(v, ["string"]);
1065 /// let v: Vec<&str> = x.into_iter().collect();
1066 /// assert!(v.is_empty());
1069 fn into_iter(self) -> IntoIter<T> {
1070 IntoIter { inner: Item { opt: self } }
1074 #[stable(since = "1.4.0", feature = "option_iter")]
1075 impl<'a, T> IntoIterator for &'a Option<T> {
1077 type IntoIter = Iter<'a, T>;
1079 fn into_iter(self) -> Iter<'a, T> {
1084 #[stable(since = "1.4.0", feature = "option_iter")]
1085 impl<'a, T> IntoIterator for &'a mut Option<T> {
1086 type Item = &'a mut T;
1087 type IntoIter = IterMut<'a, T>;
1089 fn into_iter(self) -> IterMut<'a, T> {
1094 #[stable(since = "1.12.0", feature = "option_from")]
1095 impl<T> From<T> for Option<T> {
1096 fn from(val: T) -> Option<T> {
1101 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1102 impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
1103 fn from(o: &'a Option<T>) -> Option<&'a T> {
1108 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1109 impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> {
1110 fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
1115 /////////////////////////////////////////////////////////////////////////////
1116 // The Option Iterators
1117 /////////////////////////////////////////////////////////////////////////////
1119 #[derive(Clone, Debug)]
1124 impl<A> Iterator for Item<A> {
1128 fn next(&mut self) -> Option<A> {
1133 fn size_hint(&self) -> (usize, Option<usize>) {
1135 Some(_) => (1, Some(1)),
1136 None => (0, Some(0)),
1141 impl<A> DoubleEndedIterator for Item<A> {
1143 fn next_back(&mut self) -> Option<A> {
1148 impl<A> ExactSizeIterator for Item<A> {}
1149 impl<A> FusedIterator for Item<A> {}
1150 unsafe impl<A> TrustedLen for Item<A> {}
1152 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
1154 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1156 /// This `struct` is created by the [`Option::iter`] function.
1158 /// [`Option`]: enum.Option.html
1159 /// [`Some`]: enum.Option.html#variant.Some
1160 /// [`Option::iter`]: enum.Option.html#method.iter
1161 #[stable(feature = "rust1", since = "1.0.0")]
1163 pub struct Iter<'a, A: 'a> { inner: Item<&'a A> }
1165 #[stable(feature = "rust1", since = "1.0.0")]
1166 impl<'a, A> Iterator for Iter<'a, A> {
1170 fn next(&mut self) -> Option<&'a A> { self.inner.next() }
1172 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1175 #[stable(feature = "rust1", since = "1.0.0")]
1176 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
1178 fn next_back(&mut self) -> Option<&'a A> { self.inner.next_back() }
1181 #[stable(feature = "rust1", since = "1.0.0")]
1182 impl<A> ExactSizeIterator for Iter<'_, A> {}
1184 #[stable(feature = "fused", since = "1.26.0")]
1185 impl<A> FusedIterator for Iter<'_, A> {}
1187 #[unstable(feature = "trusted_len", issue = "37572")]
1188 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1190 #[stable(feature = "rust1", since = "1.0.0")]
1191 impl<A> Clone for Iter<'_, A> {
1193 fn clone(&self) -> Self {
1194 Iter { inner: self.inner.clone() }
1198 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
1200 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1202 /// This `struct` is created by the [`Option::iter_mut`] function.
1204 /// [`Option`]: enum.Option.html
1205 /// [`Some`]: enum.Option.html#variant.Some
1206 /// [`Option::iter_mut`]: enum.Option.html#method.iter_mut
1207 #[stable(feature = "rust1", since = "1.0.0")]
1209 pub struct IterMut<'a, A: 'a> { inner: Item<&'a mut A> }
1211 #[stable(feature = "rust1", since = "1.0.0")]
1212 impl<'a, A> Iterator for IterMut<'a, A> {
1213 type Item = &'a mut A;
1216 fn next(&mut self) -> Option<&'a mut A> { self.inner.next() }
1218 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1221 #[stable(feature = "rust1", since = "1.0.0")]
1222 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
1224 fn next_back(&mut self) -> Option<&'a mut A> { self.inner.next_back() }
1227 #[stable(feature = "rust1", since = "1.0.0")]
1228 impl<A> ExactSizeIterator for IterMut<'_, A> {}
1230 #[stable(feature = "fused", since = "1.26.0")]
1231 impl<A> FusedIterator for IterMut<'_, A> {}
1232 #[unstable(feature = "trusted_len", issue = "37572")]
1233 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1235 /// An iterator over the value in [`Some`] variant of an [`Option`].
1237 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1239 /// This `struct` is created by the [`Option::into_iter`] function.
1241 /// [`Option`]: enum.Option.html
1242 /// [`Some`]: enum.Option.html#variant.Some
1243 /// [`Option::into_iter`]: enum.Option.html#method.into_iter
1244 #[derive(Clone, Debug)]
1245 #[stable(feature = "rust1", since = "1.0.0")]
1246 pub struct IntoIter<A> { inner: Item<A> }
1248 #[stable(feature = "rust1", since = "1.0.0")]
1249 impl<A> Iterator for IntoIter<A> {
1253 fn next(&mut self) -> Option<A> { self.inner.next() }
1255 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1258 #[stable(feature = "rust1", since = "1.0.0")]
1259 impl<A> DoubleEndedIterator for IntoIter<A> {
1261 fn next_back(&mut self) -> Option<A> { self.inner.next_back() }
1264 #[stable(feature = "rust1", since = "1.0.0")]
1265 impl<A> ExactSizeIterator for IntoIter<A> {}
1267 #[stable(feature = "fused", since = "1.26.0")]
1268 impl<A> FusedIterator for IntoIter<A> {}
1270 #[unstable(feature = "trusted_len", issue = "37572")]
1271 unsafe impl<A> TrustedLen for IntoIter<A> {}
1273 /////////////////////////////////////////////////////////////////////////////
1275 /////////////////////////////////////////////////////////////////////////////
1277 #[stable(feature = "rust1", since = "1.0.0")]
1278 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
1279 /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
1280 /// no further elements are taken, and the [`None`][Option::None] is
1281 /// returned. Should no [`None`][Option::None] occur, a container with the
1282 /// values of each [`Option`] is returned.
1286 /// Here is an example which increments every integer in a vector.
1287 /// We use the checked variant of `add` that returns `None` when the
1288 /// calculation would result in an overflow.
1291 /// let items = vec![0_u16, 1, 2];
1293 /// let res: Option<Vec<u16>> = items
1295 /// .map(|x| x.checked_add(1))
1298 /// assert_eq!(res, Some(vec![1, 2, 3]));
1301 /// As you can see, this will return the expected, valid items.
1303 /// Here is another example that tries to subtract one from another list
1304 /// of integers, this time checking for underflow:
1307 /// let items = vec![2_u16, 1, 0];
1309 /// let res: Option<Vec<u16>> = items
1311 /// .map(|x| x.checked_sub(1))
1314 /// assert_eq!(res, None);
1317 /// Since the last element is zero, it would underflow. Thus, the resulting
1318 /// value is `None`.
1320 /// Here is a variation on the previous example, showing that no
1321 /// further elements are taken from `iter` after the first `None`.
1324 /// let items = vec![3_u16, 2, 1, 10];
1326 /// let mut shared = 0;
1328 /// let res: Option<Vec<u16>> = items
1330 /// .map(|x| { shared += x; x.checked_sub(2) })
1333 /// assert_eq!(res, None);
1334 /// assert_eq!(shared, 6);
1337 /// Since the third element caused an underflow, no further elements were taken,
1338 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1340 /// [`Iterator`]: ../iter/trait.Iterator.html
1342 fn from_iter<I: IntoIterator<Item=Option<A>>>(iter: I) -> Option<V> {
1343 // FIXME(#11084): This could be replaced with Iterator::scan when this
1344 // performance bug is closed.
1346 struct Adapter<Iter> {
1351 impl<T, Iter: Iterator<Item=Option<T>>> Iterator for Adapter<Iter> {
1355 fn next(&mut self) -> Option<T> {
1356 match self.iter.next() {
1357 Some(Some(value)) => Some(value),
1359 self.found_none = true;
1367 fn size_hint(&self) -> (usize, Option<usize>) {
1368 if self.found_none {
1371 let (_, upper) = self.iter.size_hint();
1377 let mut adapter = Adapter { iter: iter.into_iter(), found_none: false };
1378 let v: V = FromIterator::from_iter(adapter.by_ref());
1380 if adapter.found_none {
1388 /// The error type that results from applying the try operator (`?`) to a `None` value. If you wish
1389 /// to allow `x?` (where `x` is an `Option<T>`) to be converted into your error type, you can
1390 /// implement `impl From<NoneError>` for `YourErrorType`. In that case, `x?` within a function that
1391 /// returns `Result<_, YourErrorType>` will translate a `None` value into an `Err` result.
1392 #[unstable(feature = "try_trait", issue = "42327")]
1393 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
1394 pub struct NoneError;
1396 #[unstable(feature = "try_trait", issue = "42327")]
1397 impl<T> ops::Try for Option<T> {
1399 type Error = NoneError;
1402 fn into_result(self) -> Result<T, NoneError> {
1403 self.ok_or(NoneError)
1407 fn from_ok(v: T) -> Self {
1412 fn from_error(_: NoneError) -> Self {
1417 impl<T> Option<Option<T>> {
1418 /// Converts from `Option<Option<T>>` to `Option<T>`
1423 /// #![feature(option_flattening)]
1424 /// let x: Option<Option<u32>> = Some(Some(6));
1425 /// assert_eq!(Some(6), x.flatten());
1427 /// let x: Option<Option<u32>> = Some(None);
1428 /// assert_eq!(None, x.flatten());
1430 /// let x: Option<Option<u32>> = None;
1431 /// assert_eq!(None, x.flatten());
1433 /// Flattening once only removes one level of nesting:
1435 /// #![feature(option_flattening)]
1436 /// let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
1437 /// assert_eq!(Some(Some(6)), x.flatten());
1438 /// assert_eq!(Some(6), x.flatten().flatten());
1441 #[unstable(feature = "option_flattening", issue = "60258")]
1442 pub fn flatten(self) -> Option<T> {
1443 self.and_then(convert::identity)