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, the
54 //! `check_optional` function first 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"),
75 //! Rust guarantees to optimize the following types `T` such that
76 //! [`Option<T>`] has the same size as `T`:
81 //! * `fn`, `extern "C" fn`
82 //! * [`num::NonZero*`]
83 //! * [`ptr::NonNull<U>`]
84 //! * `#[repr(transparent)]` struct around one of the types in this list.
86 //! This is called the "null pointer optimization" or NPO.
88 //! It is further guaranteed that, for the cases above, one can
89 //! [`mem::transmute`] from all valid values of `T` to `Option<T>` and
90 //! from `Some::<T>(_)` to `T` (but transmuting `None::<T>` to `T`
91 //! is undefined behaviour).
95 //! In addition to working with pattern matching, [`Option`] provides a wide
96 //! variety of different methods.
98 //! ## Querying the variant
100 //! The [`is_some`] and [`is_none`] methods return [`true`] if the [`Option`]
101 //! is [`Some`] or [`None`], respectively.
103 //! [`is_some`]: Option::is_some
104 //! [`is_none`]: Option::is_none
106 //! ## Adapters for working with references
108 //! * [`as_ref`] converts from `&Option<T>` to `Option<&T>`
109 //! * [`as_mut`] converts from `&mut Option<T>` to `Option<&mut T>`
110 //! * [`as_deref`] converts from `&Option<T>` to `Option<&T::Target>`
111 //! * [`as_deref_mut`] converts from `&mut Option<T>` to `Option<&mut T::Target>`
112 //! * [`as_pin_ref`] converts from [`&Pin`]`<Option<T>>` to `Option<`[`Pin`]`<&T>>`
113 //! * [`as_pin_mut`] converts from [`&mut Pin`]`<Option<T>>` to `Option<`[`Pin`]`<&mut T>>`
115 //! [`&mut Pin`]: crate::pin::Pin
116 //! [`&Pin`]: crate::pin::Pin
117 //! [`as_deref`]: Option::as_deref
118 //! [`as_deref_mut`]: Option::as_deref_mut
119 //! [`as_mut`]: Option::as_mut
120 //! [`as_pin_ref`]: Option::as_pin_ref
121 //! [`as_pin_mut`]: Option::as_pin_mut
122 //! [`as_ref`]: Option::as_ref
123 //! [`Pin`]: crate::pin::Pin
125 //! ## Extracting the contained value
127 //! These methods extract the contained value in an [`Option`] when it is
128 //! the [`Some`] variant. If the [`Option`] is [`None`]:
130 //! * [`expect`] panics with a provided custom message
131 //! * [`unwrap`] panics with a generic message
132 //! * [`unwrap_or`] returns the provided default value
133 //! * [`unwrap_or_default`] returns the default value of the type `T`
134 //! (which must implement the [`Default`] trait)
135 //! * [`unwrap_or_else`] evaluates a provided function
137 //! [`Default`]: crate::default::Default
138 //! [`expect`]: Option::expect
139 //! [`unwrap`]: Option::unwrap
140 //! [`unwrap_or`]: Option::unwrap_or
141 //! [`unwrap_or_default`]: Option::unwrap_or_default
142 //! [`unwrap_or_else`]: Option::unwrap_or_else
144 //! ## Transforming contained values
146 //! * [`flatten`] removes one level of nesting from an
147 //! [`Option<Option<T>>`]
148 //! * [`map`] transforms [`Some<T>`] to [`Some<U>`] using the provided
150 //! * [`map_or`] transforms [`Some<T>`] to a value of `U` using the
151 //! provided function, or transforms [`None`] to a provided default value
153 //! * [`map_or_else`] transforms [`Some<T>`] to a value of `U` using the
154 //! provided function, or transforms [`None`] to a value of `U` using
155 //! another provided function
156 //! * [`ok_or`] transforms [`Some(v)`] to [`Ok(v)`], and [`None`] to
157 //! [`Err(err)`] using the provided default `err` value
158 //! * [`ok_or_else`] transforms [`Some(v)`] to [`Ok(v)`], and [`None`] to
159 //! a value of [`Err<E>`] using the provided function
160 //! * [`transpose`] transposes an [`Option`] of a [`Result`] into a
161 //! [`Result`] of an [`Option`]
163 //! [`Err(err)`]: Err
164 //! [`flatten`]: Option::flatten
165 //! [`map`]: Option::map
166 //! [`map_or`]: Option::map_or
167 //! [`map_or_else`]: Option::map_or_else
169 //! [`ok_or`]: Option::ok_or
170 //! [`ok_or_else`]: Option::ok_or_else
171 //! [`Some(v)`]: Some
172 //! [`transpose`]: Option::transpose
174 //! ## Boolean operators
176 //! These methods treat the [`Option`] as a boolean value, where [`Some`]
177 //! acts like [`true`] and [`None`] acts like [`false`]. There are two
178 //! categories of these methods: ones that take an [`Option`] as input, and
179 //! ones that take a function as input (to be lazily evaluated).
181 //! The [`and`], [`or`], and [`xor`] methods take another [`Option`] as
182 //! input, and produce an [`Option`] as output. Only the [`and`] method can
183 //! produce an [`Option<U>`] value having a different inner type `U` than
186 //! | method | self | input | output |
187 //! |---------|-----------|-----------|-----------|
188 //! | [`and`] | `None` | (ignored) | `None` |
189 //! | [`and`] | `Some(x)` | `None` | `None` |
190 //! | [`and`] | `Some(x)` | `Some(y)` | `Some(y)` |
191 //! | [`or`] | `None` | `None` | `None` |
192 //! | [`or`] | `None` | `Some(y)` | `Some(y)` |
193 //! | [`or`] | `Some(x)` | (ignored) | `Some(x)` |
194 //! | [`xor`] | `None` | `None` | `None` |
195 //! | [`xor`] | `None` | `Some(y)` | `Some(y)` |
196 //! | [`xor`] | `Some(x)` | `None` | `Some(x)` |
197 //! | [`xor`] | `Some(x)` | `Some(y)` | `None` |
199 //! The [`and_then`], [`filter`], and [`or_else`] methods take a function
200 //! as input, and only evaluate the function when they need to produce a
201 //! new value. [`and_then`] and [`or_else`] take a function that produces
202 //! another [`Option`] value, while [`filter`] takes a predicate that is
203 //! used to decide whether to pass the [`Some`] value through. Only the
204 //! [`and_then`] method can produce an [`Option<U>`] value having a
205 //! different inner type `U` than [`Option<T>`].
207 //! | method | self | function input | function result | output |
208 //! |--------------|-----------|----------------|-----------------|-----------|
209 //! | [`and_then`] | `None` | (not provided) | (not evaluated) | `None` |
210 //! | [`and_then`] | `Some(x)` | `x` | `None` | `None` |
211 //! | [`and_then`] | `Some(x)` | `x` | `Some(y)` | `Some(y)` |
212 //! | [`filter`] | `None` | (not provided) | (not evaluated) | `None` |
213 //! | [`filter`] | `Some(x)` | `x` | `false` | `None` |
214 //! | [`filter`] | `Some(x)` | `x` | `true` | `Some(x)` |
215 //! | [`or_else`] | `None` | (not provided) | `None` | `None` |
216 //! | [`or_else`] | `None` | (not provided) | `Some(y)` | `Some(y)` |
217 //! | [`or_else`] | `Some(x)` | (not provided) | (not evaluated) | `Some(x)` |
219 //! [`and`]: Option::and
220 //! [`and_then`]: Option::and_then
221 //! [`filter`]: Option::filter
222 //! [`or`]: Option::or
223 //! [`or_else`]: Option::or_else
224 //! [`xor`]: Option::xor
228 //! An [`Option`] can be iterated over. This can be helpful if you need an
229 //! iterator that is conditionally empty. The iterator will either produce
230 //! a single value (when the [`Option`] is [`Some`]), or produce no values
231 //! (when the [`Option`] is [`None`]). For example, [`into_iter`] acts like
232 //! [`once(v)`] if the [`Option`] is [`Some(v)`], and like [`empty()`] if
233 //! the [`Option`] is [`None`].
235 //! Iterators over [`Option`] come in three types:
237 //! * [`into_iter`] consumes the [`Option`] and produces the contained
239 //! * [`iter`] produces an immutable reference of type `&T` to the
241 //! * [`iter_mut`] produces a mutable reference of type `&mut T` to the
244 //! [`Option`] implements the [`FromIterator`] trait, which allows an
245 //! iterator over [`Option`] values to be collected into an [`Option`] of a
246 //! collection of each contained value of the original [`Option`] values,
247 //! or [`None`] if any of the elements was [`None`].
249 //! [`empty()`]: crate::iter::empty
250 //! [`FromIterator`]: Option#impl-FromIterator%3COption%3CA%3E%3E
251 //! [`into_iter`]: Option::into_iter
252 //! [`iter`]: Option::iter
253 //! [`iter_mut`]: Option::iter_mut
254 //! [`once(v)`]: crate::iter::once
255 //! [`Some(v)`]: Some
257 //! An iterator over [`Option`] can be useful when chaining iterators:
260 //! let yep = Some(42);
262 //! let nums: Vec<i32> = (0..4).chain(yep.into_iter()).chain(4..8).collect();
263 //! assert_eq!(nums, [0, 1, 2, 3, 42, 4, 5, 6, 7]);
264 //! let nums: Vec<i32> = (0..4).chain(nope.into_iter()).chain(4..8).collect();
265 //! assert_eq!(nums, [0, 1, 2, 3, 4, 5, 6, 7]);
268 //! One reason to chain iterators in this way is that a function returning
269 //! `impl Iterator` must have all possible return values be of the same
270 //! concrete type. Chaining an iterated [`Option`] can help with that.
273 //! let yep = Some(42);
276 //! fn make_iter(opt: Option<i32>) -> impl Iterator<Item = i32> {
277 //! (0..4).chain(opt.into_iter()).chain(4..8)
279 //! println!("{:?}", make_iter(yep).collect::<Vec<_>>());
280 //! println!("{:?}", make_iter(nope).collect::<Vec<_>>());
283 //! If we try to do the same thing, but using pattern matching, we can't
284 //! return `impl Iterator` anymore because the concrete types of the return
287 //! ```compile_fail,E0308
288 //! # use std::iter::{empty, once};
289 //! // This won't compile because all possible returns from the function
290 //! // must have the same concrete type.
291 //! fn make_iter(opt: Option<i32>) -> impl Iterator<Item = i32> {
293 //! Some(x) => return (0..4).chain(once(x)).chain(4..8),
294 //! None => return (0..4).chain(empty()).chain(4..8)
299 //! ## Modifying an [`Option`] in-place
301 //! These methods return a mutable reference to the contained value of a
304 //! * [`insert`] inserts a value, dropping any old contents
305 //! * [`get_or_insert`] gets the current value, inserting a provided
306 //! default value if it is [`None`]
307 //! * [`get_or_insert_default`] gets the current value, inserting the
308 //! default value of type `T` if it is [`None`]
309 //! * [`get_or_insert_with`] gets the current value, inserting a default
310 //! computed by the provided function if it is [`None`]
312 //! [`insert`]: Option::insert
313 //! [`get_or_insert`]: Option::get_or_insert
314 //! [`get_or_insert_default`]: Option::get_or_insert_default
315 //! [`get_or_insert_with`]: Option::get_or_insert_with
317 //! These methods transfer ownership of the [`Option`].
319 //! * [`take`] takes ownership of the [`Option`], including any contained
320 //! value, replacing it with [`None`]
321 //! * [`replace`] takes ownership of the [`Option`], including any
322 //! contained value, replacing it with a [`Some`] containing the provided
325 //! [`take`]: Option::take
326 //! [`replace`]: Option::replace
330 //! Basic pattern matching on [`Option`]:
333 //! let msg = Some("howdy");
335 //! // Take a reference to the contained string
336 //! if let Some(m) = &msg {
337 //! println!("{}", *m);
340 //! // Remove the contained string, destroying the Option
341 //! let unwrapped_msg = msg.unwrap_or("default message");
344 //! Initialize a result to [`None`] before a loop:
347 //! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) }
349 //! // A list of data to search through.
350 //! let all_the_big_things = [
351 //! Kingdom::Plant(250, "redwood"),
352 //! Kingdom::Plant(230, "noble fir"),
353 //! Kingdom::Plant(229, "sugar pine"),
354 //! Kingdom::Animal(25, "blue whale"),
355 //! Kingdom::Animal(19, "fin whale"),
356 //! Kingdom::Animal(15, "north pacific right whale"),
359 //! // We're going to search for the name of the biggest animal,
360 //! // but to start with we've just got `None`.
361 //! let mut name_of_biggest_animal = None;
362 //! let mut size_of_biggest_animal = 0;
363 //! for big_thing in &all_the_big_things {
364 //! match *big_thing {
365 //! Kingdom::Animal(size, name) if size > size_of_biggest_animal => {
366 //! // Now we've found the name of some big animal
367 //! size_of_biggest_animal = size;
368 //! name_of_biggest_animal = Some(name);
370 //! Kingdom::Animal(..) | Kingdom::Plant(..) => ()
374 //! match name_of_biggest_animal {
375 //! Some(name) => println!("the biggest animal is {}", name),
376 //! None => println!("there are no animals :("),
380 //! [`Box<T>`]: ../../std/boxed/struct.Box.html
381 //! [`Box<U>`]: ../../std/boxed/struct.Box.html
382 //! [`num::NonZero*`]: crate::num
383 //! [`ptr::NonNull<U>`]: crate::ptr::NonNull
385 #![stable(feature = "rust1", since = "1.0.0")]
387 use crate::iter::{FromIterator, FusedIterator, TrustedLen};
391 ops::{self, ControlFlow, Deref, DerefMut},
394 /// The `Option` type. See [the module level documentation](self) for more.
395 #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
396 #[rustc_diagnostic_item = "option_type"]
397 #[stable(feature = "rust1", since = "1.0.0")]
401 #[stable(feature = "rust1", since = "1.0.0")]
405 #[stable(feature = "rust1", since = "1.0.0")]
406 Some(#[stable(feature = "rust1", since = "1.0.0")] T),
409 /////////////////////////////////////////////////////////////////////////////
410 // Type implementation
411 /////////////////////////////////////////////////////////////////////////////
414 /////////////////////////////////////////////////////////////////////////
415 // Querying the contained values
416 /////////////////////////////////////////////////////////////////////////
418 /// Returns `true` if the option is a [`Some`] value.
423 /// let x: Option<u32> = Some(2);
424 /// assert_eq!(x.is_some(), true);
426 /// let x: Option<u32> = None;
427 /// assert_eq!(x.is_some(), false);
429 #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"]
431 #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
432 #[stable(feature = "rust1", since = "1.0.0")]
433 pub const fn is_some(&self) -> bool {
434 matches!(*self, Some(_))
437 /// Returns `true` if the option is a [`None`] value.
442 /// let x: Option<u32> = Some(2);
443 /// assert_eq!(x.is_none(), false);
445 /// let x: Option<u32> = None;
446 /// assert_eq!(x.is_none(), true);
448 #[must_use = "if you intended to assert that this doesn't have a value, consider \
449 `.and_then(|_| panic!(\"`Option` had a value when expected `None`\"))` instead"]
451 #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
452 #[stable(feature = "rust1", since = "1.0.0")]
453 pub const fn is_none(&self) -> bool {
457 /// Returns `true` if the option is a [`Some`] value containing the given value.
462 /// #![feature(option_result_contains)]
464 /// let x: Option<u32> = Some(2);
465 /// assert_eq!(x.contains(&2), true);
467 /// let x: Option<u32> = Some(3);
468 /// assert_eq!(x.contains(&2), false);
470 /// let x: Option<u32> = None;
471 /// assert_eq!(x.contains(&2), false);
475 #[unstable(feature = "option_result_contains", issue = "62358")]
476 pub fn contains<U>(&self, x: &U) -> bool
486 /////////////////////////////////////////////////////////////////////////
487 // Adapter for working with references
488 /////////////////////////////////////////////////////////////////////////
490 /// Converts from `&Option<T>` to `Option<&T>`.
494 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
495 /// The [`map`] method takes the `self` argument by value, consuming the original,
496 /// so this technique uses `as_ref` to first take an `Option` to a reference
497 /// to the value inside the original.
499 /// [`map`]: Option::map
500 /// [`String`]: ../../std/string/struct.String.html
503 /// let text: Option<String> = Some("Hello, world!".to_string());
504 /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
505 /// // then consume *that* with `map`, leaving `text` on the stack.
506 /// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
507 /// println!("still can print text: {:?}", text);
510 #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
511 #[stable(feature = "rust1", since = "1.0.0")]
512 pub const fn as_ref(&self) -> Option<&T> {
514 Some(ref x) => Some(x),
519 /// Converts from `&mut Option<T>` to `Option<&mut T>`.
524 /// let mut x = Some(2);
525 /// match x.as_mut() {
526 /// Some(v) => *v = 42,
529 /// assert_eq!(x, Some(42));
532 #[stable(feature = "rust1", since = "1.0.0")]
533 pub fn as_mut(&mut self) -> Option<&mut T> {
535 Some(ref mut x) => Some(x),
540 /// Converts from [`Pin`]`<&Option<T>>` to `Option<`[`Pin`]`<&T>>`.
542 #[stable(feature = "pin", since = "1.33.0")]
543 pub fn as_pin_ref(self: Pin<&Self>) -> Option<Pin<&T>> {
544 // SAFETY: `x` is guaranteed to be pinned because it comes from `self`
546 unsafe { Pin::get_ref(self).as_ref().map(|x| Pin::new_unchecked(x)) }
549 /// Converts from [`Pin`]`<&mut Option<T>>` to `Option<`[`Pin`]`<&mut T>>`.
551 #[stable(feature = "pin", since = "1.33.0")]
552 pub fn as_pin_mut(self: Pin<&mut Self>) -> Option<Pin<&mut T>> {
553 // SAFETY: `get_unchecked_mut` is never used to move the `Option` inside `self`.
554 // `x` is guaranteed to be pinned because it comes from `self` which is pinned.
555 unsafe { Pin::get_unchecked_mut(self).as_mut().map(|x| Pin::new_unchecked(x)) }
558 /////////////////////////////////////////////////////////////////////////
559 // Getting to contained values
560 /////////////////////////////////////////////////////////////////////////
562 /// Returns the contained [`Some`] value, consuming the `self` value.
566 /// Panics if the value is a [`None`] with a custom panic message provided by
572 /// let x = Some("value");
573 /// assert_eq!(x.expect("fruits are healthy"), "value");
577 /// let x: Option<&str> = None;
578 /// x.expect("fruits are healthy"); // panics with `fruits are healthy`
582 #[stable(feature = "rust1", since = "1.0.0")]
583 pub fn expect(self, msg: &str) -> T {
586 None => expect_failed(msg),
590 /// Returns the contained [`Some`] value, consuming the `self` value.
592 /// Because this function may panic, its use is generally discouraged.
593 /// Instead, prefer to use pattern matching and handle the [`None`]
594 /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
595 /// [`unwrap_or_default`].
597 /// [`unwrap_or`]: Option::unwrap_or
598 /// [`unwrap_or_else`]: Option::unwrap_or_else
599 /// [`unwrap_or_default`]: Option::unwrap_or_default
603 /// Panics if the self value equals [`None`].
608 /// let x = Some("air");
609 /// assert_eq!(x.unwrap(), "air");
613 /// let x: Option<&str> = None;
614 /// assert_eq!(x.unwrap(), "air"); // fails
618 #[stable(feature = "rust1", since = "1.0.0")]
619 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
620 pub const fn unwrap(self) -> T {
623 None => panic!("called `Option::unwrap()` on a `None` value"),
627 /// Returns the contained [`Some`] value or a provided default.
629 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
630 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
631 /// which is lazily evaluated.
633 /// [`unwrap_or_else`]: Option::unwrap_or_else
638 /// assert_eq!(Some("car").unwrap_or("bike"), "car");
639 /// assert_eq!(None.unwrap_or("bike"), "bike");
642 #[stable(feature = "rust1", since = "1.0.0")]
643 pub fn unwrap_or(self, default: T) -> T {
650 /// Returns the contained [`Some`] value or computes it from a closure.
656 /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
657 /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
660 #[stable(feature = "rust1", since = "1.0.0")]
661 pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
668 /// Returns the contained [`Some`] value, consuming the `self` value,
669 /// without checking that the value is not [`None`].
673 /// Calling this method on [`None`] is *[undefined behavior]*.
675 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
680 /// #![feature(option_result_unwrap_unchecked)]
681 /// let x = Some("air");
682 /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air");
686 /// #![feature(option_result_unwrap_unchecked)]
687 /// let x: Option<&str> = None;
688 /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air"); // Undefined behavior!
692 #[unstable(feature = "option_result_unwrap_unchecked", reason = "newly added", issue = "81383")]
693 pub unsafe fn unwrap_unchecked(self) -> T {
694 debug_assert!(self.is_some());
697 // SAFETY: the safety contract must be upheld by the caller.
698 None => unsafe { hint::unreachable_unchecked() },
702 /////////////////////////////////////////////////////////////////////////
703 // Transforming contained values
704 /////////////////////////////////////////////////////////////////////////
706 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
710 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, consuming the original:
712 /// [`String`]: ../../std/string/struct.String.html
714 /// let maybe_some_string = Some(String::from("Hello, World!"));
715 /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
716 /// let maybe_some_len = maybe_some_string.map(|s| s.len());
718 /// assert_eq!(maybe_some_len, Some(13));
721 #[stable(feature = "rust1", since = "1.0.0")]
722 pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
724 Some(x) => Some(f(x)),
729 /// Returns the provided default result (if none),
730 /// or applies a function to the contained value (if any).
732 /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
733 /// the result of a function call, it is recommended to use [`map_or_else`],
734 /// which is lazily evaluated.
736 /// [`map_or_else`]: Option::map_or_else
741 /// let x = Some("foo");
742 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
744 /// let x: Option<&str> = None;
745 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
748 #[stable(feature = "rust1", since = "1.0.0")]
749 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
756 /// Computes a default function result (if none), or
757 /// applies a different function to the contained value (if any).
764 /// let x = Some("foo");
765 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
767 /// let x: Option<&str> = None;
768 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
771 #[stable(feature = "rust1", since = "1.0.0")]
772 pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
779 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
780 /// [`Ok(v)`] and [`None`] to [`Err(err)`].
782 /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
783 /// result of a function call, it is recommended to use [`ok_or_else`], which is
784 /// lazily evaluated.
787 /// [`Err(err)`]: Err
788 /// [`Some(v)`]: Some
789 /// [`ok_or_else`]: Option::ok_or_else
794 /// let x = Some("foo");
795 /// assert_eq!(x.ok_or(0), Ok("foo"));
797 /// let x: Option<&str> = None;
798 /// assert_eq!(x.ok_or(0), Err(0));
801 #[stable(feature = "rust1", since = "1.0.0")]
802 pub fn ok_or<E>(self, err: E) -> Result<T, E> {
809 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
810 /// [`Ok(v)`] and [`None`] to [`Err(err())`].
813 /// [`Err(err())`]: Err
814 /// [`Some(v)`]: Some
819 /// let x = Some("foo");
820 /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
822 /// let x: Option<&str> = None;
823 /// assert_eq!(x.ok_or_else(|| 0), Err(0));
826 #[stable(feature = "rust1", since = "1.0.0")]
827 pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
834 /////////////////////////////////////////////////////////////////////////
835 // Iterator constructors
836 /////////////////////////////////////////////////////////////////////////
838 /// Returns an iterator over the possibly contained value.
844 /// assert_eq!(x.iter().next(), Some(&4));
846 /// let x: Option<u32> = None;
847 /// assert_eq!(x.iter().next(), None);
850 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
851 #[stable(feature = "rust1", since = "1.0.0")]
852 pub const fn iter(&self) -> Iter<'_, T> {
853 Iter { inner: Item { opt: self.as_ref() } }
856 /// Returns a mutable iterator over the possibly contained value.
861 /// let mut x = Some(4);
862 /// match x.iter_mut().next() {
863 /// Some(v) => *v = 42,
866 /// assert_eq!(x, Some(42));
868 /// let mut x: Option<u32> = None;
869 /// assert_eq!(x.iter_mut().next(), None);
872 #[stable(feature = "rust1", since = "1.0.0")]
873 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
874 IterMut { inner: Item { opt: self.as_mut() } }
877 /////////////////////////////////////////////////////////////////////////
878 // Boolean operations on the values, eager and lazy
879 /////////////////////////////////////////////////////////////////////////
881 /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
887 /// let y: Option<&str> = None;
888 /// assert_eq!(x.and(y), None);
890 /// let x: Option<u32> = None;
891 /// let y = Some("foo");
892 /// assert_eq!(x.and(y), None);
895 /// let y = Some("foo");
896 /// assert_eq!(x.and(y), Some("foo"));
898 /// let x: Option<u32> = None;
899 /// let y: Option<&str> = None;
900 /// assert_eq!(x.and(y), None);
903 #[stable(feature = "rust1", since = "1.0.0")]
904 pub fn and<U>(self, optb: Option<U>) -> Option<U> {
911 /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
912 /// wrapped value and returns the result.
914 /// Some languages call this operation flatmap.
919 /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
920 /// fn nope(_: u32) -> Option<u32> { None }
922 /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
923 /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
924 /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
925 /// assert_eq!(None.and_then(sq).and_then(sq), None);
928 #[stable(feature = "rust1", since = "1.0.0")]
929 pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> {
936 /// Returns [`None`] if the option is [`None`], otherwise calls `predicate`
937 /// with the wrapped value and returns:
939 /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped
941 /// - [`None`] if `predicate` returns `false`.
943 /// This function works similar to [`Iterator::filter()`]. You can imagine
944 /// the `Option<T>` being an iterator over one or zero elements. `filter()`
945 /// lets you decide which elements to keep.
950 /// fn is_even(n: &i32) -> bool {
954 /// assert_eq!(None.filter(is_even), None);
955 /// assert_eq!(Some(3).filter(is_even), None);
956 /// assert_eq!(Some(4).filter(is_even), Some(4));
959 /// [`Some(t)`]: Some
961 #[stable(feature = "option_filter", since = "1.27.0")]
962 pub fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Self {
963 if let Some(x) = self {
971 /// Returns the option if it contains a value, otherwise returns `optb`.
973 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
974 /// result of a function call, it is recommended to use [`or_else`], which is
975 /// lazily evaluated.
977 /// [`or_else`]: Option::or_else
984 /// assert_eq!(x.or(y), Some(2));
987 /// let y = Some(100);
988 /// assert_eq!(x.or(y), Some(100));
991 /// let y = Some(100);
992 /// assert_eq!(x.or(y), Some(2));
994 /// let x: Option<u32> = None;
996 /// assert_eq!(x.or(y), None);
999 #[stable(feature = "rust1", since = "1.0.0")]
1000 pub fn or(self, optb: Option<T>) -> Option<T> {
1007 /// Returns the option if it contains a value, otherwise calls `f` and
1008 /// returns the result.
1013 /// fn nobody() -> Option<&'static str> { None }
1014 /// fn vikings() -> Option<&'static str> { Some("vikings") }
1016 /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
1017 /// assert_eq!(None.or_else(vikings), Some("vikings"));
1018 /// assert_eq!(None.or_else(nobody), None);
1021 #[stable(feature = "rust1", since = "1.0.0")]
1022 pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> {
1029 /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`].
1034 /// let x = Some(2);
1035 /// let y: Option<u32> = None;
1036 /// assert_eq!(x.xor(y), Some(2));
1038 /// let x: Option<u32> = None;
1039 /// let y = Some(2);
1040 /// assert_eq!(x.xor(y), Some(2));
1042 /// let x = Some(2);
1043 /// let y = Some(2);
1044 /// assert_eq!(x.xor(y), None);
1046 /// let x: Option<u32> = None;
1047 /// let y: Option<u32> = None;
1048 /// assert_eq!(x.xor(y), None);
1051 #[stable(feature = "option_xor", since = "1.37.0")]
1052 pub fn xor(self, optb: Option<T>) -> Option<T> {
1053 match (self, optb) {
1054 (Some(a), None) => Some(a),
1055 (None, Some(b)) => Some(b),
1060 /////////////////////////////////////////////////////////////////////////
1061 // Entry-like operations to insert a value and return a reference
1062 /////////////////////////////////////////////////////////////////////////
1064 /// Inserts `value` into the option then returns a mutable reference to it.
1066 /// If the option already contains a value, the old value is dropped.
1068 /// See also [`Option::get_or_insert`], which doesn't update the value if
1069 /// the option already contains [`Some`].
1074 /// let mut opt = None;
1075 /// let val = opt.insert(1);
1076 /// assert_eq!(*val, 1);
1077 /// assert_eq!(opt.unwrap(), 1);
1078 /// let val = opt.insert(2);
1079 /// assert_eq!(*val, 2);
1081 /// assert_eq!(opt.unwrap(), 3);
1084 #[stable(feature = "option_insert", since = "1.53.0")]
1085 pub fn insert(&mut self, value: T) -> &mut T {
1086 *self = Some(value);
1090 // SAFETY: the code above just filled the option
1091 None => unsafe { hint::unreachable_unchecked() },
1095 /// Inserts `value` into the option if it is [`None`], then
1096 /// returns a mutable reference to the contained value.
1098 /// See also [`Option::insert`], which updates the value even if
1099 /// the option already contains [`Some`].
1104 /// let mut x = None;
1107 /// let y: &mut u32 = x.get_or_insert(5);
1108 /// assert_eq!(y, &5);
1113 /// assert_eq!(x, Some(7));
1116 #[stable(feature = "option_entry", since = "1.20.0")]
1117 pub fn get_or_insert(&mut self, value: T) -> &mut T {
1118 self.get_or_insert_with(|| value)
1121 /// Inserts the default value into the option if it is [`None`], then
1122 /// returns a mutable reference to the contained value.
1127 /// #![feature(option_get_or_insert_default)]
1129 /// let mut x = None;
1132 /// let y: &mut u32 = x.get_or_insert_default();
1133 /// assert_eq!(y, &0);
1138 /// assert_eq!(x, Some(7));
1141 #[unstable(feature = "option_get_or_insert_default", issue = "82901")]
1142 pub fn get_or_insert_default(&mut self) -> &mut T
1146 self.get_or_insert_with(Default::default)
1149 /// Inserts a value computed from `f` into the option if it is [`None`],
1150 /// then returns a mutable reference to the contained value.
1155 /// let mut x = None;
1158 /// let y: &mut u32 = x.get_or_insert_with(|| 5);
1159 /// assert_eq!(y, &5);
1164 /// assert_eq!(x, Some(7));
1167 #[stable(feature = "option_entry", since = "1.20.0")]
1168 pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
1169 if let None = *self {
1175 // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
1176 // variant in the code above.
1177 None => unsafe { hint::unreachable_unchecked() },
1181 /////////////////////////////////////////////////////////////////////////
1183 /////////////////////////////////////////////////////////////////////////
1185 /// Takes the value out of the option, leaving a [`None`] in its place.
1190 /// let mut x = Some(2);
1191 /// let y = x.take();
1192 /// assert_eq!(x, None);
1193 /// assert_eq!(y, Some(2));
1195 /// let mut x: Option<u32> = None;
1196 /// let y = x.take();
1197 /// assert_eq!(x, None);
1198 /// assert_eq!(y, None);
1201 #[stable(feature = "rust1", since = "1.0.0")]
1202 pub fn take(&mut self) -> Option<T> {
1206 /// Replaces the actual value in the option by the value given in parameter,
1207 /// returning the old value if present,
1208 /// leaving a [`Some`] in its place without deinitializing either one.
1213 /// let mut x = Some(2);
1214 /// let old = x.replace(5);
1215 /// assert_eq!(x, Some(5));
1216 /// assert_eq!(old, Some(2));
1218 /// let mut x = None;
1219 /// let old = x.replace(3);
1220 /// assert_eq!(x, Some(3));
1221 /// assert_eq!(old, None);
1224 #[stable(feature = "option_replace", since = "1.31.0")]
1225 pub fn replace(&mut self, value: T) -> Option<T> {
1226 mem::replace(self, Some(value))
1229 /// Zips `self` with another `Option`.
1231 /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some((s, o))`.
1232 /// Otherwise, `None` is returned.
1237 /// let x = Some(1);
1238 /// let y = Some("hi");
1239 /// let z = None::<u8>;
1241 /// assert_eq!(x.zip(y), Some((1, "hi")));
1242 /// assert_eq!(x.zip(z), None);
1244 #[stable(feature = "option_zip_option", since = "1.46.0")]
1245 pub fn zip<U>(self, other: Option<U>) -> Option<(T, U)> {
1246 match (self, other) {
1247 (Some(a), Some(b)) => Some((a, b)),
1252 /// Zips `self` and another `Option` with function `f`.
1254 /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
1255 /// Otherwise, `None` is returned.
1260 /// #![feature(option_zip)]
1262 /// #[derive(Debug, PartialEq)]
1269 /// fn new(x: f64, y: f64) -> Self {
1274 /// let x = Some(17.5);
1275 /// let y = Some(42.7);
1277 /// assert_eq!(x.zip_with(y, Point::new), Some(Point { x: 17.5, y: 42.7 }));
1278 /// assert_eq!(x.zip_with(None, Point::new), None);
1280 #[unstable(feature = "option_zip", issue = "70086")]
1281 pub fn zip_with<U, F, R>(self, other: Option<U>, f: F) -> Option<R>
1283 F: FnOnce(T, U) -> R,
1285 Some(f(self?, other?))
1289 impl<T: Copy> Option<&T> {
1290 /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
1297 /// let opt_x = Some(&x);
1298 /// assert_eq!(opt_x, Some(&12));
1299 /// let copied = opt_x.copied();
1300 /// assert_eq!(copied, Some(12));
1302 #[stable(feature = "copied", since = "1.35.0")]
1303 pub fn copied(self) -> Option<T> {
1308 impl<T: Copy> Option<&mut T> {
1309 /// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the
1316 /// let opt_x = Some(&mut x);
1317 /// assert_eq!(opt_x, Some(&mut 12));
1318 /// let copied = opt_x.copied();
1319 /// assert_eq!(copied, Some(12));
1321 #[stable(feature = "copied", since = "1.35.0")]
1322 pub fn copied(self) -> Option<T> {
1323 self.map(|&mut t| t)
1327 impl<T: Clone> Option<&T> {
1328 /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
1335 /// let opt_x = Some(&x);
1336 /// assert_eq!(opt_x, Some(&12));
1337 /// let cloned = opt_x.cloned();
1338 /// assert_eq!(cloned, Some(12));
1340 #[stable(feature = "rust1", since = "1.0.0")]
1341 pub fn cloned(self) -> Option<T> {
1342 self.map(|t| t.clone())
1346 impl<T: Clone> Option<&mut T> {
1347 /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
1354 /// let opt_x = Some(&mut x);
1355 /// assert_eq!(opt_x, Some(&mut 12));
1356 /// let cloned = opt_x.cloned();
1357 /// assert_eq!(cloned, Some(12));
1359 #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
1360 pub fn cloned(self) -> Option<T> {
1361 self.map(|t| t.clone())
1365 impl<T: Default> Option<T> {
1366 /// Returns the contained [`Some`] value or a default
1368 /// Consumes the `self` argument then, if [`Some`], returns the contained
1369 /// value, otherwise if [`None`], returns the [default value] for that
1374 /// Converts a string to an integer, turning poorly-formed strings
1375 /// into 0 (the default value for integers). [`parse`] converts
1376 /// a string to any other type that implements [`FromStr`], returning
1377 /// [`None`] on error.
1380 /// let good_year_from_input = "1909";
1381 /// let bad_year_from_input = "190blarg";
1382 /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
1383 /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
1385 /// assert_eq!(1909, good_year);
1386 /// assert_eq!(0, bad_year);
1389 /// [default value]: Default::default
1390 /// [`parse`]: str::parse
1391 /// [`FromStr`]: crate::str::FromStr
1393 #[stable(feature = "rust1", since = "1.0.0")]
1394 pub fn unwrap_or_default(self) -> T {
1397 None => Default::default(),
1402 impl<T: Deref> Option<T> {
1403 /// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.
1405 /// Leaves the original Option in-place, creating a new one with a reference
1406 /// to the original one, additionally coercing the contents via [`Deref`].
1411 /// let x: Option<String> = Some("hey".to_owned());
1412 /// assert_eq!(x.as_deref(), Some("hey"));
1414 /// let x: Option<String> = None;
1415 /// assert_eq!(x.as_deref(), None);
1417 #[stable(feature = "option_deref", since = "1.40.0")]
1418 pub fn as_deref(&self) -> Option<&T::Target> {
1419 self.as_ref().map(|t| t.deref())
1423 impl<T: DerefMut> Option<T> {
1424 /// Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`.
1426 /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to
1427 /// the inner type's `Deref::Target` type.
1432 /// let mut x: Option<String> = Some("hey".to_owned());
1433 /// assert_eq!(x.as_deref_mut().map(|x| {
1434 /// x.make_ascii_uppercase();
1436 /// }), Some("HEY".to_owned().as_mut_str()));
1438 #[stable(feature = "option_deref", since = "1.40.0")]
1439 pub fn as_deref_mut(&mut self) -> Option<&mut T::Target> {
1440 self.as_mut().map(|t| t.deref_mut())
1444 impl<T, E> Option<Result<T, E>> {
1445 /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`.
1447 /// [`None`] will be mapped to [`Ok`]`(`[`None`]`)`.
1448 /// [`Some`]`(`[`Ok`]`(_))` and [`Some`]`(`[`Err`]`(_))` will be mapped to
1449 /// [`Ok`]`(`[`Some`]`(_))` and [`Err`]`(_)`.
1454 /// #[derive(Debug, Eq, PartialEq)]
1457 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1458 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1459 /// assert_eq!(x, y.transpose());
1462 #[stable(feature = "transpose_result", since = "1.33.0")]
1463 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1464 pub const fn transpose(self) -> Result<Option<T>, E> {
1466 Some(Ok(x)) => Ok(Some(x)),
1467 Some(Err(e)) => Err(e),
1473 // This is a separate function to reduce the code size of .expect() itself.
1477 fn expect_failed(msg: &str) -> ! {
1481 /////////////////////////////////////////////////////////////////////////////
1482 // Trait implementations
1483 /////////////////////////////////////////////////////////////////////////////
1485 #[stable(feature = "rust1", since = "1.0.0")]
1486 impl<T: Clone> Clone for Option<T> {
1488 fn clone(&self) -> Self {
1490 Some(x) => Some(x.clone()),
1496 fn clone_from(&mut self, source: &Self) {
1497 match (self, source) {
1498 (Some(to), Some(from)) => to.clone_from(from),
1499 (to, from) => *to = from.clone(),
1504 #[stable(feature = "rust1", since = "1.0.0")]
1505 impl<T> Default for Option<T> {
1506 /// Returns [`None`][Option::None].
1511 /// let opt: Option<u32> = Option::default();
1512 /// assert!(opt.is_none());
1515 fn default() -> Option<T> {
1520 #[stable(feature = "rust1", since = "1.0.0")]
1521 impl<T> IntoIterator for Option<T> {
1523 type IntoIter = IntoIter<T>;
1525 /// Returns a consuming iterator over the possibly contained value.
1530 /// let x = Some("string");
1531 /// let v: Vec<&str> = x.into_iter().collect();
1532 /// assert_eq!(v, ["string"]);
1535 /// let v: Vec<&str> = x.into_iter().collect();
1536 /// assert!(v.is_empty());
1539 fn into_iter(self) -> IntoIter<T> {
1540 IntoIter { inner: Item { opt: self } }
1544 #[stable(since = "1.4.0", feature = "option_iter")]
1545 impl<'a, T> IntoIterator for &'a Option<T> {
1547 type IntoIter = Iter<'a, T>;
1549 fn into_iter(self) -> Iter<'a, T> {
1554 #[stable(since = "1.4.0", feature = "option_iter")]
1555 impl<'a, T> IntoIterator for &'a mut Option<T> {
1556 type Item = &'a mut T;
1557 type IntoIter = IterMut<'a, T>;
1559 fn into_iter(self) -> IterMut<'a, T> {
1564 #[stable(since = "1.12.0", feature = "option_from")]
1565 impl<T> From<T> for Option<T> {
1566 /// Copies `val` into a new `Some`.
1571 /// let o: Option<u8> = Option::from(67);
1573 /// assert_eq!(Some(67), o);
1575 fn from(val: T) -> Option<T> {
1580 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1581 impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
1582 /// Converts from `&Option<T>` to `Option<&T>`.
1586 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
1587 /// The [`map`] method takes the `self` argument by value, consuming the original,
1588 /// so this technique uses `from` to first take an `Option` to a reference
1589 /// to the value inside the original.
1591 /// [`map`]: Option::map
1592 /// [`String`]: ../../std/string/struct.String.html
1595 /// let s: Option<String> = Some(String::from("Hello, Rustaceans!"));
1596 /// let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());
1598 /// println!("Can still print s: {:?}", s);
1600 /// assert_eq!(o, Some(18));
1602 fn from(o: &'a Option<T>) -> Option<&'a T> {
1607 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1608 impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> {
1609 /// Converts from `&mut Option<T>` to `Option<&mut T>`
1614 /// let mut s = Some(String::from("Hello"));
1615 /// let o: Option<&mut String> = Option::from(&mut s);
1618 /// Some(t) => *t = String::from("Hello, Rustaceans!"),
1622 /// assert_eq!(s, Some(String::from("Hello, Rustaceans!")));
1624 fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
1629 /////////////////////////////////////////////////////////////////////////////
1630 // The Option Iterators
1631 /////////////////////////////////////////////////////////////////////////////
1633 #[derive(Clone, Debug)]
1638 impl<A> Iterator for Item<A> {
1642 fn next(&mut self) -> Option<A> {
1647 fn size_hint(&self) -> (usize, Option<usize>) {
1649 Some(_) => (1, Some(1)),
1650 None => (0, Some(0)),
1655 impl<A> DoubleEndedIterator for Item<A> {
1657 fn next_back(&mut self) -> Option<A> {
1662 impl<A> ExactSizeIterator for Item<A> {}
1663 impl<A> FusedIterator for Item<A> {}
1664 unsafe impl<A> TrustedLen for Item<A> {}
1666 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
1668 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1670 /// This `struct` is created by the [`Option::iter`] function.
1671 #[stable(feature = "rust1", since = "1.0.0")]
1673 pub struct Iter<'a, A: 'a> {
1677 #[stable(feature = "rust1", since = "1.0.0")]
1678 impl<'a, A> Iterator for Iter<'a, A> {
1682 fn next(&mut self) -> Option<&'a A> {
1686 fn size_hint(&self) -> (usize, Option<usize>) {
1687 self.inner.size_hint()
1691 #[stable(feature = "rust1", since = "1.0.0")]
1692 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
1694 fn next_back(&mut self) -> Option<&'a A> {
1695 self.inner.next_back()
1699 #[stable(feature = "rust1", since = "1.0.0")]
1700 impl<A> ExactSizeIterator for Iter<'_, A> {}
1702 #[stable(feature = "fused", since = "1.26.0")]
1703 impl<A> FusedIterator for Iter<'_, A> {}
1705 #[unstable(feature = "trusted_len", issue = "37572")]
1706 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1708 #[stable(feature = "rust1", since = "1.0.0")]
1709 impl<A> Clone for Iter<'_, A> {
1711 fn clone(&self) -> Self {
1712 Iter { inner: self.inner.clone() }
1716 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
1718 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1720 /// This `struct` is created by the [`Option::iter_mut`] function.
1721 #[stable(feature = "rust1", since = "1.0.0")]
1723 pub struct IterMut<'a, A: 'a> {
1724 inner: Item<&'a mut A>,
1727 #[stable(feature = "rust1", since = "1.0.0")]
1728 impl<'a, A> Iterator for IterMut<'a, A> {
1729 type Item = &'a mut A;
1732 fn next(&mut self) -> Option<&'a mut A> {
1736 fn size_hint(&self) -> (usize, Option<usize>) {
1737 self.inner.size_hint()
1741 #[stable(feature = "rust1", since = "1.0.0")]
1742 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
1744 fn next_back(&mut self) -> Option<&'a mut A> {
1745 self.inner.next_back()
1749 #[stable(feature = "rust1", since = "1.0.0")]
1750 impl<A> ExactSizeIterator for IterMut<'_, A> {}
1752 #[stable(feature = "fused", since = "1.26.0")]
1753 impl<A> FusedIterator for IterMut<'_, A> {}
1754 #[unstable(feature = "trusted_len", issue = "37572")]
1755 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1757 /// An iterator over the value in [`Some`] variant of an [`Option`].
1759 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1761 /// This `struct` is created by the [`Option::into_iter`] function.
1762 #[derive(Clone, Debug)]
1763 #[stable(feature = "rust1", since = "1.0.0")]
1764 pub struct IntoIter<A> {
1768 #[stable(feature = "rust1", since = "1.0.0")]
1769 impl<A> Iterator for IntoIter<A> {
1773 fn next(&mut self) -> Option<A> {
1777 fn size_hint(&self) -> (usize, Option<usize>) {
1778 self.inner.size_hint()
1782 #[stable(feature = "rust1", since = "1.0.0")]
1783 impl<A> DoubleEndedIterator for IntoIter<A> {
1785 fn next_back(&mut self) -> Option<A> {
1786 self.inner.next_back()
1790 #[stable(feature = "rust1", since = "1.0.0")]
1791 impl<A> ExactSizeIterator for IntoIter<A> {}
1793 #[stable(feature = "fused", since = "1.26.0")]
1794 impl<A> FusedIterator for IntoIter<A> {}
1796 #[unstable(feature = "trusted_len", issue = "37572")]
1797 unsafe impl<A> TrustedLen for IntoIter<A> {}
1799 /////////////////////////////////////////////////////////////////////////////
1801 /////////////////////////////////////////////////////////////////////////////
1803 #[stable(feature = "rust1", since = "1.0.0")]
1804 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
1805 /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
1806 /// no further elements are taken, and the [`None`][Option::None] is
1807 /// returned. Should no [`None`][Option::None] occur, a container with the
1808 /// values of each [`Option`] is returned.
1812 /// Here is an example which increments every integer in a vector.
1813 /// We use the checked variant of `add` that returns `None` when the
1814 /// calculation would result in an overflow.
1817 /// let items = vec![0_u16, 1, 2];
1819 /// let res: Option<Vec<u16>> = items
1821 /// .map(|x| x.checked_add(1))
1824 /// assert_eq!(res, Some(vec![1, 2, 3]));
1827 /// As you can see, this will return the expected, valid items.
1829 /// Here is another example that tries to subtract one from another list
1830 /// of integers, this time checking for underflow:
1833 /// let items = vec![2_u16, 1, 0];
1835 /// let res: Option<Vec<u16>> = items
1837 /// .map(|x| x.checked_sub(1))
1840 /// assert_eq!(res, None);
1843 /// Since the last element is zero, it would underflow. Thus, the resulting
1844 /// value is `None`.
1846 /// Here is a variation on the previous example, showing that no
1847 /// further elements are taken from `iter` after the first `None`.
1850 /// let items = vec![3_u16, 2, 1, 10];
1852 /// let mut shared = 0;
1854 /// let res: Option<Vec<u16>> = items
1856 /// .map(|x| { shared += x; x.checked_sub(2) })
1859 /// assert_eq!(res, None);
1860 /// assert_eq!(shared, 6);
1863 /// Since the third element caused an underflow, no further elements were taken,
1864 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1866 fn from_iter<I: IntoIterator<Item = Option<A>>>(iter: I) -> Option<V> {
1867 // FIXME(#11084): This could be replaced with Iterator::scan when this
1868 // performance bug is closed.
1870 iter.into_iter().map(|x| x.ok_or(())).collect::<Result<_, _>>().ok()
1874 /// The error type that results from applying the try operator (`?`) to a `None` value. If you wish
1875 /// to allow `x?` (where `x` is an `Option<T>`) to be converted into your error type, you can
1876 /// implement `impl From<NoneError>` for `YourErrorType`. In that case, `x?` within a function that
1877 /// returns `Result<_, YourErrorType>` will translate a `None` value into an `Err` result.
1878 #[rustc_diagnostic_item = "none_error"]
1879 #[unstable(feature = "try_trait", issue = "42327")]
1880 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
1882 pub struct NoneError;
1884 #[unstable(feature = "try_trait", issue = "42327")]
1886 impl<T> ops::TryV1 for Option<T> {
1888 type Error = NoneError;
1891 fn into_result(self) -> Result<T, NoneError> {
1892 self.ok_or(NoneError)
1896 fn from_ok(v: T) -> Self {
1901 fn from_error(_: NoneError) -> Self {
1906 #[unstable(feature = "try_trait_v2", issue = "84277")]
1907 impl<T> ops::TryV2 for Option<T> {
1909 type Residual = Option<convert::Infallible>;
1912 fn from_output(output: Self::Output) -> Self {
1917 fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
1919 Some(v) => ControlFlow::Continue(v),
1920 None => ControlFlow::Break(None),
1925 #[unstable(feature = "try_trait_v2", issue = "84277")]
1926 impl<T> ops::FromResidual for Option<T> {
1928 fn from_residual(residual: Option<convert::Infallible>) -> Self {
1935 impl<T> Option<Option<T>> {
1936 /// Converts from `Option<Option<T>>` to `Option<T>`
1943 /// let x: Option<Option<u32>> = Some(Some(6));
1944 /// assert_eq!(Some(6), x.flatten());
1946 /// let x: Option<Option<u32>> = Some(None);
1947 /// assert_eq!(None, x.flatten());
1949 /// let x: Option<Option<u32>> = None;
1950 /// assert_eq!(None, x.flatten());
1953 /// Flattening only removes one level of nesting at a time:
1956 /// let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
1957 /// assert_eq!(Some(Some(6)), x.flatten());
1958 /// assert_eq!(Some(6), x.flatten().flatten());
1961 #[stable(feature = "option_flattening", since = "1.40.0")]
1962 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1963 pub const fn flatten(self) -> Option<T> {
1965 Some(inner) => inner,