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 iter::{FromIterator, FusedIterator, TrustedLen};
139 use {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
182 #[stable(feature = "rust1", since = "1.0.0")]
183 pub fn is_some(&self) -> bool {
190 /// Returns `true` if the option is a [`None`] value.
195 /// let x: Option<u32> = Some(2);
196 /// assert_eq!(x.is_none(), false);
198 /// let x: Option<u32> = None;
199 /// assert_eq!(x.is_none(), true);
202 /// [`None`]: #variant.None
204 #[stable(feature = "rust1", since = "1.0.0")]
205 pub fn is_none(&self) -> bool {
209 /////////////////////////////////////////////////////////////////////////
210 // Adapter for working with references
211 /////////////////////////////////////////////////////////////////////////
213 /// Converts from `Option<T>` to `Option<&T>`.
217 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
218 /// The [`map`] method takes the `self` argument by value, consuming the original,
219 /// so this technique uses `as_ref` to first take an `Option` to a reference
220 /// to the value inside the original.
222 /// [`map`]: enum.Option.html#method.map
223 /// [`String`]: ../../std/string/struct.String.html
224 /// [`usize`]: ../../std/primitive.usize.html
227 /// let text: Option<String> = Some("Hello, world!".to_string());
228 /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
229 /// // then consume *that* with `map`, leaving `text` on the stack.
230 /// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
231 /// println!("still can print text: {:?}", text);
234 #[stable(feature = "rust1", since = "1.0.0")]
235 pub fn as_ref(&self) -> Option<&T> {
237 Some(ref x) => Some(x),
242 /// Converts from `Option<T>` to `Option<&mut T>`.
247 /// let mut x = Some(2);
248 /// match x.as_mut() {
249 /// Some(v) => *v = 42,
252 /// assert_eq!(x, Some(42));
255 #[stable(feature = "rust1", since = "1.0.0")]
256 pub fn as_mut(&mut self) -> Option<&mut T> {
258 Some(ref mut x) => Some(x),
264 /// Converts from `Pin<&Option<T>>` to `Option<Pin<&T>>`
266 #[stable(feature = "pin", since = "1.33.0")]
267 pub fn as_pin_ref<'a>(self: Pin<&'a Option<T>>) -> Option<Pin<&'a T>> {
269 Pin::get_ref(self).as_ref().map(|x| Pin::new_unchecked(x))
273 /// Converts from `Pin<&mut Option<T>>` to `Option<Pin<&mut T>>`
275 #[stable(feature = "pin", since = "1.33.0")]
276 pub fn as_pin_mut<'a>(self: Pin<&'a mut Option<T>>) -> Option<Pin<&'a mut T>> {
278 Pin::get_unchecked_mut(self).as_mut().map(|x| Pin::new_unchecked(x))
282 /////////////////////////////////////////////////////////////////////////
283 // Getting to contained values
284 /////////////////////////////////////////////////////////////////////////
286 /// Unwraps an option, yielding the content of a [`Some`].
290 /// Panics if the value is a [`None`] with a custom panic message provided by
293 /// [`Some`]: #variant.Some
294 /// [`None`]: #variant.None
299 /// let x = Some("value");
300 /// assert_eq!(x.expect("the world is ending"), "value");
303 /// ```{.should_panic}
304 /// let x: Option<&str> = None;
305 /// x.expect("the world is ending"); // panics with `the world is ending`
308 #[stable(feature = "rust1", since = "1.0.0")]
309 pub fn expect(self, msg: &str) -> T {
312 None => expect_failed(msg),
316 /// Moves the value `v` out of the `Option<T>` if it is [`Some(v)`].
318 /// In general, because this function may panic, its use is discouraged.
319 /// Instead, prefer to use pattern matching and handle the [`None`]
324 /// Panics if the self value equals [`None`].
326 /// [`Some(v)`]: #variant.Some
327 /// [`None`]: #variant.None
332 /// let x = Some("air");
333 /// assert_eq!(x.unwrap(), "air");
336 /// ```{.should_panic}
337 /// let x: Option<&str> = None;
338 /// assert_eq!(x.unwrap(), "air"); // fails
341 #[stable(feature = "rust1", since = "1.0.0")]
342 pub fn unwrap(self) -> T {
345 None => panic!("called `Option::unwrap()` on a `None` value"),
349 /// Returns the contained value or a default.
351 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
352 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
353 /// which is lazily evaluated.
355 /// [`unwrap_or_else`]: #method.unwrap_or_else
360 /// assert_eq!(Some("car").unwrap_or("bike"), "car");
361 /// assert_eq!(None.unwrap_or("bike"), "bike");
364 #[stable(feature = "rust1", since = "1.0.0")]
365 pub fn unwrap_or(self, def: T) -> T {
372 /// Returns the contained value or computes it from a closure.
378 /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
379 /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
382 #[stable(feature = "rust1", since = "1.0.0")]
383 pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
390 /////////////////////////////////////////////////////////////////////////
391 // Transforming contained values
392 /////////////////////////////////////////////////////////////////////////
394 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
398 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, consuming the original:
400 /// [`String`]: ../../std/string/struct.String.html
401 /// [`usize`]: ../../std/primitive.usize.html
404 /// let maybe_some_string = Some(String::from("Hello, World!"));
405 /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
406 /// let maybe_some_len = maybe_some_string.map(|s| s.len());
408 /// assert_eq!(maybe_some_len, Some(13));
411 #[stable(feature = "rust1", since = "1.0.0")]
412 pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
414 Some(x) => Some(f(x)),
419 /// Applies a function to the contained value (if any),
420 /// or returns the provided default (if not).
425 /// let x = Some("foo");
426 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
428 /// let x: Option<&str> = None;
429 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
432 #[stable(feature = "rust1", since = "1.0.0")]
433 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
440 /// Applies a function to the contained value (if any),
441 /// or computes a default (if not).
448 /// let x = Some("foo");
449 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
451 /// let x: Option<&str> = None;
452 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
455 #[stable(feature = "rust1", since = "1.0.0")]
456 pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
463 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
464 /// [`Ok(v)`] and [`None`] to [`Err(err)`].
466 /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
467 /// result of a function call, it is recommended to use [`ok_or_else`], which is
468 /// lazily evaluated.
470 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
471 /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
472 /// [`Err(err)`]: ../../std/result/enum.Result.html#variant.Err
473 /// [`None`]: #variant.None
474 /// [`Some(v)`]: #variant.Some
475 /// [`ok_or_else`]: #method.ok_or_else
480 /// let x = Some("foo");
481 /// assert_eq!(x.ok_or(0), Ok("foo"));
483 /// let x: Option<&str> = None;
484 /// assert_eq!(x.ok_or(0), Err(0));
487 #[stable(feature = "rust1", since = "1.0.0")]
488 pub fn ok_or<E>(self, err: E) -> Result<T, E> {
495 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
496 /// [`Ok(v)`] and [`None`] to [`Err(err())`].
498 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
499 /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
500 /// [`Err(err())`]: ../../std/result/enum.Result.html#variant.Err
501 /// [`None`]: #variant.None
502 /// [`Some(v)`]: #variant.Some
507 /// let x = Some("foo");
508 /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
510 /// let x: Option<&str> = None;
511 /// assert_eq!(x.ok_or_else(|| 0), Err(0));
514 #[stable(feature = "rust1", since = "1.0.0")]
515 pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
522 /////////////////////////////////////////////////////////////////////////
523 // Iterator constructors
524 /////////////////////////////////////////////////////////////////////////
526 /// Returns an iterator over the possibly contained value.
532 /// assert_eq!(x.iter().next(), Some(&4));
534 /// let x: Option<u32> = None;
535 /// assert_eq!(x.iter().next(), None);
538 #[stable(feature = "rust1", since = "1.0.0")]
539 pub fn iter(&self) -> Iter<T> {
540 Iter { inner: Item { opt: self.as_ref() } }
543 /// Returns a mutable iterator over the possibly contained value.
548 /// let mut x = Some(4);
549 /// match x.iter_mut().next() {
550 /// Some(v) => *v = 42,
553 /// assert_eq!(x, Some(42));
555 /// let mut x: Option<u32> = None;
556 /// assert_eq!(x.iter_mut().next(), None);
559 #[stable(feature = "rust1", since = "1.0.0")]
560 pub fn iter_mut(&mut self) -> IterMut<T> {
561 IterMut { inner: Item { opt: self.as_mut() } }
564 /////////////////////////////////////////////////////////////////////////
565 // Boolean operations on the values, eager and lazy
566 /////////////////////////////////////////////////////////////////////////
568 /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
570 /// [`None`]: #variant.None
576 /// let y: Option<&str> = None;
577 /// assert_eq!(x.and(y), None);
579 /// let x: Option<u32> = None;
580 /// let y = Some("foo");
581 /// assert_eq!(x.and(y), None);
584 /// let y = Some("foo");
585 /// assert_eq!(x.and(y), Some("foo"));
587 /// let x: Option<u32> = None;
588 /// let y: Option<&str> = None;
589 /// assert_eq!(x.and(y), None);
592 #[stable(feature = "rust1", since = "1.0.0")]
593 pub fn and<U>(self, optb: Option<U>) -> Option<U> {
600 /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
601 /// wrapped value and returns the result.
603 /// Some languages call this operation flatmap.
605 /// [`None`]: #variant.None
610 /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
611 /// fn nope(_: u32) -> Option<u32> { None }
613 /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
614 /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
615 /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
616 /// assert_eq!(None.and_then(sq).and_then(sq), None);
619 #[stable(feature = "rust1", since = "1.0.0")]
620 pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> {
627 /// Returns `None` if the option is `None`, otherwise calls `predicate`
628 /// with the wrapped value and returns:
630 /// - `Some(t)` if `predicate` returns `true` (where `t` is the wrapped
632 /// - `None` if `predicate` returns `false`.
634 /// This function works similar to `Iterator::filter()`. You can imagine
635 /// the `Option<T>` being an iterator over one or zero elements. `filter()`
636 /// lets you decide which elements to keep.
641 /// fn is_even(n: &i32) -> bool {
645 /// assert_eq!(None.filter(is_even), None);
646 /// assert_eq!(Some(3).filter(is_even), None);
647 /// assert_eq!(Some(4).filter(is_even), Some(4));
650 #[stable(feature = "option_filter", since = "1.27.0")]
651 pub fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Self {
652 if let Some(x) = self {
660 /// Returns the option if it contains a value, otherwise returns `optb`.
662 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
663 /// result of a function call, it is recommended to use [`or_else`], which is
664 /// lazily evaluated.
666 /// [`or_else`]: #method.or_else
673 /// assert_eq!(x.or(y), Some(2));
676 /// let y = Some(100);
677 /// assert_eq!(x.or(y), Some(100));
680 /// let y = Some(100);
681 /// assert_eq!(x.or(y), Some(2));
683 /// let x: Option<u32> = None;
685 /// assert_eq!(x.or(y), None);
688 #[stable(feature = "rust1", since = "1.0.0")]
689 pub fn or(self, optb: Option<T>) -> Option<T> {
696 /// Returns the option if it contains a value, otherwise calls `f` and
697 /// returns the result.
702 /// fn nobody() -> Option<&'static str> { None }
703 /// fn vikings() -> Option<&'static str> { Some("vikings") }
705 /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
706 /// assert_eq!(None.or_else(vikings), Some("vikings"));
707 /// assert_eq!(None.or_else(nobody), None);
710 #[stable(feature = "rust1", since = "1.0.0")]
711 pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> {
718 /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns `None`.
720 /// [`Some`]: #variant.Some
721 /// [`None`]: #variant.None
726 /// #![feature(option_xor)]
729 /// let y: Option<u32> = None;
730 /// assert_eq!(x.xor(y), Some(2));
732 /// let x: Option<u32> = None;
734 /// assert_eq!(x.xor(y), Some(2));
738 /// assert_eq!(x.xor(y), None);
740 /// let x: Option<u32> = None;
741 /// let y: Option<u32> = None;
742 /// assert_eq!(x.xor(y), None);
745 #[unstable(feature = "option_xor", issue = "50512")]
746 pub fn xor(self, optb: Option<T>) -> Option<T> {
748 (Some(a), None) => Some(a),
749 (None, Some(b)) => Some(b),
754 /////////////////////////////////////////////////////////////////////////
755 // Entry-like operations to insert if None and return a reference
756 /////////////////////////////////////////////////////////////////////////
758 /// Inserts `v` into the option if it is [`None`], then
759 /// returns a mutable reference to the contained value.
761 /// [`None`]: #variant.None
766 /// let mut x = None;
769 /// let y: &mut u32 = x.get_or_insert(5);
770 /// assert_eq!(y, &5);
775 /// assert_eq!(x, Some(7));
778 #[stable(feature = "option_entry", since = "1.20.0")]
779 pub fn get_or_insert(&mut self, v: T) -> &mut T {
781 None => *self = Some(v),
786 Some(ref mut v) => v,
787 None => unsafe { hint::unreachable_unchecked() },
791 /// Inserts a value computed from `f` into the option if it is [`None`], then
792 /// returns a mutable reference to the contained value.
794 /// [`None`]: #variant.None
799 /// let mut x = None;
802 /// let y: &mut u32 = x.get_or_insert_with(|| 5);
803 /// assert_eq!(y, &5);
808 /// assert_eq!(x, Some(7));
811 #[stable(feature = "option_entry", since = "1.20.0")]
812 pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
814 None => *self = Some(f()),
819 Some(ref mut v) => v,
820 None => unsafe { hint::unreachable_unchecked() },
824 /////////////////////////////////////////////////////////////////////////
826 /////////////////////////////////////////////////////////////////////////
828 /// Takes the value out of the option, leaving a [`None`] in its place.
830 /// [`None`]: #variant.None
835 /// let mut x = Some(2);
836 /// let y = x.take();
837 /// assert_eq!(x, None);
838 /// assert_eq!(y, Some(2));
840 /// let mut x: Option<u32> = None;
841 /// let y = x.take();
842 /// assert_eq!(x, None);
843 /// assert_eq!(y, None);
846 #[stable(feature = "rust1", since = "1.0.0")]
847 pub fn take(&mut self) -> Option<T> {
848 mem::replace(self, None)
851 /// Replaces the actual value in the option by the value given in parameter,
852 /// returning the old value if present,
853 /// leaving a [`Some`] in its place without deinitializing either one.
855 /// [`Some`]: #variant.Some
860 /// let mut x = Some(2);
861 /// let old = x.replace(5);
862 /// assert_eq!(x, Some(5));
863 /// assert_eq!(old, Some(2));
865 /// let mut x = None;
866 /// let old = x.replace(3);
867 /// assert_eq!(x, Some(3));
868 /// assert_eq!(old, None);
871 #[stable(feature = "option_replace", since = "1.31.0")]
872 pub fn replace(&mut self, value: T) -> Option<T> {
873 mem::replace(self, Some(value))
877 impl<T: Copy> Option<&T> {
878 /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
884 /// #![feature(copied)]
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 #[unstable(feature = "copied", issue = "57126")]
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
905 /// #![feature(copied)]
908 /// let opt_x = Some(&mut x);
909 /// assert_eq!(opt_x, Some(&mut 12));
910 /// let copied = opt_x.copied();
911 /// assert_eq!(copied, Some(12));
913 #[unstable(feature = "copied", issue = "57126")]
914 pub fn copied(self) -> Option<T> {
919 impl<T: Clone> Option<&T> {
920 /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
927 /// let opt_x = Some(&x);
928 /// assert_eq!(opt_x, Some(&12));
929 /// let cloned = opt_x.cloned();
930 /// assert_eq!(cloned, Some(12));
932 #[stable(feature = "rust1", since = "1.0.0")]
933 pub fn cloned(self) -> Option<T> {
934 self.map(|t| t.clone())
938 impl<T: Clone> Option<&mut T> {
939 /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
946 /// let opt_x = Some(&mut x);
947 /// assert_eq!(opt_x, Some(&mut 12));
948 /// let cloned = opt_x.cloned();
949 /// assert_eq!(cloned, Some(12));
951 #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
952 pub fn cloned(self) -> Option<T> {
953 self.map(|t| t.clone())
957 impl<T: Default> Option<T> {
958 /// Returns the contained value or a default
960 /// Consumes the `self` argument then, if [`Some`], returns the contained
961 /// value, otherwise if [`None`], returns the [default value] for that
966 /// Converts a string to an integer, turning poorly-formed strings
967 /// into 0 (the default value for integers). [`parse`] converts
968 /// a string to any other type that implements [`FromStr`], returning
969 /// [`None`] on error.
972 /// let good_year_from_input = "1909";
973 /// let bad_year_from_input = "190blarg";
974 /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
975 /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
977 /// assert_eq!(1909, good_year);
978 /// assert_eq!(0, bad_year);
981 /// [`Some`]: #variant.Some
982 /// [`None`]: #variant.None
983 /// [default value]: ../default/trait.Default.html#tymethod.default
984 /// [`parse`]: ../../std/primitive.str.html#method.parse
985 /// [`FromStr`]: ../../std/str/trait.FromStr.html
987 #[stable(feature = "rust1", since = "1.0.0")]
988 pub fn unwrap_or_default(self) -> T {
991 None => Default::default(),
996 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
997 impl<T: Deref> Option<T> {
998 /// Converts from `&Option<T>` to `Option<&T::Target>`.
1000 /// Leaves the original Option in-place, creating a new one with a reference
1001 /// to the original one, additionally coercing the contents via `Deref`.
1002 pub fn deref(&self) -> Option<&T::Target> {
1003 self.as_ref().map(|t| t.deref())
1007 impl<T, E> Option<Result<T, E>> {
1008 /// Transposes an `Option` of a `Result` into a `Result` of an `Option`.
1010 /// `None` will be mapped to `Ok(None)`.
1011 /// `Some(Ok(_))` and `Some(Err(_))` will be mapped to `Ok(Some(_))` and `Err(_)`.
1016 /// #[derive(Debug, Eq, PartialEq)]
1019 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1020 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1021 /// assert_eq!(x, y.transpose());
1024 #[stable(feature = "transpose_result", since = "1.33.0")]
1025 pub fn transpose(self) -> Result<Option<T>, E> {
1027 Some(Ok(x)) => Ok(Some(x)),
1028 Some(Err(e)) => Err(e),
1034 // This is a separate function to reduce the code size of .expect() itself.
1037 fn expect_failed(msg: &str) -> ! {
1041 /////////////////////////////////////////////////////////////////////////////
1042 // Trait implementations
1043 /////////////////////////////////////////////////////////////////////////////
1045 #[stable(feature = "rust1", since = "1.0.0")]
1046 impl<T> Default for Option<T> {
1047 /// Returns [`None`][Option::None].
1049 fn default() -> Option<T> { None }
1052 #[stable(feature = "rust1", since = "1.0.0")]
1053 impl<T> IntoIterator for Option<T> {
1055 type IntoIter = IntoIter<T>;
1057 /// Returns a consuming iterator over the possibly contained value.
1062 /// let x = Some("string");
1063 /// let v: Vec<&str> = x.into_iter().collect();
1064 /// assert_eq!(v, ["string"]);
1067 /// let v: Vec<&str> = x.into_iter().collect();
1068 /// assert!(v.is_empty());
1071 fn into_iter(self) -> IntoIter<T> {
1072 IntoIter { inner: Item { opt: self } }
1076 #[stable(since = "1.4.0", feature = "option_iter")]
1077 impl<'a, T> IntoIterator for &'a Option<T> {
1079 type IntoIter = Iter<'a, T>;
1081 fn into_iter(self) -> Iter<'a, T> {
1086 #[stable(since = "1.4.0", feature = "option_iter")]
1087 impl<'a, T> IntoIterator for &'a mut Option<T> {
1088 type Item = &'a mut T;
1089 type IntoIter = IterMut<'a, T>;
1091 fn into_iter(self) -> IterMut<'a, T> {
1096 #[stable(since = "1.12.0", feature = "option_from")]
1097 impl<T> From<T> for Option<T> {
1098 fn from(val: T) -> Option<T> {
1103 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1104 impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
1105 fn from(o: &'a Option<T>) -> Option<&'a T> {
1110 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1111 impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> {
1112 fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
1117 /////////////////////////////////////////////////////////////////////////////
1118 // The Option Iterators
1119 /////////////////////////////////////////////////////////////////////////////
1121 #[derive(Clone, Debug)]
1126 impl<A> Iterator for Item<A> {
1130 fn next(&mut self) -> Option<A> {
1135 fn size_hint(&self) -> (usize, Option<usize>) {
1137 Some(_) => (1, Some(1)),
1138 None => (0, Some(0)),
1143 impl<A> DoubleEndedIterator for Item<A> {
1145 fn next_back(&mut self) -> Option<A> {
1150 impl<A> ExactSizeIterator for Item<A> {}
1151 impl<A> FusedIterator for Item<A> {}
1152 unsafe impl<A> TrustedLen for Item<A> {}
1154 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
1156 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1158 /// This `struct` is created by the [`Option::iter`] function.
1160 /// [`Option`]: enum.Option.html
1161 /// [`Some`]: enum.Option.html#variant.Some
1162 /// [`Option::iter`]: enum.Option.html#method.iter
1163 #[stable(feature = "rust1", since = "1.0.0")]
1165 pub struct Iter<'a, A: 'a> { inner: Item<&'a A> }
1167 #[stable(feature = "rust1", since = "1.0.0")]
1168 impl<'a, A> Iterator for Iter<'a, A> {
1172 fn next(&mut self) -> Option<&'a A> { self.inner.next() }
1174 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1177 #[stable(feature = "rust1", since = "1.0.0")]
1178 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
1180 fn next_back(&mut self) -> Option<&'a A> { self.inner.next_back() }
1183 #[stable(feature = "rust1", since = "1.0.0")]
1184 impl<A> ExactSizeIterator for Iter<'_, A> {}
1186 #[stable(feature = "fused", since = "1.26.0")]
1187 impl<A> FusedIterator for Iter<'_, A> {}
1189 #[unstable(feature = "trusted_len", issue = "37572")]
1190 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1192 #[stable(feature = "rust1", since = "1.0.0")]
1193 impl<A> Clone for Iter<'_, A> {
1195 fn clone(&self) -> Self {
1196 Iter { inner: self.inner.clone() }
1200 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
1202 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1204 /// This `struct` is created by the [`Option::iter_mut`] function.
1206 /// [`Option`]: enum.Option.html
1207 /// [`Some`]: enum.Option.html#variant.Some
1208 /// [`Option::iter_mut`]: enum.Option.html#method.iter_mut
1209 #[stable(feature = "rust1", since = "1.0.0")]
1211 pub struct IterMut<'a, A: 'a> { inner: Item<&'a mut A> }
1213 #[stable(feature = "rust1", since = "1.0.0")]
1214 impl<'a, A> Iterator for IterMut<'a, A> {
1215 type Item = &'a mut A;
1218 fn next(&mut self) -> Option<&'a mut A> { self.inner.next() }
1220 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1223 #[stable(feature = "rust1", since = "1.0.0")]
1224 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
1226 fn next_back(&mut self) -> Option<&'a mut A> { self.inner.next_back() }
1229 #[stable(feature = "rust1", since = "1.0.0")]
1230 impl<A> ExactSizeIterator for IterMut<'_, A> {}
1232 #[stable(feature = "fused", since = "1.26.0")]
1233 impl<A> FusedIterator for IterMut<'_, A> {}
1234 #[unstable(feature = "trusted_len", issue = "37572")]
1235 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1237 /// An iterator over the value in [`Some`] variant of an [`Option`].
1239 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1241 /// This `struct` is created by the [`Option::into_iter`] function.
1243 /// [`Option`]: enum.Option.html
1244 /// [`Some`]: enum.Option.html#variant.Some
1245 /// [`Option::into_iter`]: enum.Option.html#method.into_iter
1246 #[derive(Clone, Debug)]
1247 #[stable(feature = "rust1", since = "1.0.0")]
1248 pub struct IntoIter<A> { inner: Item<A> }
1250 #[stable(feature = "rust1", since = "1.0.0")]
1251 impl<A> Iterator for IntoIter<A> {
1255 fn next(&mut self) -> Option<A> { self.inner.next() }
1257 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1260 #[stable(feature = "rust1", since = "1.0.0")]
1261 impl<A> DoubleEndedIterator for IntoIter<A> {
1263 fn next_back(&mut self) -> Option<A> { self.inner.next_back() }
1266 #[stable(feature = "rust1", since = "1.0.0")]
1267 impl<A> ExactSizeIterator for IntoIter<A> {}
1269 #[stable(feature = "fused", since = "1.26.0")]
1270 impl<A> FusedIterator for IntoIter<A> {}
1272 #[unstable(feature = "trusted_len", issue = "37572")]
1273 unsafe impl<A> TrustedLen for IntoIter<A> {}
1275 /////////////////////////////////////////////////////////////////////////////
1277 /////////////////////////////////////////////////////////////////////////////
1279 #[stable(feature = "rust1", since = "1.0.0")]
1280 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
1281 /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
1282 /// no further elements are taken, and the [`None`][Option::None] is
1283 /// returned. Should no [`None`][Option::None] occur, a container with the
1284 /// values of each [`Option`] is returned.
1288 /// Here is an example which increments every integer in a vector.
1289 /// `We use the checked variant of `add` that returns `None` when the
1290 /// calculation would result in an overflow.
1293 /// let items = vec![0_u16, 1, 2];
1295 /// let res: Option<Vec<u16>> = items
1297 /// .map(|x| x.checked_add(1))
1300 /// assert_eq!(res, Some(vec![1, 2, 3]));
1303 /// As you can see, this will return the expected, valid items.
1305 /// Here is another example that tries to subtract one from another list
1306 /// of integers, this time checking for underflow:
1309 /// let items = vec![2_u16, 1, 0];
1311 /// let res: Option<Vec<u16>> = items
1313 /// .map(|x| x.checked_sub(1))
1316 /// assert_eq!(res, None);
1319 /// Since the last element is zero, it would underflow. Thus, the resulting
1320 /// value is `None`.
1322 /// [`Iterator`]: ../iter/trait.Iterator.html
1324 fn from_iter<I: IntoIterator<Item=Option<A>>>(iter: I) -> Option<V> {
1325 // FIXME(#11084): This could be replaced with Iterator::scan when this
1326 // performance bug is closed.
1328 struct Adapter<Iter> {
1333 impl<T, Iter: Iterator<Item=Option<T>>> Iterator for Adapter<Iter> {
1337 fn next(&mut self) -> Option<T> {
1338 match self.iter.next() {
1339 Some(Some(value)) => Some(value),
1341 self.found_none = true;
1349 fn size_hint(&self) -> (usize, Option<usize>) {
1350 if self.found_none {
1353 let (_, upper) = self.iter.size_hint();
1359 let mut adapter = Adapter { iter: iter.into_iter(), found_none: false };
1360 let v: V = FromIterator::from_iter(adapter.by_ref());
1362 if adapter.found_none {
1370 /// The error type that results from applying the try operator (`?`) to a `None` value. If you wish
1371 /// to allow `x?` (where `x` is an `Option<T>`) to be converted into your error type, you can
1372 /// implement `impl From<NoneError>` for `YourErrorType`. In that case, `x?` within a function that
1373 /// returns `Result<_, YourErrorType>` will translate a `None` value into an `Err` result.
1374 #[unstable(feature = "try_trait", issue = "42327")]
1375 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
1376 pub struct NoneError;
1378 #[unstable(feature = "try_trait", issue = "42327")]
1379 impl<T> ops::Try for Option<T> {
1381 type Error = NoneError;
1384 fn into_result(self) -> Result<T, NoneError> {
1385 self.ok_or(NoneError)
1389 fn from_ok(v: T) -> Self {
1394 fn from_error(_: NoneError) -> Self {