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
359 //! match do_insert {
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);
1182 #[must_use = "if you intended to set a value, consider assignment instead"]
1184 #[stable(feature = "option_insert", since = "1.53.0")]
1185 pub fn insert(&mut self, value
: T
) -> &mut T
{
1186 *self = Some(value
);
1190 // SAFETY: the code above just filled the option
1191 None
=> unsafe { hint::unreachable_unchecked() }
,
1195 /// Inserts `value` into the option if it is [`None`], then
1196 /// returns a mutable reference to the contained value.
1198 /// See also [`Option::insert`], which updates the value even if
1199 /// the option already contains [`Some`].
1204 /// let mut x = None;
1207 /// let y: &mut u32 = x.get_or_insert(5);
1208 /// assert_eq!(y, &5);
1213 /// assert_eq!(x, Some(7));
1216 #[stable(feature = "option_entry", since = "1.20.0")]
1217 pub fn get_or_insert(&mut self, value
: T
) -> &mut T
{
1218 self.get_or_insert_with(|| value
)
1221 /// Inserts the default value into the option if it is [`None`], then
1222 /// returns a mutable reference to the contained value.
1227 /// #![feature(option_get_or_insert_default)]
1229 /// let mut x = None;
1232 /// let y: &mut u32 = x.get_or_insert_default();
1233 /// assert_eq!(y, &0);
1238 /// assert_eq!(x, Some(7));
1241 #[unstable(feature = "option_get_or_insert_default", issue = "82901")]
1242 pub fn get_or_insert_default(&mut self) -> &mut T
1246 self.get_or_insert_with(Default
::default)
1249 /// Inserts a value computed from `f` into the option if it is [`None`],
1250 /// then returns a mutable reference to the contained value.
1255 /// let mut x = None;
1258 /// let y: &mut u32 = x.get_or_insert_with(|| 5);
1259 /// assert_eq!(y, &5);
1264 /// assert_eq!(x, Some(7));
1267 #[stable(feature = "option_entry", since = "1.20.0")]
1268 pub fn get_or_insert_with
<F
: FnOnce() -> T
>(&mut self, f
: F
) -> &mut T
{
1269 if let None
= *self {
1275 // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
1276 // variant in the code above.
1277 None
=> unsafe { hint::unreachable_unchecked() }
,
1281 /////////////////////////////////////////////////////////////////////////
1283 /////////////////////////////////////////////////////////////////////////
1285 /// Takes the value out of the option, leaving a [`None`] in its place.
1290 /// let mut x = Some(2);
1291 /// let y = x.take();
1292 /// assert_eq!(x, None);
1293 /// assert_eq!(y, Some(2));
1295 /// let mut x: Option<u32> = None;
1296 /// let y = x.take();
1297 /// assert_eq!(x, None);
1298 /// assert_eq!(y, None);
1301 #[stable(feature = "rust1", since = "1.0.0")]
1302 pub fn take(&mut self) -> Option
<T
> {
1306 /// Replaces the actual value in the option by the value given in parameter,
1307 /// returning the old value if present,
1308 /// leaving a [`Some`] in its place without deinitializing either one.
1313 /// let mut x = Some(2);
1314 /// let old = x.replace(5);
1315 /// assert_eq!(x, Some(5));
1316 /// assert_eq!(old, Some(2));
1318 /// let mut x = None;
1319 /// let old = x.replace(3);
1320 /// assert_eq!(x, Some(3));
1321 /// assert_eq!(old, None);
1324 #[stable(feature = "option_replace", since = "1.31.0")]
1325 pub fn replace(&mut self, value
: T
) -> Option
<T
> {
1326 mem
::replace(self, Some(value
))
1329 /// Zips `self` with another `Option`.
1331 /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some((s, o))`.
1332 /// Otherwise, `None` is returned.
1337 /// let x = Some(1);
1338 /// let y = Some("hi");
1339 /// let z = None::<u8>;
1341 /// assert_eq!(x.zip(y), Some((1, "hi")));
1342 /// assert_eq!(x.zip(z), None);
1344 #[stable(feature = "option_zip_option", since = "1.46.0")]
1345 pub fn zip
<U
>(self, other
: Option
<U
>) -> Option
<(T
, U
)> {
1346 match (self, other
) {
1347 (Some(a
), Some(b
)) => Some((a
, b
)),
1352 /// Zips `self` and another `Option` with function `f`.
1354 /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
1355 /// Otherwise, `None` is returned.
1360 /// #![feature(option_zip)]
1362 /// #[derive(Debug, PartialEq)]
1369 /// fn new(x: f64, y: f64) -> Self {
1374 /// let x = Some(17.5);
1375 /// let y = Some(42.7);
1377 /// assert_eq!(x.zip_with(y, Point::new), Some(Point { x: 17.5, y: 42.7 }));
1378 /// assert_eq!(x.zip_with(None, Point::new), None);
1380 #[unstable(feature = "option_zip", issue = "70086")]
1381 pub fn zip_with
<U
, F
, R
>(self, other
: Option
<U
>, f
: F
) -> Option
<R
>
1383 F
: FnOnce(T
, U
) -> R
,
1385 Some(f(self?
, other?
))
1389 impl<T
: Copy
> Option
<&T
> {
1390 /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
1397 /// let opt_x = Some(&x);
1398 /// assert_eq!(opt_x, Some(&12));
1399 /// let copied = opt_x.copied();
1400 /// assert_eq!(copied, Some(12));
1402 #[stable(feature = "copied", since = "1.35.0")]
1403 pub fn copied(self) -> Option
<T
> {
1408 impl<T
: Copy
> Option
<&mut T
> {
1409 /// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the
1416 /// let opt_x = Some(&mut x);
1417 /// assert_eq!(opt_x, Some(&mut 12));
1418 /// let copied = opt_x.copied();
1419 /// assert_eq!(copied, Some(12));
1421 #[stable(feature = "copied", since = "1.35.0")]
1422 pub fn copied(self) -> Option
<T
> {
1423 self.map(|&mut t
| t
)
1427 impl<T
: Clone
> Option
<&T
> {
1428 /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
1435 /// let opt_x = Some(&x);
1436 /// assert_eq!(opt_x, Some(&12));
1437 /// let cloned = opt_x.cloned();
1438 /// assert_eq!(cloned, Some(12));
1440 #[stable(feature = "rust1", since = "1.0.0")]
1441 pub fn cloned(self) -> Option
<T
> {
1442 self.map(|t
| t
.clone())
1446 impl<T
: Clone
> Option
<&mut T
> {
1447 /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
1454 /// let opt_x = Some(&mut x);
1455 /// assert_eq!(opt_x, Some(&mut 12));
1456 /// let cloned = opt_x.cloned();
1457 /// assert_eq!(cloned, Some(12));
1459 #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
1460 pub fn cloned(self) -> Option
<T
> {
1461 self.map(|t
| t
.clone())
1465 impl<T
: Default
> Option
<T
> {
1466 /// Returns the contained [`Some`] value or a default
1468 /// Consumes the `self` argument then, if [`Some`], returns the contained
1469 /// value, otherwise if [`None`], returns the [default value] for that
1474 /// Converts a string to an integer, turning poorly-formed strings
1475 /// into 0 (the default value for integers). [`parse`] converts
1476 /// a string to any other type that implements [`FromStr`], returning
1477 /// [`None`] on error.
1480 /// let good_year_from_input = "1909";
1481 /// let bad_year_from_input = "190blarg";
1482 /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
1483 /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
1485 /// assert_eq!(1909, good_year);
1486 /// assert_eq!(0, bad_year);
1489 /// [default value]: Default::default
1490 /// [`parse`]: str::parse
1491 /// [`FromStr`]: crate::str::FromStr
1493 #[stable(feature = "rust1", since = "1.0.0")]
1494 pub fn unwrap_or_default(self) -> T
{
1497 None
=> Default
::default(),
1502 impl<T
: Deref
> Option
<T
> {
1503 /// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.
1505 /// Leaves the original Option in-place, creating a new one with a reference
1506 /// to the original one, additionally coercing the contents via [`Deref`].
1511 /// let x: Option<String> = Some("hey".to_owned());
1512 /// assert_eq!(x.as_deref(), Some("hey"));
1514 /// let x: Option<String> = None;
1515 /// assert_eq!(x.as_deref(), None);
1517 #[stable(feature = "option_deref", since = "1.40.0")]
1518 pub fn as_deref(&self) -> Option
<&T
::Target
> {
1519 self.as_ref().map(|t
| t
.deref())
1523 impl<T
: DerefMut
> Option
<T
> {
1524 /// Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`.
1526 /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to
1527 /// the inner type's `Deref::Target` type.
1532 /// let mut x: Option<String> = Some("hey".to_owned());
1533 /// assert_eq!(x.as_deref_mut().map(|x| {
1534 /// x.make_ascii_uppercase();
1536 /// }), Some("HEY".to_owned().as_mut_str()));
1538 #[stable(feature = "option_deref", since = "1.40.0")]
1539 pub fn as_deref_mut(&mut self) -> Option
<&mut T
::Target
> {
1540 self.as_mut().map(|t
| t
.deref_mut())
1544 impl<T
, E
> Option
<Result
<T
, E
>> {
1545 /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`.
1547 /// [`None`] will be mapped to [`Ok`]`(`[`None`]`)`.
1548 /// [`Some`]`(`[`Ok`]`(_))` and [`Some`]`(`[`Err`]`(_))` will be mapped to
1549 /// [`Ok`]`(`[`Some`]`(_))` and [`Err`]`(_)`.
1554 /// #[derive(Debug, Eq, PartialEq)]
1557 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1558 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1559 /// assert_eq!(x, y.transpose());
1562 #[stable(feature = "transpose_result", since = "1.33.0")]
1563 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1564 pub const fn transpose(self) -> Result
<Option
<T
>, E
> {
1566 Some(Ok(x
)) => Ok(Some(x
)),
1567 Some(Err(e
)) => Err(e
),
1573 // This is a separate function to reduce the code size of .expect() itself.
1577 fn expect_failed(msg
: &str) -> ! {
1581 /////////////////////////////////////////////////////////////////////////////
1582 // Trait implementations
1583 /////////////////////////////////////////////////////////////////////////////
1585 #[stable(feature = "rust1", since = "1.0.0")]
1586 impl<T
: Clone
> Clone
for Option
<T
> {
1588 fn clone(&self) -> Self {
1590 Some(x
) => Some(x
.clone()),
1596 fn clone_from(&mut self, source
: &Self) {
1597 match (self, source
) {
1598 (Some(to
), Some(from
)) => to
.clone_from(from
),
1599 (to
, from
) => *to
= from
.clone(),
1604 #[stable(feature = "rust1", since = "1.0.0")]
1605 impl<T
> Default
for Option
<T
> {
1606 /// Returns [`None`][Option::None].
1611 /// let opt: Option<u32> = Option::default();
1612 /// assert!(opt.is_none());
1615 fn default() -> Option
<T
> {
1620 #[stable(feature = "rust1", since = "1.0.0")]
1621 impl<T
> IntoIterator
for Option
<T
> {
1623 type IntoIter
= IntoIter
<T
>;
1625 /// Returns a consuming iterator over the possibly contained value.
1630 /// let x = Some("string");
1631 /// let v: Vec<&str> = x.into_iter().collect();
1632 /// assert_eq!(v, ["string"]);
1635 /// let v: Vec<&str> = x.into_iter().collect();
1636 /// assert!(v.is_empty());
1639 fn into_iter(self) -> IntoIter
<T
> {
1640 IntoIter { inner: Item { opt: self }
}
1644 #[stable(since = "1.4.0", feature = "option_iter")]
1645 impl<'a
, T
> IntoIterator
for &'a Option
<T
> {
1647 type IntoIter
= Iter
<'a
, T
>;
1649 fn into_iter(self) -> Iter
<'a
, T
> {
1654 #[stable(since = "1.4.0", feature = "option_iter")]
1655 impl<'a
, T
> IntoIterator
for &'a
mut Option
<T
> {
1656 type Item
= &'a
mut T
;
1657 type IntoIter
= IterMut
<'a
, T
>;
1659 fn into_iter(self) -> IterMut
<'a
, T
> {
1664 #[stable(since = "1.12.0", feature = "option_from")]
1665 impl<T
> From
<T
> for Option
<T
> {
1666 /// Copies `val` into a new `Some`.
1671 /// let o: Option<u8> = Option::from(67);
1673 /// assert_eq!(Some(67), o);
1675 fn from(val
: T
) -> Option
<T
> {
1680 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1681 impl<'a
, T
> From
<&'a Option
<T
>> for Option
<&'a T
> {
1682 /// Converts from `&Option<T>` to `Option<&T>`.
1686 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
1687 /// The [`map`] method takes the `self` argument by value, consuming the original,
1688 /// so this technique uses `from` to first take an `Option` to a reference
1689 /// to the value inside the original.
1691 /// [`map`]: Option::map
1692 /// [`String`]: ../../std/string/struct.String.html
1695 /// let s: Option<String> = Some(String::from("Hello, Rustaceans!"));
1696 /// let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());
1698 /// println!("Can still print s: {:?}", s);
1700 /// assert_eq!(o, Some(18));
1702 fn from(o
: &'a Option
<T
>) -> Option
<&'a T
> {
1707 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1708 impl<'a
, T
> From
<&'a
mut Option
<T
>> for Option
<&'a
mut T
> {
1709 /// Converts from `&mut Option<T>` to `Option<&mut T>`
1714 /// let mut s = Some(String::from("Hello"));
1715 /// let o: Option<&mut String> = Option::from(&mut s);
1718 /// Some(t) => *t = String::from("Hello, Rustaceans!"),
1722 /// assert_eq!(s, Some(String::from("Hello, Rustaceans!")));
1724 fn from(o
: &'a
mut Option
<T
>) -> Option
<&'a
mut T
> {
1729 /////////////////////////////////////////////////////////////////////////////
1730 // The Option Iterators
1731 /////////////////////////////////////////////////////////////////////////////
1733 #[derive(Clone, Debug)]
1738 impl<A
> Iterator
for Item
<A
> {
1742 fn next(&mut self) -> Option
<A
> {
1747 fn size_hint(&self) -> (usize, Option
<usize>) {
1749 Some(_
) => (1, Some(1)),
1750 None
=> (0, Some(0)),
1755 impl<A
> DoubleEndedIterator
for Item
<A
> {
1757 fn next_back(&mut self) -> Option
<A
> {
1762 impl<A
> ExactSizeIterator
for Item
<A
> {}
1763 impl<A
> FusedIterator
for Item
<A
> {}
1764 unsafe impl<A
> TrustedLen
for Item
<A
> {}
1766 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
1768 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1770 /// This `struct` is created by the [`Option::iter`] function.
1771 #[stable(feature = "rust1", since = "1.0.0")]
1773 pub struct Iter
<'a
, A
: 'a
> {
1777 #[stable(feature = "rust1", since = "1.0.0")]
1778 impl<'a
, A
> Iterator
for Iter
<'a
, A
> {
1782 fn next(&mut self) -> Option
<&'a A
> {
1786 fn size_hint(&self) -> (usize, Option
<usize>) {
1787 self.inner
.size_hint()
1791 #[stable(feature = "rust1", since = "1.0.0")]
1792 impl<'a
, A
> DoubleEndedIterator
for Iter
<'a
, A
> {
1794 fn next_back(&mut self) -> Option
<&'a A
> {
1795 self.inner
.next_back()
1799 #[stable(feature = "rust1", since = "1.0.0")]
1800 impl<A
> ExactSizeIterator
for Iter
<'_
, A
> {}
1802 #[stable(feature = "fused", since = "1.26.0")]
1803 impl<A
> FusedIterator
for Iter
<'_
, A
> {}
1805 #[unstable(feature = "trusted_len", issue = "37572")]
1806 unsafe impl<A
> TrustedLen
for Iter
<'_
, A
> {}
1808 #[stable(feature = "rust1", since = "1.0.0")]
1809 impl<A
> Clone
for Iter
<'_
, A
> {
1811 fn clone(&self) -> Self {
1812 Iter { inner: self.inner.clone() }
1816 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
1818 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1820 /// This `struct` is created by the [`Option::iter_mut`] function.
1821 #[stable(feature = "rust1", since = "1.0.0")]
1823 pub struct IterMut
<'a
, A
: 'a
> {
1824 inner
: Item
<&'a
mut A
>,
1827 #[stable(feature = "rust1", since = "1.0.0")]
1828 impl<'a
, A
> Iterator
for IterMut
<'a
, A
> {
1829 type Item
= &'a
mut A
;
1832 fn next(&mut self) -> Option
<&'a
mut A
> {
1836 fn size_hint(&self) -> (usize, Option
<usize>) {
1837 self.inner
.size_hint()
1841 #[stable(feature = "rust1", since = "1.0.0")]
1842 impl<'a
, A
> DoubleEndedIterator
for IterMut
<'a
, A
> {
1844 fn next_back(&mut self) -> Option
<&'a
mut A
> {
1845 self.inner
.next_back()
1849 #[stable(feature = "rust1", since = "1.0.0")]
1850 impl<A
> ExactSizeIterator
for IterMut
<'_
, A
> {}
1852 #[stable(feature = "fused", since = "1.26.0")]
1853 impl<A
> FusedIterator
for IterMut
<'_
, A
> {}
1854 #[unstable(feature = "trusted_len", issue = "37572")]
1855 unsafe impl<A
> TrustedLen
for IterMut
<'_
, A
> {}
1857 /// An iterator over the value in [`Some`] variant of an [`Option`].
1859 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1861 /// This `struct` is created by the [`Option::into_iter`] function.
1862 #[derive(Clone, Debug)]
1863 #[stable(feature = "rust1", since = "1.0.0")]
1864 pub struct IntoIter
<A
> {
1868 #[stable(feature = "rust1", since = "1.0.0")]
1869 impl<A
> Iterator
for IntoIter
<A
> {
1873 fn next(&mut self) -> Option
<A
> {
1877 fn size_hint(&self) -> (usize, Option
<usize>) {
1878 self.inner
.size_hint()
1882 #[stable(feature = "rust1", since = "1.0.0")]
1883 impl<A
> DoubleEndedIterator
for IntoIter
<A
> {
1885 fn next_back(&mut self) -> Option
<A
> {
1886 self.inner
.next_back()
1890 #[stable(feature = "rust1", since = "1.0.0")]
1891 impl<A
> ExactSizeIterator
for IntoIter
<A
> {}
1893 #[stable(feature = "fused", since = "1.26.0")]
1894 impl<A
> FusedIterator
for IntoIter
<A
> {}
1896 #[unstable(feature = "trusted_len", issue = "37572")]
1897 unsafe impl<A
> TrustedLen
for IntoIter
<A
> {}
1899 /////////////////////////////////////////////////////////////////////////////
1901 /////////////////////////////////////////////////////////////////////////////
1903 #[stable(feature = "rust1", since = "1.0.0")]
1904 impl<A
, V
: FromIterator
<A
>> FromIterator
<Option
<A
>> for Option
<V
> {
1905 /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
1906 /// no further elements are taken, and the [`None`][Option::None] is
1907 /// returned. Should no [`None`][Option::None] occur, a container with the
1908 /// values of each [`Option`] is returned.
1912 /// Here is an example which increments every integer in a vector.
1913 /// We use the checked variant of `add` that returns `None` when the
1914 /// calculation would result in an overflow.
1917 /// let items = vec![0_u16, 1, 2];
1919 /// let res: Option<Vec<u16>> = items
1921 /// .map(|x| x.checked_add(1))
1924 /// assert_eq!(res, Some(vec![1, 2, 3]));
1927 /// As you can see, this will return the expected, valid items.
1929 /// Here is another example that tries to subtract one from another list
1930 /// of integers, this time checking for underflow:
1933 /// let items = vec![2_u16, 1, 0];
1935 /// let res: Option<Vec<u16>> = items
1937 /// .map(|x| x.checked_sub(1))
1940 /// assert_eq!(res, None);
1943 /// Since the last element is zero, it would underflow. Thus, the resulting
1944 /// value is `None`.
1946 /// Here is a variation on the previous example, showing that no
1947 /// further elements are taken from `iter` after the first `None`.
1950 /// let items = vec![3_u16, 2, 1, 10];
1952 /// let mut shared = 0;
1954 /// let res: Option<Vec<u16>> = items
1956 /// .map(|x| { shared += x; x.checked_sub(2) })
1959 /// assert_eq!(res, None);
1960 /// assert_eq!(shared, 6);
1963 /// Since the third element caused an underflow, no further elements were taken,
1964 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1966 fn from_iter
<I
: IntoIterator
<Item
= Option
<A
>>>(iter
: I
) -> Option
<V
> {
1967 // FIXME(#11084): This could be replaced with Iterator::scan when this
1968 // performance bug is closed.
1970 iter
.into_iter().map(|x
| x
.ok_or(())).collect
::<Result
<_
, _
>>().ok()
1974 #[unstable(feature = "try_trait_v2", issue = "84277")]
1975 impl<T
> ops
::TryV2
for Option
<T
> {
1977 type Residual
= Option
<convert
::Infallible
>;
1980 fn from_output(output
: Self::Output
) -> Self {
1985 fn branch(self) -> ControlFlow
<Self::Residual
, Self::Output
> {
1987 Some(v
) => ControlFlow
::Continue(v
),
1988 None
=> ControlFlow
::Break(None
),
1993 #[unstable(feature = "try_trait_v2", issue = "84277")]
1994 impl<T
> ops
::FromResidual
for Option
<T
> {
1996 fn from_residual(residual
: Option
<convert
::Infallible
>) -> Self {
2003 impl<T
> Option
<Option
<T
>> {
2004 /// Converts from `Option<Option<T>>` to `Option<T>`
2011 /// let x: Option<Option<u32>> = Some(Some(6));
2012 /// assert_eq!(Some(6), x.flatten());
2014 /// let x: Option<Option<u32>> = Some(None);
2015 /// assert_eq!(None, x.flatten());
2017 /// let x: Option<Option<u32>> = None;
2018 /// assert_eq!(None, x.flatten());
2021 /// Flattening only removes one level of nesting at a time:
2024 /// let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
2025 /// assert_eq!(Some(Some(6)), x.flatten());
2026 /// assert_eq!(Some(6), x.flatten().flatten());
2029 #[stable(feature = "option_flattening", since = "1.40.0")]
2030 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
2031 pub const fn flatten(self) -> Option
<T
> {
2033 Some(inner
) => inner
,