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 //! [`Box<T>`]: ../../std/boxed/struct.Box.html
54 //! The following example uses [`Option`] to create an optional box of
55 //! [`i32`]. Notice that in order to use the inner [`i32`] value, the
56 //! `check_optional` function first needs to use pattern matching to
57 //! determine whether the box has a value (i.e., it is [`Some(...)`][`Some`]) or
61 //! let optional = None;
62 //! check_optional(optional);
64 //! let optional = Some(Box::new(9000));
65 //! check_optional(optional);
67 //! fn check_optional(optional: Option<Box<i32>>) {
69 //! Some(p) => println!("has value {}", p),
70 //! None => println!("has no value"),
77 //! Rust guarantees to optimize the following types `T` such that
78 //! [`Option<T>`] has the same size as `T`:
83 //! * `fn`, `extern "C" fn`
84 //! * [`num::NonZero*`]
85 //! * [`ptr::NonNull<U>`]
86 //! * `#[repr(transparent)]` struct around one of the types in this list.
88 //! [`Box<U>`]: ../../std/boxed/struct.Box.html
89 //! [`num::NonZero*`]: crate::num
90 //! [`ptr::NonNull<U>`]: crate::ptr::NonNull
92 //! This is called the "null pointer optimization" or NPO.
94 //! It is further guaranteed that, for the cases above, one can
95 //! [`mem::transmute`] from all valid values of `T` to `Option<T>` and
96 //! from `Some::<T>(_)` to `T` (but transmuting `None::<T>` to `T`
97 //! is undefined behaviour).
101 //! In addition to working with pattern matching, [`Option`] provides a wide
102 //! variety of different methods.
104 //! ## Querying the variant
106 //! The [`is_some`] and [`is_none`] methods return [`true`] if the [`Option`]
107 //! is [`Some`] or [`None`], respectively.
109 //! [`is_none`]: Option::is_none
110 //! [`is_some`]: Option::is_some
112 //! ## Adapters for working with references
114 //! * [`as_ref`] converts from `&Option<T>` to `Option<&T>`
115 //! * [`as_mut`] converts from `&mut Option<T>` to `Option<&mut T>`
116 //! * [`as_deref`] converts from `&Option<T>` to `Option<&T::Target>`
117 //! * [`as_deref_mut`] converts from `&mut Option<T>` to
118 //! `Option<&mut T::Target>`
119 //! * [`as_pin_ref`] converts from [`Pin`]`<&Option<T>>` to
120 //! `Option<`[`Pin`]`<&T>>`
121 //! * [`as_pin_mut`] converts from [`Pin`]`<&mut Option<T>>` to
122 //! `Option<`[`Pin`]`<&mut T>>`
124 //! [`as_deref`]: Option::as_deref
125 //! [`as_deref_mut`]: Option::as_deref_mut
126 //! [`as_mut`]: Option::as_mut
127 //! [`as_pin_mut`]: Option::as_pin_mut
128 //! [`as_pin_ref`]: Option::as_pin_ref
129 //! [`as_ref`]: Option::as_ref
131 //! ## Extracting the contained value
133 //! These methods extract the contained value in an [`Option<T>`] when it
134 //! is the [`Some`] variant. If the [`Option`] is [`None`]:
136 //! * [`expect`] panics with a provided custom message
137 //! * [`unwrap`] panics with a generic message
138 //! * [`unwrap_or`] returns the provided default value
139 //! * [`unwrap_or_default`] returns the default value of the type `T`
140 //! (which must implement the [`Default`] trait)
141 //! * [`unwrap_or_else`] returns the result of evaluating the provided
144 //! [`expect`]: Option::expect
145 //! [`unwrap`]: Option::unwrap
146 //! [`unwrap_or`]: Option::unwrap_or
147 //! [`unwrap_or_default`]: Option::unwrap_or_default
148 //! [`unwrap_or_else`]: Option::unwrap_or_else
150 //! ## Transforming contained values
152 //! These methods transform [`Option`] to [`Result`]:
154 //! * [`ok_or`] transforms [`Some(v)`] to [`Ok(v)`], and [`None`] to
155 //! [`Err(err)`] using the provided default `err` value
156 //! * [`ok_or_else`] transforms [`Some(v)`] to [`Ok(v)`], and [`None`] to
157 //! a value of [`Err`] using the provided function
158 //! * [`transpose`] transposes an [`Option`] of a [`Result`] into a
159 //! [`Result`] of an [`Option`]
161 //! [`Err(err)`]: Err
163 //! [`Some(v)`]: Some
164 //! [`ok_or`]: Option::ok_or
165 //! [`ok_or_else`]: Option::ok_or_else
166 //! [`transpose`]: Option::transpose
168 //! These methods transform the [`Some`] variant:
170 //! * [`filter`] calls the provided predicate function on the contained
171 //! value `t` if the [`Option`] is [`Some(t)`], and returns [`Some(t)`]
172 //! if the function returns `true`; otherwise, returns [`None`]
173 //! * [`flatten`] removes one level of nesting from an
174 //! [`Option<Option<T>>`]
175 //! * [`map`] transforms [`Option<T>`] to [`Option<U>`] by applying the
176 //! provided function to the contained value of [`Some`] and leaving
177 //! [`None`] values unchanged
179 //! [`Some(t)`]: Some
180 //! [`filter`]: Option::filter
181 //! [`flatten`]: Option::flatten
182 //! [`map`]: Option::map
184 //! These methods transform [`Option<T>`] to a value of a possibly
185 //! different type `U`:
187 //! * [`map_or`] applies the provided function to the contained value of
188 //! [`Some`], or returns the provided default value if the [`Option`] is
190 //! * [`map_or_else`] applies the provided function to the contained value
191 //! of [`Some`], or returns the result of evaluating the provided
192 //! fallback function if the [`Option`] is [`None`]
194 //! [`map_or`]: Option::map_or
195 //! [`map_or_else`]: Option::map_or_else
197 //! These methods combine the [`Some`] variants of two [`Option`] values:
199 //! * [`zip`] returns [`Some((s, o))`] if `self` is [`Some(s)`] and the
200 //! provided [`Option`] value is [`Some(o)`]; otherwise, returns [`None`]
201 //! * [`zip_with`] calls the provided function `f` and returns
202 //! [`Some(f(s, o))`] if `self` is [`Some(s)`] and the provided
203 //! [`Option`] value is [`Some(o)`]; otherwise, returns [`None`]
205 //! [`Some(f(s, o))`]: Some
206 //! [`Some(o)`]: Some
207 //! [`Some(s)`]: Some
208 //! [`Some((s, o))`]: Some
209 //! [`zip`]: Option::zip
210 //! [`zip_with`]: Option::zip_with
212 //! ## Boolean operators
214 //! These methods treat the [`Option`] as a boolean value, where [`Some`]
215 //! acts like [`true`] and [`None`] acts like [`false`]. There are two
216 //! categories of these methods: ones that take an [`Option`] as input, and
217 //! ones that take a function as input (to be lazily evaluated).
219 //! The [`and`], [`or`], and [`xor`] methods take another [`Option`] as
220 //! input, and produce an [`Option`] as output. Only the [`and`] method can
221 //! produce an [`Option<U>`] value having a different inner type `U` than
224 //! | method | self | input | output |
225 //! |---------|-----------|-----------|-----------|
226 //! | [`and`] | `None` | (ignored) | `None` |
227 //! | [`and`] | `Some(x)` | `None` | `None` |
228 //! | [`and`] | `Some(x)` | `Some(y)` | `Some(y)` |
229 //! | [`or`] | `None` | `None` | `None` |
230 //! | [`or`] | `None` | `Some(y)` | `Some(y)` |
231 //! | [`or`] | `Some(x)` | (ignored) | `Some(x)` |
232 //! | [`xor`] | `None` | `None` | `None` |
233 //! | [`xor`] | `None` | `Some(y)` | `Some(y)` |
234 //! | [`xor`] | `Some(x)` | `None` | `Some(x)` |
235 //! | [`xor`] | `Some(x)` | `Some(y)` | `None` |
237 //! [`and`]: Option::and
238 //! [`or`]: Option::or
239 //! [`xor`]: Option::xor
241 //! The [`and_then`] and [`or_else`] methods take a function as input, and
242 //! only evaluate the function when they need to produce a new value. Only
243 //! the [`and_then`] method can produce an [`Option<U>`] value having a
244 //! different inner type `U` than [`Option<T>`].
246 //! | method | self | function input | function result | output |
247 //! |--------------|-----------|----------------|-----------------|-----------|
248 //! | [`and_then`] | `None` | (not provided) | (not evaluated) | `None` |
249 //! | [`and_then`] | `Some(x)` | `x` | `None` | `None` |
250 //! | [`and_then`] | `Some(x)` | `x` | `Some(y)` | `Some(y)` |
251 //! | [`or_else`] | `None` | (not provided) | `None` | `None` |
252 //! | [`or_else`] | `None` | (not provided) | `Some(y)` | `Some(y)` |
253 //! | [`or_else`] | `Some(x)` | (not provided) | (not evaluated) | `Some(x)` |
255 //! [`and_then`]: Option::and_then
256 //! [`or_else`]: Option::or_else
258 //! This is an example of using methods like [`and_then`] and [`or`] in a
259 //! pipeline of method calls. Early stages of the pipeline pass failure
260 //! values ([`None`]) through unchanged, and continue processing on
261 //! success values ([`Some`]). Toward the end, [`or`] substitutes an error
262 //! message if it receives [`None`].
265 //! # use std::collections::BTreeMap;
266 //! let mut bt = BTreeMap::new();
267 //! bt.insert(20u8, "foo");
268 //! bt.insert(42u8, "bar");
269 //! let res = vec![0u8, 1, 11, 200, 22]
272 //! // `checked_sub()` returns `None` on error
274 //! // same with `checked_mul()`
275 //! .and_then(|x| x.checked_mul(2))
276 //! // `BTreeMap::get` returns `None` on error
277 //! .and_then(|x| bt.get(&x))
278 //! // Substitute an error message if we have `None` so far
279 //! .or(Some(&"error!"))
281 //! // Won't panic because we unconditionally used `Some` above
284 //! .collect::<Vec<_>>();
285 //! assert_eq!(res, ["error!", "error!", "foo", "error!", "bar"]);
288 //! ## Iterating over `Option`
290 //! An [`Option`] can be iterated over. This can be helpful if you need an
291 //! iterator that is conditionally empty. The iterator will either produce
292 //! a single value (when the [`Option`] is [`Some`]), or produce no values
293 //! (when the [`Option`] is [`None`]). For example, [`into_iter`] acts like
294 //! [`once(v)`] if the [`Option`] is [`Some(v)`], and like [`empty()`] if
295 //! the [`Option`] is [`None`].
297 //! [`Some(v)`]: Some
298 //! [`empty()`]: crate::iter::empty
299 //! [`once(v)`]: crate::iter::once
301 //! Iterators over [`Option<T>`] come in three types:
303 //! * [`into_iter`] consumes the [`Option`] and produces the contained
305 //! * [`iter`] produces an immutable reference of type `&T` to the
307 //! * [`iter_mut`] produces a mutable reference of type `&mut T` to the
310 //! [`into_iter`]: Option::into_iter
311 //! [`iter`]: Option::iter
312 //! [`iter_mut`]: Option::iter_mut
314 //! An iterator over [`Option`] can be useful when chaining iterators, for
315 //! example, to conditionally insert items. (It's not always necessary to
316 //! explicitly call an iterator constructor: many [`Iterator`] methods that
317 //! accept other iterators will also accept iterable types that implement
318 //! [`IntoIterator`], which includes [`Option`].)
321 //! let yep = Some(42);
323 //! // chain() already calls into_iter(), so we don't have to do so
324 //! let nums: Vec<i32> = (0..4).chain(yep).chain(4..8).collect();
325 //! assert_eq!(nums, [0, 1, 2, 3, 42, 4, 5, 6, 7]);
326 //! let nums: Vec<i32> = (0..4).chain(nope).chain(4..8).collect();
327 //! assert_eq!(nums, [0, 1, 2, 3, 4, 5, 6, 7]);
330 //! One reason to chain iterators in this way is that a function returning
331 //! `impl Iterator` must have all possible return values be of the same
332 //! concrete type. Chaining an iterated [`Option`] can help with that.
335 //! fn make_iter(do_insert: bool) -> impl Iterator<Item = i32> {
336 //! // Explicit returns to illustrate return types matching
337 //! match do_insert {
338 //! true => return (0..4).chain(Some(42)).chain(4..8),
339 //! false => return (0..4).chain(None).chain(4..8),
342 //! println!("{:?}", make_iter(true).collect::<Vec<_>>());
343 //! println!("{:?}", make_iter(false).collect::<Vec<_>>());
346 //! If we try to do the same thing, but using [`once()`] and [`empty()`],
347 //! we can't return `impl Iterator` anymore because the concrete types of
348 //! the return values differ.
350 //! [`empty()`]: crate::iter::empty
351 //! [`once()`]: crate::iter::once
353 //! ```compile_fail,E0308
354 //! # use std::iter::{empty, once};
355 //! // This won't compile because all possible returns from the function
356 //! // must have the same concrete type.
357 //! fn make_iter(do_insert: bool) -> impl Iterator<Item = i32> {
358 //! // Explicit returns to illustrate return types not matching
360 //! true => return (0..4).chain(once(42)).chain(4..8),
361 //! false => return (0..4).chain(empty()).chain(4..8),
366 //! ## Collecting into `Option`
368 //! [`Option`] implements the [`FromIterator`][impl-FromIterator] trait,
369 //! which allows an iterator over [`Option`] values to be collected into an
370 //! [`Option`] of a collection of each contained value of the original
371 //! [`Option`] values, or [`None`] if any of the elements was [`None`].
373 //! [impl-FromIterator]: Option#impl-FromIterator%3COption%3CA%3E%3E
376 //! let v = vec![Some(2), Some(4), None, Some(8)];
377 //! let res: Option<Vec<_>> = v.into_iter().collect();
378 //! assert_eq!(res, None);
379 //! let v = vec![Some(2), Some(4), Some(8)];
380 //! let res: Option<Vec<_>> = v.into_iter().collect();
381 //! assert_eq!(res, Some(vec![2, 4, 8]));
384 //! [`Option`] also implements the [`Product`][impl-Product] and
385 //! [`Sum`][impl-Sum] traits, allowing an iterator over [`Option`] values
386 //! to provide the [`product`][Iterator::product] and
387 //! [`sum`][Iterator::sum] methods.
389 //! [impl-Product]: Option#impl-Product%3COption%3CU%3E%3E
390 //! [impl-Sum]: Option#impl-Sum%3COption%3CU%3E%3E
393 //! let v = vec![None, Some(1), Some(2), Some(3)];
394 //! let res: Option<i32> = v.into_iter().sum();
395 //! assert_eq!(res, None);
396 //! let v = vec![Some(1), Some(2), Some(21)];
397 //! let res: Option<i32> = v.into_iter().product();
398 //! assert_eq!(res, Some(42));
401 //! ## Modifying an [`Option`] in-place
403 //! These methods return a mutable reference to the contained value of an
406 //! * [`insert`] inserts a value, dropping any old contents
407 //! * [`get_or_insert`] gets the current value, inserting a provided
408 //! default value if it is [`None`]
409 //! * [`get_or_insert_default`] gets the current value, inserting the
410 //! default value of type `T` (which must implement [`Default`]) if it is
412 //! * [`get_or_insert_with`] gets the current value, inserting a default
413 //! computed by the provided function if it is [`None`]
415 //! [`get_or_insert`]: Option::get_or_insert
416 //! [`get_or_insert_default`]: Option::get_or_insert_default
417 //! [`get_or_insert_with`]: Option::get_or_insert_with
418 //! [`insert`]: Option::insert
420 //! These methods transfer ownership of the contained value of an
423 //! * [`take`] takes ownership of the contained value of an [`Option`], if
424 //! any, replacing the [`Option`] with [`None`]
425 //! * [`replace`] takes ownership of the contained value of an [`Option`],
426 //! if any, replacing the [`Option`] with a [`Some`] containing the
429 //! [`replace`]: Option::replace
430 //! [`take`]: Option::take
434 //! Basic pattern matching on [`Option`]:
437 //! let msg = Some("howdy");
439 //! // Take a reference to the contained string
440 //! if let Some(m) = &msg {
441 //! println!("{}", *m);
444 //! // Remove the contained string, destroying the Option
445 //! let unwrapped_msg = msg.unwrap_or("default message");
448 //! Initialize a result to [`None`] before a loop:
451 //! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) }
453 //! // A list of data to search through.
454 //! let all_the_big_things = [
455 //! Kingdom::Plant(250, "redwood"),
456 //! Kingdom::Plant(230, "noble fir"),
457 //! Kingdom::Plant(229, "sugar pine"),
458 //! Kingdom::Animal(25, "blue whale"),
459 //! Kingdom::Animal(19, "fin whale"),
460 //! Kingdom::Animal(15, "north pacific right whale"),
463 //! // We're going to search for the name of the biggest animal,
464 //! // but to start with we've just got `None`.
465 //! let mut name_of_biggest_animal = None;
466 //! let mut size_of_biggest_animal = 0;
467 //! for big_thing in &all_the_big_things {
468 //! match *big_thing {
469 //! Kingdom::Animal(size, name) if size > size_of_biggest_animal => {
470 //! // Now we've found the name of some big animal
471 //! size_of_biggest_animal = size;
472 //! name_of_biggest_animal = Some(name);
474 //! Kingdom::Animal(..) | Kingdom::Plant(..) => ()
478 //! match name_of_biggest_animal {
479 //! Some(name) => println!("the biggest animal is {}", name),
480 //! None => println!("there are no animals :("),
484 #![stable(feature = "rust1", since = "1.0.0")]
486 use crate::iter::{FromIterator, FusedIterator, TrustedLen};
490 ops::{self, ControlFlow, Deref, DerefMut},
493 /// The `Option` type. See [the module level documentation](self) for more.
494 #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
495 #[rustc_diagnostic_item = "option_type"]
496 #[stable(feature = "rust1", since = "1.0.0")]
500 #[stable(feature = "rust1", since = "1.0.0")]
504 #[stable(feature = "rust1", since = "1.0.0")]
505 Some(#[stable(feature = "rust1", since = "1.0.0")] T),
508 /////////////////////////////////////////////////////////////////////////////
509 // Type implementation
510 /////////////////////////////////////////////////////////////////////////////
513 /////////////////////////////////////////////////////////////////////////
514 // Querying the contained values
515 /////////////////////////////////////////////////////////////////////////
517 /// Returns `true` if the option is a [`Some`] value.
522 /// let x: Option<u32> = Some(2);
523 /// assert_eq!(x.is_some(), true);
525 /// let x: Option<u32> = None;
526 /// assert_eq!(x.is_some(), false);
528 #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"]
530 #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
531 #[stable(feature = "rust1", since = "1.0.0")]
532 pub const fn is_some(&self) -> bool {
533 matches!(*self, Some(_))
536 /// Returns `true` if the option is a [`None`] value.
541 /// let x: Option<u32> = Some(2);
542 /// assert_eq!(x.is_none(), false);
544 /// let x: Option<u32> = None;
545 /// assert_eq!(x.is_none(), true);
547 #[must_use = "if you intended to assert that this doesn't have a value, consider \
548 `.and_then(|_| panic!(\"`Option` had a value when expected `None`\"))` instead"]
550 #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
551 #[stable(feature = "rust1", since = "1.0.0")]
552 pub const fn is_none(&self) -> bool {
556 /// Returns `true` if the option is a [`Some`] value containing the given value.
561 /// #![feature(option_result_contains)]
563 /// let x: Option<u32> = Some(2);
564 /// assert_eq!(x.contains(&2), true);
566 /// let x: Option<u32> = Some(3);
567 /// assert_eq!(x.contains(&2), false);
569 /// let x: Option<u32> = None;
570 /// assert_eq!(x.contains(&2), false);
574 #[unstable(feature = "option_result_contains", issue = "62358")]
575 pub fn contains<U>(&self, x: &U) -> bool
585 /////////////////////////////////////////////////////////////////////////
586 // Adapter for working with references
587 /////////////////////////////////////////////////////////////////////////
589 /// Converts from `&Option<T>` to `Option<&T>`.
593 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
594 /// The [`map`] method takes the `self` argument by value, consuming the original,
595 /// so this technique uses `as_ref` to first take an `Option` to a reference
596 /// to the value inside the original.
598 /// [`map`]: Option::map
599 /// [`String`]: ../../std/string/struct.String.html
602 /// let text: Option<String> = Some("Hello, world!".to_string());
603 /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
604 /// // then consume *that* with `map`, leaving `text` on the stack.
605 /// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
606 /// println!("still can print text: {:?}", text);
609 #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
610 #[stable(feature = "rust1", since = "1.0.0")]
611 pub const fn as_ref(&self) -> Option<&T> {
613 Some(ref x) => Some(x),
618 /// Converts from `&mut Option<T>` to `Option<&mut T>`.
623 /// let mut x = Some(2);
624 /// match x.as_mut() {
625 /// Some(v) => *v = 42,
628 /// assert_eq!(x, Some(42));
631 #[stable(feature = "rust1", since = "1.0.0")]
632 pub fn as_mut(&mut self) -> Option<&mut T> {
634 Some(ref mut x) => Some(x),
639 /// Converts from [`Pin`]`<&Option<T>>` to `Option<`[`Pin`]`<&T>>`.
641 #[stable(feature = "pin", since = "1.33.0")]
642 pub fn as_pin_ref(self: Pin<&Self>) -> Option<Pin<&T>> {
643 // SAFETY: `x` is guaranteed to be pinned because it comes from `self`
645 unsafe { Pin::get_ref(self).as_ref().map(|x| Pin::new_unchecked(x)) }
648 /// Converts from [`Pin`]`<&mut Option<T>>` to `Option<`[`Pin`]`<&mut T>>`.
650 #[stable(feature = "pin", since = "1.33.0")]
651 pub fn as_pin_mut(self: Pin<&mut Self>) -> Option<Pin<&mut T>> {
652 // SAFETY: `get_unchecked_mut` is never used to move the `Option` inside `self`.
653 // `x` is guaranteed to be pinned because it comes from `self` which is pinned.
654 unsafe { Pin::get_unchecked_mut(self).as_mut().map(|x| Pin::new_unchecked(x)) }
657 /////////////////////////////////////////////////////////////////////////
658 // Getting to contained values
659 /////////////////////////////////////////////////////////////////////////
661 /// Returns the contained [`Some`] value, consuming the `self` value.
665 /// Panics if the value is a [`None`] with a custom panic message provided by
671 /// let x = Some("value");
672 /// assert_eq!(x.expect("fruits are healthy"), "value");
676 /// let x: Option<&str> = None;
677 /// x.expect("fruits are healthy"); // panics with `fruits are healthy`
681 #[stable(feature = "rust1", since = "1.0.0")]
682 pub fn expect(self, msg: &str) -> T {
685 None => expect_failed(msg),
689 /// Returns the contained [`Some`] value, consuming the `self` value.
691 /// Because this function may panic, its use is generally discouraged.
692 /// Instead, prefer to use pattern matching and handle the [`None`]
693 /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
694 /// [`unwrap_or_default`].
696 /// [`unwrap_or`]: Option::unwrap_or
697 /// [`unwrap_or_else`]: Option::unwrap_or_else
698 /// [`unwrap_or_default`]: Option::unwrap_or_default
702 /// Panics if the self value equals [`None`].
707 /// let x = Some("air");
708 /// assert_eq!(x.unwrap(), "air");
712 /// let x: Option<&str> = None;
713 /// assert_eq!(x.unwrap(), "air"); // fails
717 #[stable(feature = "rust1", since = "1.0.0")]
718 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
719 pub const fn unwrap(self) -> T {
722 None => panic!("called `Option::unwrap()` on a `None` value"),
726 /// Returns the contained [`Some`] value or a provided default.
728 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
729 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
730 /// which is lazily evaluated.
732 /// [`unwrap_or_else`]: Option::unwrap_or_else
737 /// assert_eq!(Some("car").unwrap_or("bike"), "car");
738 /// assert_eq!(None.unwrap_or("bike"), "bike");
741 #[stable(feature = "rust1", since = "1.0.0")]
742 pub fn unwrap_or(self, default: T) -> T {
749 /// Returns the contained [`Some`] value or computes it from a closure.
755 /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
756 /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
759 #[stable(feature = "rust1", since = "1.0.0")]
760 pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
767 /// Returns the contained [`Some`] value, consuming the `self` value,
768 /// without checking that the value is not [`None`].
772 /// Calling this method on [`None`] is *[undefined behavior]*.
774 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
779 /// #![feature(option_result_unwrap_unchecked)]
780 /// let x = Some("air");
781 /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air");
785 /// #![feature(option_result_unwrap_unchecked)]
786 /// let x: Option<&str> = None;
787 /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air"); // Undefined behavior!
791 #[unstable(feature = "option_result_unwrap_unchecked", reason = "newly added", issue = "81383")]
792 pub unsafe fn unwrap_unchecked(self) -> T {
793 debug_assert!(self.is_some());
796 // SAFETY: the safety contract must be upheld by the caller.
797 None => unsafe { hint::unreachable_unchecked() },
801 /////////////////////////////////////////////////////////////////////////
802 // Transforming contained values
803 /////////////////////////////////////////////////////////////////////////
805 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
809 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, consuming the original:
811 /// [`String`]: ../../std/string/struct.String.html
813 /// let maybe_some_string = Some(String::from("Hello, World!"));
814 /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
815 /// let maybe_some_len = maybe_some_string.map(|s| s.len());
817 /// assert_eq!(maybe_some_len, Some(13));
820 #[stable(feature = "rust1", since = "1.0.0")]
821 pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
823 Some(x) => Some(f(x)),
828 /// Returns the provided default result (if none),
829 /// or applies a function to the contained value (if any).
831 /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
832 /// the result of a function call, it is recommended to use [`map_or_else`],
833 /// which is lazily evaluated.
835 /// [`map_or_else`]: Option::map_or_else
840 /// let x = Some("foo");
841 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
843 /// let x: Option<&str> = None;
844 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
847 #[stable(feature = "rust1", since = "1.0.0")]
848 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
855 /// Computes a default function result (if none), or
856 /// applies a different function to the contained value (if any).
863 /// let x = Some("foo");
864 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
866 /// let x: Option<&str> = None;
867 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
870 #[stable(feature = "rust1", since = "1.0.0")]
871 pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
878 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
879 /// [`Ok(v)`] and [`None`] to [`Err(err)`].
881 /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
882 /// result of a function call, it is recommended to use [`ok_or_else`], which is
883 /// lazily evaluated.
886 /// [`Err(err)`]: Err
887 /// [`Some(v)`]: Some
888 /// [`ok_or_else`]: Option::ok_or_else
893 /// let x = Some("foo");
894 /// assert_eq!(x.ok_or(0), Ok("foo"));
896 /// let x: Option<&str> = None;
897 /// assert_eq!(x.ok_or(0), Err(0));
900 #[stable(feature = "rust1", since = "1.0.0")]
901 pub fn ok_or<E>(self, err: E) -> Result<T, E> {
908 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
909 /// [`Ok(v)`] and [`None`] to [`Err(err())`].
912 /// [`Err(err())`]: Err
913 /// [`Some(v)`]: Some
918 /// let x = Some("foo");
919 /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
921 /// let x: Option<&str> = None;
922 /// assert_eq!(x.ok_or_else(|| 0), Err(0));
925 #[stable(feature = "rust1", since = "1.0.0")]
926 pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
933 /////////////////////////////////////////////////////////////////////////
934 // Iterator constructors
935 /////////////////////////////////////////////////////////////////////////
937 /// Returns an iterator over the possibly contained value.
943 /// assert_eq!(x.iter().next(), Some(&4));
945 /// let x: Option<u32> = None;
946 /// assert_eq!(x.iter().next(), None);
949 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
950 #[stable(feature = "rust1", since = "1.0.0")]
951 pub const fn iter(&self) -> Iter<'_, T> {
952 Iter { inner: Item { opt: self.as_ref() } }
955 /// Returns a mutable iterator over the possibly contained value.
960 /// let mut x = Some(4);
961 /// match x.iter_mut().next() {
962 /// Some(v) => *v = 42,
965 /// assert_eq!(x, Some(42));
967 /// let mut x: Option<u32> = None;
968 /// assert_eq!(x.iter_mut().next(), None);
971 #[stable(feature = "rust1", since = "1.0.0")]
972 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
973 IterMut { inner: Item { opt: self.as_mut() } }
976 /////////////////////////////////////////////////////////////////////////
977 // Boolean operations on the values, eager and lazy
978 /////////////////////////////////////////////////////////////////////////
980 /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
986 /// let y: Option<&str> = None;
987 /// assert_eq!(x.and(y), None);
989 /// let x: Option<u32> = None;
990 /// let y = Some("foo");
991 /// assert_eq!(x.and(y), None);
994 /// let y = Some("foo");
995 /// assert_eq!(x.and(y), Some("foo"));
997 /// let x: Option<u32> = None;
998 /// let y: Option<&str> = None;
999 /// assert_eq!(x.and(y), None);
1002 #[stable(feature = "rust1", since = "1.0.0")]
1003 pub fn and<U>(self, optb: Option<U>) -> Option<U> {
1010 /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
1011 /// wrapped value and returns the result.
1013 /// Some languages call this operation flatmap.
1018 /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
1019 /// fn nope(_: u32) -> Option<u32> { None }
1021 /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
1022 /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
1023 /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
1024 /// assert_eq!(None.and_then(sq).and_then(sq), None);
1027 #[stable(feature = "rust1", since = "1.0.0")]
1028 pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> {
1035 /// Returns [`None`] if the option is [`None`], otherwise calls `predicate`
1036 /// with the wrapped value and returns:
1038 /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped
1040 /// - [`None`] if `predicate` returns `false`.
1042 /// This function works similar to [`Iterator::filter()`]. You can imagine
1043 /// the `Option<T>` being an iterator over one or zero elements. `filter()`
1044 /// lets you decide which elements to keep.
1049 /// fn is_even(n: &i32) -> bool {
1053 /// assert_eq!(None.filter(is_even), None);
1054 /// assert_eq!(Some(3).filter(is_even), None);
1055 /// assert_eq!(Some(4).filter(is_even), Some(4));
1058 /// [`Some(t)`]: Some
1060 #[stable(feature = "option_filter", since = "1.27.0")]
1061 pub fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Self {
1062 if let Some(x) = self {
1070 /// Returns the option if it contains a value, otherwise returns `optb`.
1072 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
1073 /// result of a function call, it is recommended to use [`or_else`], which is
1074 /// lazily evaluated.
1076 /// [`or_else`]: Option::or_else
1081 /// let x = Some(2);
1083 /// assert_eq!(x.or(y), Some(2));
1086 /// let y = Some(100);
1087 /// assert_eq!(x.or(y), Some(100));
1089 /// let x = Some(2);
1090 /// let y = Some(100);
1091 /// assert_eq!(x.or(y), Some(2));
1093 /// let x: Option<u32> = None;
1095 /// assert_eq!(x.or(y), None);
1098 #[stable(feature = "rust1", since = "1.0.0")]
1099 pub fn or(self, optb: Option<T>) -> Option<T> {
1106 /// Returns the option if it contains a value, otherwise calls `f` and
1107 /// returns the result.
1112 /// fn nobody() -> Option<&'static str> { None }
1113 /// fn vikings() -> Option<&'static str> { Some("vikings") }
1115 /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
1116 /// assert_eq!(None.or_else(vikings), Some("vikings"));
1117 /// assert_eq!(None.or_else(nobody), None);
1120 #[stable(feature = "rust1", since = "1.0.0")]
1121 pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> {
1128 /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`].
1133 /// let x = Some(2);
1134 /// let y: Option<u32> = None;
1135 /// assert_eq!(x.xor(y), Some(2));
1137 /// let x: Option<u32> = None;
1138 /// let y = Some(2);
1139 /// assert_eq!(x.xor(y), Some(2));
1141 /// let x = Some(2);
1142 /// let y = Some(2);
1143 /// assert_eq!(x.xor(y), None);
1145 /// let x: Option<u32> = None;
1146 /// let y: Option<u32> = None;
1147 /// assert_eq!(x.xor(y), None);
1150 #[stable(feature = "option_xor", since = "1.37.0")]
1151 pub fn xor(self, optb: Option<T>) -> Option<T> {
1152 match (self, optb) {
1153 (Some(a), None) => Some(a),
1154 (None, Some(b)) => Some(b),
1159 /////////////////////////////////////////////////////////////////////////
1160 // Entry-like operations to insert a value and return a reference
1161 /////////////////////////////////////////////////////////////////////////
1163 /// Inserts `value` into the option then returns a mutable reference to it.
1165 /// If the option already contains a value, the old value is dropped.
1167 /// See also [`Option::get_or_insert`], which doesn't update the value if
1168 /// the option already contains [`Some`].
1173 /// let mut opt = None;
1174 /// let val = opt.insert(1);
1175 /// assert_eq!(*val, 1);
1176 /// assert_eq!(opt.unwrap(), 1);
1177 /// let val = opt.insert(2);
1178 /// assert_eq!(*val, 2);
1180 /// assert_eq!(opt.unwrap(), 3);
1183 #[stable(feature = "option_insert", since = "1.53.0")]
1184 pub fn insert(&mut self, value: T) -> &mut T {
1185 *self = Some(value);
1189 // SAFETY: the code above just filled the option
1190 None => unsafe { hint::unreachable_unchecked() },
1194 /// Inserts `value` into the option if it is [`None`], then
1195 /// returns a mutable reference to the contained value.
1197 /// See also [`Option::insert`], which updates the value even if
1198 /// the option already contains [`Some`].
1203 /// let mut x = None;
1206 /// let y: &mut u32 = x.get_or_insert(5);
1207 /// assert_eq!(y, &5);
1212 /// assert_eq!(x, Some(7));
1215 #[stable(feature = "option_entry", since = "1.20.0")]
1216 pub fn get_or_insert(&mut self, value: T) -> &mut T {
1217 self.get_or_insert_with(|| value)
1220 /// Inserts the default value into the option if it is [`None`], then
1221 /// returns a mutable reference to the contained value.
1226 /// #![feature(option_get_or_insert_default)]
1228 /// let mut x = None;
1231 /// let y: &mut u32 = x.get_or_insert_default();
1232 /// assert_eq!(y, &0);
1237 /// assert_eq!(x, Some(7));
1240 #[unstable(feature = "option_get_or_insert_default", issue = "82901")]
1241 pub fn get_or_insert_default(&mut self) -> &mut T
1245 self.get_or_insert_with(Default::default)
1248 /// Inserts a value computed from `f` into the option if it is [`None`],
1249 /// then returns a mutable reference to the contained value.
1254 /// let mut x = None;
1257 /// let y: &mut u32 = x.get_or_insert_with(|| 5);
1258 /// assert_eq!(y, &5);
1263 /// assert_eq!(x, Some(7));
1266 #[stable(feature = "option_entry", since = "1.20.0")]
1267 pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
1268 if let None = *self {
1274 // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
1275 // variant in the code above.
1276 None => unsafe { hint::unreachable_unchecked() },
1280 /////////////////////////////////////////////////////////////////////////
1282 /////////////////////////////////////////////////////////////////////////
1284 /// Takes the value out of the option, leaving a [`None`] in its place.
1289 /// let mut x = Some(2);
1290 /// let y = x.take();
1291 /// assert_eq!(x, None);
1292 /// assert_eq!(y, Some(2));
1294 /// let mut x: Option<u32> = None;
1295 /// let y = x.take();
1296 /// assert_eq!(x, None);
1297 /// assert_eq!(y, None);
1300 #[stable(feature = "rust1", since = "1.0.0")]
1301 pub fn take(&mut self) -> Option<T> {
1305 /// Replaces the actual value in the option by the value given in parameter,
1306 /// returning the old value if present,
1307 /// leaving a [`Some`] in its place without deinitializing either one.
1312 /// let mut x = Some(2);
1313 /// let old = x.replace(5);
1314 /// assert_eq!(x, Some(5));
1315 /// assert_eq!(old, Some(2));
1317 /// let mut x = None;
1318 /// let old = x.replace(3);
1319 /// assert_eq!(x, Some(3));
1320 /// assert_eq!(old, None);
1323 #[stable(feature = "option_replace", since = "1.31.0")]
1324 pub fn replace(&mut self, value: T) -> Option<T> {
1325 mem::replace(self, Some(value))
1328 /// Zips `self` with another `Option`.
1330 /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some((s, o))`.
1331 /// Otherwise, `None` is returned.
1336 /// let x = Some(1);
1337 /// let y = Some("hi");
1338 /// let z = None::<u8>;
1340 /// assert_eq!(x.zip(y), Some((1, "hi")));
1341 /// assert_eq!(x.zip(z), None);
1343 #[stable(feature = "option_zip_option", since = "1.46.0")]
1344 pub fn zip<U>(self, other: Option<U>) -> Option<(T, U)> {
1345 match (self, other) {
1346 (Some(a), Some(b)) => Some((a, b)),
1351 /// Zips `self` and another `Option` with function `f`.
1353 /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
1354 /// Otherwise, `None` is returned.
1359 /// #![feature(option_zip)]
1361 /// #[derive(Debug, PartialEq)]
1368 /// fn new(x: f64, y: f64) -> Self {
1373 /// let x = Some(17.5);
1374 /// let y = Some(42.7);
1376 /// assert_eq!(x.zip_with(y, Point::new), Some(Point { x: 17.5, y: 42.7 }));
1377 /// assert_eq!(x.zip_with(None, Point::new), None);
1379 #[unstable(feature = "option_zip", issue = "70086")]
1380 pub fn zip_with<U, F, R>(self, other: Option<U>, f: F) -> Option<R>
1382 F: FnOnce(T, U) -> R,
1384 Some(f(self?, other?))
1388 impl<T: Copy> Option<&T> {
1389 /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
1396 /// let opt_x = Some(&x);
1397 /// assert_eq!(opt_x, Some(&12));
1398 /// let copied = opt_x.copied();
1399 /// assert_eq!(copied, Some(12));
1401 #[stable(feature = "copied", since = "1.35.0")]
1402 pub fn copied(self) -> Option<T> {
1407 impl<T: Copy> Option<&mut T> {
1408 /// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the
1415 /// let opt_x = Some(&mut x);
1416 /// assert_eq!(opt_x, Some(&mut 12));
1417 /// let copied = opt_x.copied();
1418 /// assert_eq!(copied, Some(12));
1420 #[stable(feature = "copied", since = "1.35.0")]
1421 pub fn copied(self) -> Option<T> {
1422 self.map(|&mut t| t)
1426 impl<T: Clone> Option<&T> {
1427 /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
1434 /// let opt_x = Some(&x);
1435 /// assert_eq!(opt_x, Some(&12));
1436 /// let cloned = opt_x.cloned();
1437 /// assert_eq!(cloned, Some(12));
1439 #[stable(feature = "rust1", since = "1.0.0")]
1440 pub fn cloned(self) -> Option<T> {
1441 self.map(|t| t.clone())
1445 impl<T: Clone> Option<&mut T> {
1446 /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
1453 /// let opt_x = Some(&mut x);
1454 /// assert_eq!(opt_x, Some(&mut 12));
1455 /// let cloned = opt_x.cloned();
1456 /// assert_eq!(cloned, Some(12));
1458 #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
1459 pub fn cloned(self) -> Option<T> {
1460 self.map(|t| t.clone())
1464 impl<T: Default> Option<T> {
1465 /// Returns the contained [`Some`] value or a default
1467 /// Consumes the `self` argument then, if [`Some`], returns the contained
1468 /// value, otherwise if [`None`], returns the [default value] for that
1473 /// Converts a string to an integer, turning poorly-formed strings
1474 /// into 0 (the default value for integers). [`parse`] converts
1475 /// a string to any other type that implements [`FromStr`], returning
1476 /// [`None`] on error.
1479 /// let good_year_from_input = "1909";
1480 /// let bad_year_from_input = "190blarg";
1481 /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
1482 /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
1484 /// assert_eq!(1909, good_year);
1485 /// assert_eq!(0, bad_year);
1488 /// [default value]: Default::default
1489 /// [`parse`]: str::parse
1490 /// [`FromStr`]: crate::str::FromStr
1492 #[stable(feature = "rust1", since = "1.0.0")]
1493 pub fn unwrap_or_default(self) -> T {
1496 None => Default::default(),
1501 impl<T: Deref> Option<T> {
1502 /// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.
1504 /// Leaves the original Option in-place, creating a new one with a reference
1505 /// to the original one, additionally coercing the contents via [`Deref`].
1510 /// let x: Option<String> = Some("hey".to_owned());
1511 /// assert_eq!(x.as_deref(), Some("hey"));
1513 /// let x: Option<String> = None;
1514 /// assert_eq!(x.as_deref(), None);
1516 #[stable(feature = "option_deref", since = "1.40.0")]
1517 pub fn as_deref(&self) -> Option<&T::Target> {
1518 self.as_ref().map(|t| t.deref())
1522 impl<T: DerefMut> Option<T> {
1523 /// Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`.
1525 /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to
1526 /// the inner type's `Deref::Target` type.
1531 /// let mut x: Option<String> = Some("hey".to_owned());
1532 /// assert_eq!(x.as_deref_mut().map(|x| {
1533 /// x.make_ascii_uppercase();
1535 /// }), Some("HEY".to_owned().as_mut_str()));
1537 #[stable(feature = "option_deref", since = "1.40.0")]
1538 pub fn as_deref_mut(&mut self) -> Option<&mut T::Target> {
1539 self.as_mut().map(|t| t.deref_mut())
1543 impl<T, E> Option<Result<T, E>> {
1544 /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`.
1546 /// [`None`] will be mapped to [`Ok`]`(`[`None`]`)`.
1547 /// [`Some`]`(`[`Ok`]`(_))` and [`Some`]`(`[`Err`]`(_))` will be mapped to
1548 /// [`Ok`]`(`[`Some`]`(_))` and [`Err`]`(_)`.
1553 /// #[derive(Debug, Eq, PartialEq)]
1556 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1557 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1558 /// assert_eq!(x, y.transpose());
1561 #[stable(feature = "transpose_result", since = "1.33.0")]
1562 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1563 pub const fn transpose(self) -> Result<Option<T>, E> {
1565 Some(Ok(x)) => Ok(Some(x)),
1566 Some(Err(e)) => Err(e),
1572 // This is a separate function to reduce the code size of .expect() itself.
1576 fn expect_failed(msg: &str) -> ! {
1580 /////////////////////////////////////////////////////////////////////////////
1581 // Trait implementations
1582 /////////////////////////////////////////////////////////////////////////////
1584 #[stable(feature = "rust1", since = "1.0.0")]
1585 impl<T: Clone> Clone for Option<T> {
1587 fn clone(&self) -> Self {
1589 Some(x) => Some(x.clone()),
1595 fn clone_from(&mut self, source: &Self) {
1596 match (self, source) {
1597 (Some(to), Some(from)) => to.clone_from(from),
1598 (to, from) => *to = from.clone(),
1603 #[stable(feature = "rust1", since = "1.0.0")]
1604 impl<T> Default for Option<T> {
1605 /// Returns [`None`][Option::None].
1610 /// let opt: Option<u32> = Option::default();
1611 /// assert!(opt.is_none());
1614 fn default() -> Option<T> {
1619 #[stable(feature = "rust1", since = "1.0.0")]
1620 impl<T> IntoIterator for Option<T> {
1622 type IntoIter = IntoIter<T>;
1624 /// Returns a consuming iterator over the possibly contained value.
1629 /// let x = Some("string");
1630 /// let v: Vec<&str> = x.into_iter().collect();
1631 /// assert_eq!(v, ["string"]);
1634 /// let v: Vec<&str> = x.into_iter().collect();
1635 /// assert!(v.is_empty());
1638 fn into_iter(self) -> IntoIter<T> {
1639 IntoIter { inner: Item { opt: self } }
1643 #[stable(since = "1.4.0", feature = "option_iter")]
1644 impl<'a, T> IntoIterator for &'a Option<T> {
1646 type IntoIter = Iter<'a, T>;
1648 fn into_iter(self) -> Iter<'a, T> {
1653 #[stable(since = "1.4.0", feature = "option_iter")]
1654 impl<'a, T> IntoIterator for &'a mut Option<T> {
1655 type Item = &'a mut T;
1656 type IntoIter = IterMut<'a, T>;
1658 fn into_iter(self) -> IterMut<'a, T> {
1663 #[stable(since = "1.12.0", feature = "option_from")]
1664 impl<T> From<T> for Option<T> {
1665 /// Copies `val` into a new `Some`.
1670 /// let o: Option<u8> = Option::from(67);
1672 /// assert_eq!(Some(67), o);
1674 fn from(val: T) -> Option<T> {
1679 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1680 impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
1681 /// Converts from `&Option<T>` to `Option<&T>`.
1685 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
1686 /// The [`map`] method takes the `self` argument by value, consuming the original,
1687 /// so this technique uses `from` to first take an `Option` to a reference
1688 /// to the value inside the original.
1690 /// [`map`]: Option::map
1691 /// [`String`]: ../../std/string/struct.String.html
1694 /// let s: Option<String> = Some(String::from("Hello, Rustaceans!"));
1695 /// let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());
1697 /// println!("Can still print s: {:?}", s);
1699 /// assert_eq!(o, Some(18));
1701 fn from(o: &'a Option<T>) -> Option<&'a T> {
1706 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1707 impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> {
1708 /// Converts from `&mut Option<T>` to `Option<&mut T>`
1713 /// let mut s = Some(String::from("Hello"));
1714 /// let o: Option<&mut String> = Option::from(&mut s);
1717 /// Some(t) => *t = String::from("Hello, Rustaceans!"),
1721 /// assert_eq!(s, Some(String::from("Hello, Rustaceans!")));
1723 fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
1728 /////////////////////////////////////////////////////////////////////////////
1729 // The Option Iterators
1730 /////////////////////////////////////////////////////////////////////////////
1732 #[derive(Clone, Debug)]
1737 impl<A> Iterator for Item<A> {
1741 fn next(&mut self) -> Option<A> {
1746 fn size_hint(&self) -> (usize, Option<usize>) {
1748 Some(_) => (1, Some(1)),
1749 None => (0, Some(0)),
1754 impl<A> DoubleEndedIterator for Item<A> {
1756 fn next_back(&mut self) -> Option<A> {
1761 impl<A> ExactSizeIterator for Item<A> {}
1762 impl<A> FusedIterator for Item<A> {}
1763 unsafe impl<A> TrustedLen for Item<A> {}
1765 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
1767 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1769 /// This `struct` is created by the [`Option::iter`] function.
1770 #[stable(feature = "rust1", since = "1.0.0")]
1772 pub struct Iter<'a, A: 'a> {
1776 #[stable(feature = "rust1", since = "1.0.0")]
1777 impl<'a, A> Iterator for Iter<'a, A> {
1781 fn next(&mut self) -> Option<&'a A> {
1785 fn size_hint(&self) -> (usize, Option<usize>) {
1786 self.inner.size_hint()
1790 #[stable(feature = "rust1", since = "1.0.0")]
1791 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
1793 fn next_back(&mut self) -> Option<&'a A> {
1794 self.inner.next_back()
1798 #[stable(feature = "rust1", since = "1.0.0")]
1799 impl<A> ExactSizeIterator for Iter<'_, A> {}
1801 #[stable(feature = "fused", since = "1.26.0")]
1802 impl<A> FusedIterator for Iter<'_, A> {}
1804 #[unstable(feature = "trusted_len", issue = "37572")]
1805 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1807 #[stable(feature = "rust1", since = "1.0.0")]
1808 impl<A> Clone for Iter<'_, A> {
1810 fn clone(&self) -> Self {
1811 Iter { inner: self.inner.clone() }
1815 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
1817 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1819 /// This `struct` is created by the [`Option::iter_mut`] function.
1820 #[stable(feature = "rust1", since = "1.0.0")]
1822 pub struct IterMut<'a, A: 'a> {
1823 inner: Item<&'a mut A>,
1826 #[stable(feature = "rust1", since = "1.0.0")]
1827 impl<'a, A> Iterator for IterMut<'a, A> {
1828 type Item = &'a mut A;
1831 fn next(&mut self) -> Option<&'a mut A> {
1835 fn size_hint(&self) -> (usize, Option<usize>) {
1836 self.inner.size_hint()
1840 #[stable(feature = "rust1", since = "1.0.0")]
1841 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
1843 fn next_back(&mut self) -> Option<&'a mut A> {
1844 self.inner.next_back()
1848 #[stable(feature = "rust1", since = "1.0.0")]
1849 impl<A> ExactSizeIterator for IterMut<'_, A> {}
1851 #[stable(feature = "fused", since = "1.26.0")]
1852 impl<A> FusedIterator for IterMut<'_, A> {}
1853 #[unstable(feature = "trusted_len", issue = "37572")]
1854 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1856 /// An iterator over the value in [`Some`] variant of an [`Option`].
1858 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1860 /// This `struct` is created by the [`Option::into_iter`] function.
1861 #[derive(Clone, Debug)]
1862 #[stable(feature = "rust1", since = "1.0.0")]
1863 pub struct IntoIter<A> {
1867 #[stable(feature = "rust1", since = "1.0.0")]
1868 impl<A> Iterator for IntoIter<A> {
1872 fn next(&mut self) -> Option<A> {
1876 fn size_hint(&self) -> (usize, Option<usize>) {
1877 self.inner.size_hint()
1881 #[stable(feature = "rust1", since = "1.0.0")]
1882 impl<A> DoubleEndedIterator for IntoIter<A> {
1884 fn next_back(&mut self) -> Option<A> {
1885 self.inner.next_back()
1889 #[stable(feature = "rust1", since = "1.0.0")]
1890 impl<A> ExactSizeIterator for IntoIter<A> {}
1892 #[stable(feature = "fused", since = "1.26.0")]
1893 impl<A> FusedIterator for IntoIter<A> {}
1895 #[unstable(feature = "trusted_len", issue = "37572")]
1896 unsafe impl<A> TrustedLen for IntoIter<A> {}
1898 /////////////////////////////////////////////////////////////////////////////
1900 /////////////////////////////////////////////////////////////////////////////
1902 #[stable(feature = "rust1", since = "1.0.0")]
1903 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
1904 /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
1905 /// no further elements are taken, and the [`None`][Option::None] is
1906 /// returned. Should no [`None`][Option::None] occur, a container with the
1907 /// values of each [`Option`] is returned.
1911 /// Here is an example which increments every integer in a vector.
1912 /// We use the checked variant of `add` that returns `None` when the
1913 /// calculation would result in an overflow.
1916 /// let items = vec![0_u16, 1, 2];
1918 /// let res: Option<Vec<u16>> = items
1920 /// .map(|x| x.checked_add(1))
1923 /// assert_eq!(res, Some(vec![1, 2, 3]));
1926 /// As you can see, this will return the expected, valid items.
1928 /// Here is another example that tries to subtract one from another list
1929 /// of integers, this time checking for underflow:
1932 /// let items = vec![2_u16, 1, 0];
1934 /// let res: Option<Vec<u16>> = items
1936 /// .map(|x| x.checked_sub(1))
1939 /// assert_eq!(res, None);
1942 /// Since the last element is zero, it would underflow. Thus, the resulting
1943 /// value is `None`.
1945 /// Here is a variation on the previous example, showing that no
1946 /// further elements are taken from `iter` after the first `None`.
1949 /// let items = vec![3_u16, 2, 1, 10];
1951 /// let mut shared = 0;
1953 /// let res: Option<Vec<u16>> = items
1955 /// .map(|x| { shared += x; x.checked_sub(2) })
1958 /// assert_eq!(res, None);
1959 /// assert_eq!(shared, 6);
1962 /// Since the third element caused an underflow, no further elements were taken,
1963 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1965 fn from_iter<I: IntoIterator<Item = Option<A>>>(iter: I) -> Option<V> {
1966 // FIXME(#11084): This could be replaced with Iterator::scan when this
1967 // performance bug is closed.
1969 iter.into_iter().map(|x| x.ok_or(())).collect::<Result<_, _>>().ok()
1973 /// The error type that results from applying the try operator (`?`) to a `None` value. If you wish
1974 /// to allow `x?` (where `x` is an `Option<T>`) to be converted into your error type, you can
1975 /// implement `impl From<NoneError>` for `YourErrorType`. In that case, `x?` within a function that
1976 /// returns `Result<_, YourErrorType>` will translate a `None` value into an `Err` result.
1977 #[rustc_diagnostic_item = "none_error"]
1978 #[unstable(feature = "try_trait", issue = "42327")]
1979 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
1981 pub struct NoneError;
1983 #[unstable(feature = "try_trait", issue = "42327")]
1985 impl<T> ops::TryV1 for Option<T> {
1987 type Error = NoneError;
1990 fn into_result(self) -> Result<T, NoneError> {
1991 self.ok_or(NoneError)
1995 fn from_ok(v: T) -> Self {
2000 fn from_error(_: NoneError) -> Self {
2005 #[unstable(feature = "try_trait_v2", issue = "84277")]
2006 impl<T> ops::TryV2 for Option<T> {
2008 type Residual = Option<convert::Infallible>;
2011 fn from_output(output: Self::Output) -> Self {
2016 fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
2018 Some(v) => ControlFlow::Continue(v),
2019 None => ControlFlow::Break(None),
2024 #[unstable(feature = "try_trait_v2", issue = "84277")]
2025 impl<T> ops::FromResidual for Option<T> {
2027 fn from_residual(residual: Option<convert::Infallible>) -> Self {
2034 impl<T> Option<Option<T>> {
2035 /// Converts from `Option<Option<T>>` to `Option<T>`
2042 /// let x: Option<Option<u32>> = Some(Some(6));
2043 /// assert_eq!(Some(6), x.flatten());
2045 /// let x: Option<Option<u32>> = Some(None);
2046 /// assert_eq!(None, x.flatten());
2048 /// let x: Option<Option<u32>> = None;
2049 /// assert_eq!(None, x.flatten());
2052 /// Flattening only removes one level of nesting at a time:
2055 /// let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
2056 /// assert_eq!(Some(Some(6)), x.flatten());
2057 /// assert_eq!(Some(6), x.flatten().flatten());
2060 #[stable(feature = "option_flattening", since = "1.40.0")]
2061 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
2062 pub const fn flatten(self) -> Option<T> {
2064 Some(inner) => inner,