]> git.lizzy.rs Git - rust.git/blob - library/core/src/option.rs
Revert effects of PRs 81167 and 83091.
[rust.git] / library / core / src / option.rs
1 //! Optional values.
2 //!
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:
7 //!
8 //! * Initial values
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
12 //!   returned on error
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
18 //!
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.
21 //!
22 //! ```
23 //! fn divide(numerator: f64, denominator: f64) -> Option<f64> {
24 //!     if denominator == 0.0 {
25 //!         None
26 //!     } else {
27 //!         Some(numerator / denominator)
28 //!     }
29 //! }
30 //!
31 //! // The return value of the function is an option
32 //! let result = divide(2.0, 3.0);
33 //!
34 //! // Pattern match to retrieve the value
35 //! match result {
36 //!     // The division was valid
37 //!     Some(x) => println!("Result: {}", x),
38 //!     // The division was invalid
39 //!     None    => println!("Cannot divide by 0"),
40 //! }
41 //! ```
42 //!
43 //
44 // FIXME: Show how `Option` is used in practice, with lots of methods
45 //
46 //! # Options and pointers ("nullable" pointers)
47 //!
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>`]`>`.
51 //!
52 //! The following example uses [`Option`] to create an optional box of
53 //! [`i32`]. Notice that in order to use the inner [`i32`] value first, the
54 //! `check_optional` function needs to use pattern matching to
55 //! determine whether the box has a value (i.e., it is [`Some(...)`][`Some`]) or
56 //! not ([`None`]).
57 //!
58 //! ```
59 //! let optional = None;
60 //! check_optional(optional);
61 //!
62 //! let optional = Some(Box::new(9000));
63 //! check_optional(optional);
64 //!
65 //! fn check_optional(optional: Option<Box<i32>>) {
66 //!     match optional {
67 //!         Some(p) => println!("has value {}", p),
68 //!         None => println!("has no value"),
69 //!     }
70 //! }
71 //! ```
72 //!
73 //! # Representation
74 //!
75 //! Rust guarantees to optimize the following types `T` such that
76 //! [`Option<T>`] has the same size as `T`:
77 //!
78 //! * [`Box<U>`]
79 //! * `&U`
80 //! * `&mut U`
81 //! * `fn`, `extern "C" fn`
82 //! * [`num::NonZero*`]
83 //! * [`ptr::NonNull<U>`]
84 //! * `#[repr(transparent)]` struct around one of the types in this list.
85 //!
86 //! This is called the "null pointer optimization" or NPO.
87 //!
88 //! It is further guaranteed that, for the cases above, one can
89 //! [`mem::transmute`] from all valid values of `T` to `Option<T>` and
90 //! from `Some::<T>(_)` to `T` (but transmuting `None::<T>` to `T`
91 //! is undefined behaviour).
92 //!
93 //! # Examples
94 //!
95 //! Basic pattern matching on [`Option`]:
96 //!
97 //! ```
98 //! let msg = Some("howdy");
99 //!
100 //! // Take a reference to the contained string
101 //! if let Some(m) = &msg {
102 //!     println!("{}", *m);
103 //! }
104 //!
105 //! // Remove the contained string, destroying the Option
106 //! let unwrapped_msg = msg.unwrap_or("default message");
107 //! ```
108 //!
109 //! Initialize a result to [`None`] before a loop:
110 //!
111 //! ```
112 //! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) }
113 //!
114 //! // A list of data to search through.
115 //! let all_the_big_things = [
116 //!     Kingdom::Plant(250, "redwood"),
117 //!     Kingdom::Plant(230, "noble fir"),
118 //!     Kingdom::Plant(229, "sugar pine"),
119 //!     Kingdom::Animal(25, "blue whale"),
120 //!     Kingdom::Animal(19, "fin whale"),
121 //!     Kingdom::Animal(15, "north pacific right whale"),
122 //! ];
123 //!
124 //! // We're going to search for the name of the biggest animal,
125 //! // but to start with we've just got `None`.
126 //! let mut name_of_biggest_animal = None;
127 //! let mut size_of_biggest_animal = 0;
128 //! for big_thing in &all_the_big_things {
129 //!     match *big_thing {
130 //!         Kingdom::Animal(size, name) if size > size_of_biggest_animal => {
131 //!             // Now we've found the name of some big animal
132 //!             size_of_biggest_animal = size;
133 //!             name_of_biggest_animal = Some(name);
134 //!         }
135 //!         Kingdom::Animal(..) | Kingdom::Plant(..) => ()
136 //!     }
137 //! }
138 //!
139 //! match name_of_biggest_animal {
140 //!     Some(name) => println!("the biggest animal is {}", name),
141 //!     None => println!("there are no animals :("),
142 //! }
143 //! ```
144 //!
145 //! [`Box<T>`]: ../../std/boxed/struct.Box.html
146 //! [`Box<U>`]: ../../std/boxed/struct.Box.html
147 //! [`num::NonZero*`]: crate::num
148 //! [`ptr::NonNull<U>`]: crate::ptr::NonNull
149
150 #![stable(feature = "rust1", since = "1.0.0")]
151
152 use crate::iter::{FromIterator, FusedIterator, TrustedLen};
153 use crate::pin::Pin;
154 use crate::{
155     convert, hint, mem,
156     ops::{self, ControlFlow, Deref, DerefMut},
157 };
158
159 /// The `Option` type. See [the module level documentation](self) for more.
160 #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
161 #[rustc_diagnostic_item = "option_type"]
162 #[stable(feature = "rust1", since = "1.0.0")]
163 pub enum Option<T> {
164     /// No value
165     #[lang = "None"]
166     #[stable(feature = "rust1", since = "1.0.0")]
167     None,
168     /// Some value `T`
169     #[lang = "Some"]
170     #[stable(feature = "rust1", since = "1.0.0")]
171     Some(#[stable(feature = "rust1", since = "1.0.0")] T),
172 }
173
174 /////////////////////////////////////////////////////////////////////////////
175 // Type implementation
176 /////////////////////////////////////////////////////////////////////////////
177
178 impl<T> Option<T> {
179     /////////////////////////////////////////////////////////////////////////
180     // Querying the contained values
181     /////////////////////////////////////////////////////////////////////////
182
183     /// Returns `true` if the option is a [`Some`] value.
184     ///
185     /// # Examples
186     ///
187     /// ```
188     /// let x: Option<u32> = Some(2);
189     /// assert_eq!(x.is_some(), true);
190     ///
191     /// let x: Option<u32> = None;
192     /// assert_eq!(x.is_some(), false);
193     /// ```
194     #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"]
195     #[inline]
196     #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
197     #[stable(feature = "rust1", since = "1.0.0")]
198     pub const fn is_some(&self) -> bool {
199         matches!(*self, Some(_))
200     }
201
202     /// Returns `true` if the option is a [`None`] value.
203     ///
204     /// # Examples
205     ///
206     /// ```
207     /// let x: Option<u32> = Some(2);
208     /// assert_eq!(x.is_none(), false);
209     ///
210     /// let x: Option<u32> = None;
211     /// assert_eq!(x.is_none(), true);
212     /// ```
213     #[must_use = "if you intended to assert that this doesn't have a value, consider \
214                   `.and_then(|_| panic!(\"`Option` had a value when expected `None`\"))` instead"]
215     #[inline]
216     #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
217     #[stable(feature = "rust1", since = "1.0.0")]
218     pub const fn is_none(&self) -> bool {
219         !self.is_some()
220     }
221
222     /// Returns `true` if the option is a [`Some`] value containing the given value.
223     ///
224     /// # Examples
225     ///
226     /// ```
227     /// #![feature(option_result_contains)]
228     ///
229     /// let x: Option<u32> = Some(2);
230     /// assert_eq!(x.contains(&2), true);
231     ///
232     /// let x: Option<u32> = Some(3);
233     /// assert_eq!(x.contains(&2), false);
234     ///
235     /// let x: Option<u32> = None;
236     /// assert_eq!(x.contains(&2), false);
237     /// ```
238     #[must_use]
239     #[inline]
240     #[unstable(feature = "option_result_contains", issue = "62358")]
241     pub fn contains<U>(&self, x: &U) -> bool
242     where
243         U: PartialEq<T>,
244     {
245         match self {
246             Some(y) => x == y,
247             None => false,
248         }
249     }
250
251     /////////////////////////////////////////////////////////////////////////
252     // Adapter for working with references
253     /////////////////////////////////////////////////////////////////////////
254
255     /// Converts from `&Option<T>` to `Option<&T>`.
256     ///
257     /// # Examples
258     ///
259     /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
260     /// The [`map`] method takes the `self` argument by value, consuming the original,
261     /// so this technique uses `as_ref` to first take an `Option` to a reference
262     /// to the value inside the original.
263     ///
264     /// [`map`]: Option::map
265     /// [`String`]: ../../std/string/struct.String.html
266     ///
267     /// ```
268     /// let text: Option<String> = Some("Hello, world!".to_string());
269     /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
270     /// // then consume *that* with `map`, leaving `text` on the stack.
271     /// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
272     /// println!("still can print text: {:?}", text);
273     /// ```
274     #[inline]
275     #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
276     #[stable(feature = "rust1", since = "1.0.0")]
277     pub const fn as_ref(&self) -> Option<&T> {
278         match *self {
279             Some(ref x) => Some(x),
280             None => None,
281         }
282     }
283
284     /// Converts from `&mut Option<T>` to `Option<&mut T>`.
285     ///
286     /// # Examples
287     ///
288     /// ```
289     /// let mut x = Some(2);
290     /// match x.as_mut() {
291     ///     Some(v) => *v = 42,
292     ///     None => {},
293     /// }
294     /// assert_eq!(x, Some(42));
295     /// ```
296     #[inline]
297     #[stable(feature = "rust1", since = "1.0.0")]
298     pub fn as_mut(&mut self) -> Option<&mut T> {
299         match *self {
300             Some(ref mut x) => Some(x),
301             None => None,
302         }
303     }
304
305     /// Converts from [`Pin`]`<&Option<T>>` to `Option<`[`Pin`]`<&T>>`.
306     #[inline]
307     #[stable(feature = "pin", since = "1.33.0")]
308     pub fn as_pin_ref(self: Pin<&Self>) -> Option<Pin<&T>> {
309         // SAFETY: `x` is guaranteed to be pinned because it comes from `self`
310         // which is pinned.
311         unsafe { Pin::get_ref(self).as_ref().map(|x| Pin::new_unchecked(x)) }
312     }
313
314     /// Converts from [`Pin`]`<&mut Option<T>>` to `Option<`[`Pin`]`<&mut T>>`.
315     #[inline]
316     #[stable(feature = "pin", since = "1.33.0")]
317     pub fn as_pin_mut(self: Pin<&mut Self>) -> Option<Pin<&mut T>> {
318         // SAFETY: `get_unchecked_mut` is never used to move the `Option` inside `self`.
319         // `x` is guaranteed to be pinned because it comes from `self` which is pinned.
320         unsafe { Pin::get_unchecked_mut(self).as_mut().map(|x| Pin::new_unchecked(x)) }
321     }
322
323     /////////////////////////////////////////////////////////////////////////
324     // Getting to contained values
325     /////////////////////////////////////////////////////////////////////////
326
327     /// Returns the contained [`Some`] value, consuming the `self` value.
328     ///
329     /// # Panics
330     ///
331     /// Panics if the value is a [`None`] with a custom panic message provided by
332     /// `msg`.
333     ///
334     /// # Examples
335     ///
336     /// ```
337     /// let x = Some("value");
338     /// assert_eq!(x.expect("fruits are healthy"), "value");
339     /// ```
340     ///
341     /// ```should_panic
342     /// let x: Option<&str> = None;
343     /// x.expect("fruits are healthy"); // panics with `fruits are healthy`
344     /// ```
345     #[inline]
346     #[track_caller]
347     #[stable(feature = "rust1", since = "1.0.0")]
348     pub fn expect(self, msg: &str) -> T {
349         match self {
350             Some(val) => val,
351             None => expect_failed(msg),
352         }
353     }
354
355     /// Returns the contained [`Some`] value, consuming the `self` value.
356     ///
357     /// Because this function may panic, its use is generally discouraged.
358     /// Instead, prefer to use pattern matching and handle the [`None`]
359     /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
360     /// [`unwrap_or_default`].
361     ///
362     /// [`unwrap_or`]: Option::unwrap_or
363     /// [`unwrap_or_else`]: Option::unwrap_or_else
364     /// [`unwrap_or_default`]: Option::unwrap_or_default
365     ///
366     /// # Panics
367     ///
368     /// Panics if the self value equals [`None`].
369     ///
370     /// # Examples
371     ///
372     /// ```
373     /// let x = Some("air");
374     /// assert_eq!(x.unwrap(), "air");
375     /// ```
376     ///
377     /// ```should_panic
378     /// let x: Option<&str> = None;
379     /// assert_eq!(x.unwrap(), "air"); // fails
380     /// ```
381     #[inline]
382     #[track_caller]
383     #[stable(feature = "rust1", since = "1.0.0")]
384     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
385     pub const fn unwrap(self) -> T {
386         match self {
387             Some(val) => val,
388             None => panic!("called `Option::unwrap()` on a `None` value"),
389         }
390     }
391
392     /// Returns the contained [`Some`] value or a provided default.
393     ///
394     /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
395     /// the result of a function call, it is recommended to use [`unwrap_or_else`],
396     /// which is lazily evaluated.
397     ///
398     /// [`unwrap_or_else`]: Option::unwrap_or_else
399     ///
400     /// # Examples
401     ///
402     /// ```
403     /// assert_eq!(Some("car").unwrap_or("bike"), "car");
404     /// assert_eq!(None.unwrap_or("bike"), "bike");
405     /// ```
406     #[inline]
407     #[stable(feature = "rust1", since = "1.0.0")]
408     pub fn unwrap_or(self, default: T) -> T {
409         match self {
410             Some(x) => x,
411             None => default,
412         }
413     }
414
415     /// Returns the contained [`Some`] value or computes it from a closure.
416     ///
417     /// # Examples
418     ///
419     /// ```
420     /// let k = 10;
421     /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
422     /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
423     /// ```
424     #[inline]
425     #[stable(feature = "rust1", since = "1.0.0")]
426     pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
427         match self {
428             Some(x) => x,
429             None => f(),
430         }
431     }
432
433     /// Returns the contained [`Some`] value, consuming the `self` value,
434     /// without checking that the value is not [`None`].
435     ///
436     /// # Safety
437     ///
438     /// Calling this method on [`None`] is *[undefined behavior]*.
439     ///
440     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
441     ///
442     /// # Examples
443     ///
444     /// ```
445     /// #![feature(option_result_unwrap_unchecked)]
446     /// let x = Some("air");
447     /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air");
448     /// ```
449     ///
450     /// ```no_run
451     /// #![feature(option_result_unwrap_unchecked)]
452     /// let x: Option<&str> = None;
453     /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air"); // Undefined behavior!
454     /// ```
455     #[inline]
456     #[track_caller]
457     #[unstable(feature = "option_result_unwrap_unchecked", reason = "newly added", issue = "81383")]
458     pub unsafe fn unwrap_unchecked(self) -> T {
459         debug_assert!(self.is_some());
460         match self {
461             Some(val) => val,
462             // SAFETY: the safety contract must be upheld by the caller.
463             None => unsafe { hint::unreachable_unchecked() },
464         }
465     }
466
467     /////////////////////////////////////////////////////////////////////////
468     // Transforming contained values
469     /////////////////////////////////////////////////////////////////////////
470
471     /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
472     ///
473     /// # Examples
474     ///
475     /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, consuming the original:
476     ///
477     /// [`String`]: ../../std/string/struct.String.html
478     /// ```
479     /// let maybe_some_string = Some(String::from("Hello, World!"));
480     /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
481     /// let maybe_some_len = maybe_some_string.map(|s| s.len());
482     ///
483     /// assert_eq!(maybe_some_len, Some(13));
484     /// ```
485     #[inline]
486     #[stable(feature = "rust1", since = "1.0.0")]
487     pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
488         match self {
489             Some(x) => Some(f(x)),
490             None => None,
491         }
492     }
493
494     /// Returns the provided default result (if none),
495     /// or applies a function to the contained value (if any).
496     ///
497     /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
498     /// the result of a function call, it is recommended to use [`map_or_else`],
499     /// which is lazily evaluated.
500     ///
501     /// [`map_or_else`]: Option::map_or_else
502     ///
503     /// # Examples
504     ///
505     /// ```
506     /// let x = Some("foo");
507     /// assert_eq!(x.map_or(42, |v| v.len()), 3);
508     ///
509     /// let x: Option<&str> = None;
510     /// assert_eq!(x.map_or(42, |v| v.len()), 42);
511     /// ```
512     #[inline]
513     #[stable(feature = "rust1", since = "1.0.0")]
514     pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
515         match self {
516             Some(t) => f(t),
517             None => default,
518         }
519     }
520
521     /// Computes a default function result (if none), or
522     /// applies a different function to the contained value (if any).
523     ///
524     /// # Examples
525     ///
526     /// ```
527     /// let k = 21;
528     ///
529     /// let x = Some("foo");
530     /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
531     ///
532     /// let x: Option<&str> = None;
533     /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
534     /// ```
535     #[inline]
536     #[stable(feature = "rust1", since = "1.0.0")]
537     pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
538         match self {
539             Some(t) => f(t),
540             None => default(),
541         }
542     }
543
544     /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
545     /// [`Ok(v)`] and [`None`] to [`Err(err)`].
546     ///
547     /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
548     /// result of a function call, it is recommended to use [`ok_or_else`], which is
549     /// lazily evaluated.
550     ///
551     /// [`Ok(v)`]: Ok
552     /// [`Err(err)`]: Err
553     /// [`Some(v)`]: Some
554     /// [`ok_or_else`]: Option::ok_or_else
555     ///
556     /// # Examples
557     ///
558     /// ```
559     /// let x = Some("foo");
560     /// assert_eq!(x.ok_or(0), Ok("foo"));
561     ///
562     /// let x: Option<&str> = None;
563     /// assert_eq!(x.ok_or(0), Err(0));
564     /// ```
565     #[inline]
566     #[stable(feature = "rust1", since = "1.0.0")]
567     pub fn ok_or<E>(self, err: E) -> Result<T, E> {
568         match self {
569             Some(v) => Ok(v),
570             None => Err(err),
571         }
572     }
573
574     /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
575     /// [`Ok(v)`] and [`None`] to [`Err(err())`].
576     ///
577     /// [`Ok(v)`]: Ok
578     /// [`Err(err())`]: Err
579     /// [`Some(v)`]: Some
580     ///
581     /// # Examples
582     ///
583     /// ```
584     /// let x = Some("foo");
585     /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
586     ///
587     /// let x: Option<&str> = None;
588     /// assert_eq!(x.ok_or_else(|| 0), Err(0));
589     /// ```
590     #[inline]
591     #[stable(feature = "rust1", since = "1.0.0")]
592     pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
593         match self {
594             Some(v) => Ok(v),
595             None => Err(err()),
596         }
597     }
598
599     /////////////////////////////////////////////////////////////////////////
600     // Iterator constructors
601     /////////////////////////////////////////////////////////////////////////
602
603     /// Returns an iterator over the possibly contained value.
604     ///
605     /// # Examples
606     ///
607     /// ```
608     /// let x = Some(4);
609     /// assert_eq!(x.iter().next(), Some(&4));
610     ///
611     /// let x: Option<u32> = None;
612     /// assert_eq!(x.iter().next(), None);
613     /// ```
614     #[inline]
615     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
616     #[stable(feature = "rust1", since = "1.0.0")]
617     pub const fn iter(&self) -> Iter<'_, T> {
618         Iter { inner: Item { opt: self.as_ref() } }
619     }
620
621     /// Returns a mutable iterator over the possibly contained value.
622     ///
623     /// # Examples
624     ///
625     /// ```
626     /// let mut x = Some(4);
627     /// match x.iter_mut().next() {
628     ///     Some(v) => *v = 42,
629     ///     None => {},
630     /// }
631     /// assert_eq!(x, Some(42));
632     ///
633     /// let mut x: Option<u32> = None;
634     /// assert_eq!(x.iter_mut().next(), None);
635     /// ```
636     #[inline]
637     #[stable(feature = "rust1", since = "1.0.0")]
638     pub fn iter_mut(&mut self) -> IterMut<'_, T> {
639         IterMut { inner: Item { opt: self.as_mut() } }
640     }
641
642     /////////////////////////////////////////////////////////////////////////
643     // Boolean operations on the values, eager and lazy
644     /////////////////////////////////////////////////////////////////////////
645
646     /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
647     ///
648     /// # Examples
649     ///
650     /// ```
651     /// let x = Some(2);
652     /// let y: Option<&str> = None;
653     /// assert_eq!(x.and(y), None);
654     ///
655     /// let x: Option<u32> = None;
656     /// let y = Some("foo");
657     /// assert_eq!(x.and(y), None);
658     ///
659     /// let x = Some(2);
660     /// let y = Some("foo");
661     /// assert_eq!(x.and(y), Some("foo"));
662     ///
663     /// let x: Option<u32> = None;
664     /// let y: Option<&str> = None;
665     /// assert_eq!(x.and(y), None);
666     /// ```
667     #[inline]
668     #[stable(feature = "rust1", since = "1.0.0")]
669     pub fn and<U>(self, optb: Option<U>) -> Option<U> {
670         match self {
671             Some(_) => optb,
672             None => None,
673         }
674     }
675
676     /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
677     /// wrapped value and returns the result.
678     ///
679     /// Some languages call this operation flatmap.
680     ///
681     /// # Examples
682     ///
683     /// ```
684     /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
685     /// fn nope(_: u32) -> Option<u32> { None }
686     ///
687     /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
688     /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
689     /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
690     /// assert_eq!(None.and_then(sq).and_then(sq), None);
691     /// ```
692     #[inline]
693     #[stable(feature = "rust1", since = "1.0.0")]
694     pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> {
695         match self {
696             Some(x) => f(x),
697             None => None,
698         }
699     }
700
701     /// Returns [`None`] if the option is [`None`], otherwise calls `predicate`
702     /// with the wrapped value and returns:
703     ///
704     /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped
705     ///   value), and
706     /// - [`None`] if `predicate` returns `false`.
707     ///
708     /// This function works similar to [`Iterator::filter()`]. You can imagine
709     /// the `Option<T>` being an iterator over one or zero elements. `filter()`
710     /// lets you decide which elements to keep.
711     ///
712     /// # Examples
713     ///
714     /// ```rust
715     /// fn is_even(n: &i32) -> bool {
716     ///     n % 2 == 0
717     /// }
718     ///
719     /// assert_eq!(None.filter(is_even), None);
720     /// assert_eq!(Some(3).filter(is_even), None);
721     /// assert_eq!(Some(4).filter(is_even), Some(4));
722     /// ```
723     ///
724     /// [`Some(t)`]: Some
725     #[inline]
726     #[stable(feature = "option_filter", since = "1.27.0")]
727     pub fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Self {
728         if let Some(x) = self {
729             if predicate(&x) {
730                 return Some(x);
731             }
732         }
733         None
734     }
735
736     /// Returns the option if it contains a value, otherwise returns `optb`.
737     ///
738     /// Arguments passed to `or` are eagerly evaluated; if you are passing the
739     /// result of a function call, it is recommended to use [`or_else`], which is
740     /// lazily evaluated.
741     ///
742     /// [`or_else`]: Option::or_else
743     ///
744     /// # Examples
745     ///
746     /// ```
747     /// let x = Some(2);
748     /// let y = None;
749     /// assert_eq!(x.or(y), Some(2));
750     ///
751     /// let x = None;
752     /// let y = Some(100);
753     /// assert_eq!(x.or(y), Some(100));
754     ///
755     /// let x = Some(2);
756     /// let y = Some(100);
757     /// assert_eq!(x.or(y), Some(2));
758     ///
759     /// let x: Option<u32> = None;
760     /// let y = None;
761     /// assert_eq!(x.or(y), None);
762     /// ```
763     #[inline]
764     #[stable(feature = "rust1", since = "1.0.0")]
765     pub fn or(self, optb: Option<T>) -> Option<T> {
766         match self {
767             Some(_) => self,
768             None => optb,
769         }
770     }
771
772     /// Returns the option if it contains a value, otherwise calls `f` and
773     /// returns the result.
774     ///
775     /// # Examples
776     ///
777     /// ```
778     /// fn nobody() -> Option<&'static str> { None }
779     /// fn vikings() -> Option<&'static str> { Some("vikings") }
780     ///
781     /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
782     /// assert_eq!(None.or_else(vikings), Some("vikings"));
783     /// assert_eq!(None.or_else(nobody), None);
784     /// ```
785     #[inline]
786     #[stable(feature = "rust1", since = "1.0.0")]
787     pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> {
788         match self {
789             Some(_) => self,
790             None => f(),
791         }
792     }
793
794     /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`].
795     ///
796     /// # Examples
797     ///
798     /// ```
799     /// let x = Some(2);
800     /// let y: Option<u32> = None;
801     /// assert_eq!(x.xor(y), Some(2));
802     ///
803     /// let x: Option<u32> = None;
804     /// let y = Some(2);
805     /// assert_eq!(x.xor(y), Some(2));
806     ///
807     /// let x = Some(2);
808     /// let y = Some(2);
809     /// assert_eq!(x.xor(y), None);
810     ///
811     /// let x: Option<u32> = None;
812     /// let y: Option<u32> = None;
813     /// assert_eq!(x.xor(y), None);
814     /// ```
815     #[inline]
816     #[stable(feature = "option_xor", since = "1.37.0")]
817     pub fn xor(self, optb: Option<T>) -> Option<T> {
818         match (self, optb) {
819             (Some(a), None) => Some(a),
820             (None, Some(b)) => Some(b),
821             _ => None,
822         }
823     }
824
825     /////////////////////////////////////////////////////////////////////////
826     // Entry-like operations to insert a value and return a reference
827     /////////////////////////////////////////////////////////////////////////
828
829     /// Inserts `value` into the option then returns a mutable reference to it.
830     ///
831     /// If the option already contains a value, the old value is dropped.
832     ///
833     /// See also [`Option::get_or_insert`], which doesn't update the value if
834     /// the option already contains [`Some`].
835     ///
836     /// # Example
837     ///
838     /// ```
839     /// let mut opt = None;
840     /// let val = opt.insert(1);
841     /// assert_eq!(*val, 1);
842     /// assert_eq!(opt.unwrap(), 1);
843     /// let val = opt.insert(2);
844     /// assert_eq!(*val, 2);
845     /// *val = 3;
846     /// assert_eq!(opt.unwrap(), 3);
847     /// ```
848     #[inline]
849     #[stable(feature = "option_insert", since = "1.53.0")]
850     pub fn insert(&mut self, value: T) -> &mut T {
851         *self = Some(value);
852
853         match self {
854             Some(v) => v,
855             // SAFETY: the code above just filled the option
856             None => unsafe { hint::unreachable_unchecked() },
857         }
858     }
859
860     /// Inserts `value` into the option if it is [`None`], then
861     /// returns a mutable reference to the contained value.
862     ///
863     /// See also [`Option::insert`], which updates the value even if
864     /// the option already contains [`Some`].
865     ///
866     /// # Examples
867     ///
868     /// ```
869     /// let mut x = None;
870     ///
871     /// {
872     ///     let y: &mut u32 = x.get_or_insert(5);
873     ///     assert_eq!(y, &5);
874     ///
875     ///     *y = 7;
876     /// }
877     ///
878     /// assert_eq!(x, Some(7));
879     /// ```
880     #[inline]
881     #[stable(feature = "option_entry", since = "1.20.0")]
882     pub fn get_or_insert(&mut self, value: T) -> &mut T {
883         self.get_or_insert_with(|| value)
884     }
885
886     /// Inserts the default value into the option if it is [`None`], then
887     /// returns a mutable reference to the contained value.
888     ///
889     /// # Examples
890     ///
891     /// ```
892     /// #![feature(option_get_or_insert_default)]
893     ///
894     /// let mut x = None;
895     ///
896     /// {
897     ///     let y: &mut u32 = x.get_or_insert_default();
898     ///     assert_eq!(y, &0);
899     ///
900     ///     *y = 7;
901     /// }
902     ///
903     /// assert_eq!(x, Some(7));
904     /// ```
905     #[inline]
906     #[unstable(feature = "option_get_or_insert_default", issue = "82901")]
907     pub fn get_or_insert_default(&mut self) -> &mut T
908     where
909         T: Default,
910     {
911         self.get_or_insert_with(Default::default)
912     }
913
914     /// Inserts a value computed from `f` into the option if it is [`None`],
915     /// then returns a mutable reference to the contained value.
916     ///
917     /// # Examples
918     ///
919     /// ```
920     /// let mut x = None;
921     ///
922     /// {
923     ///     let y: &mut u32 = x.get_or_insert_with(|| 5);
924     ///     assert_eq!(y, &5);
925     ///
926     ///     *y = 7;
927     /// }
928     ///
929     /// assert_eq!(x, Some(7));
930     /// ```
931     #[inline]
932     #[stable(feature = "option_entry", since = "1.20.0")]
933     pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
934         if let None = *self {
935             *self = Some(f());
936         }
937
938         match self {
939             Some(v) => v,
940             // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
941             // variant in the code above.
942             None => unsafe { hint::unreachable_unchecked() },
943         }
944     }
945
946     /////////////////////////////////////////////////////////////////////////
947     // Misc
948     /////////////////////////////////////////////////////////////////////////
949
950     /// Takes the value out of the option, leaving a [`None`] in its place.
951     ///
952     /// # Examples
953     ///
954     /// ```
955     /// let mut x = Some(2);
956     /// let y = x.take();
957     /// assert_eq!(x, None);
958     /// assert_eq!(y, Some(2));
959     ///
960     /// let mut x: Option<u32> = None;
961     /// let y = x.take();
962     /// assert_eq!(x, None);
963     /// assert_eq!(y, None);
964     /// ```
965     #[inline]
966     #[stable(feature = "rust1", since = "1.0.0")]
967     pub fn take(&mut self) -> Option<T> {
968         mem::take(self)
969     }
970
971     /// Replaces the actual value in the option by the value given in parameter,
972     /// returning the old value if present,
973     /// leaving a [`Some`] in its place without deinitializing either one.
974     ///
975     /// # Examples
976     ///
977     /// ```
978     /// let mut x = Some(2);
979     /// let old = x.replace(5);
980     /// assert_eq!(x, Some(5));
981     /// assert_eq!(old, Some(2));
982     ///
983     /// let mut x = None;
984     /// let old = x.replace(3);
985     /// assert_eq!(x, Some(3));
986     /// assert_eq!(old, None);
987     /// ```
988     #[inline]
989     #[stable(feature = "option_replace", since = "1.31.0")]
990     pub fn replace(&mut self, value: T) -> Option<T> {
991         mem::replace(self, Some(value))
992     }
993
994     /// Zips `self` with another `Option`.
995     ///
996     /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some((s, o))`.
997     /// Otherwise, `None` is returned.
998     ///
999     /// # Examples
1000     ///
1001     /// ```
1002     /// let x = Some(1);
1003     /// let y = Some("hi");
1004     /// let z = None::<u8>;
1005     ///
1006     /// assert_eq!(x.zip(y), Some((1, "hi")));
1007     /// assert_eq!(x.zip(z), None);
1008     /// ```
1009     #[stable(feature = "option_zip_option", since = "1.46.0")]
1010     pub fn zip<U>(self, other: Option<U>) -> Option<(T, U)> {
1011         match (self, other) {
1012             (Some(a), Some(b)) => Some((a, b)),
1013             _ => None,
1014         }
1015     }
1016
1017     /// Zips `self` and another `Option` with function `f`.
1018     ///
1019     /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
1020     /// Otherwise, `None` is returned.
1021     ///
1022     /// # Examples
1023     ///
1024     /// ```
1025     /// #![feature(option_zip)]
1026     ///
1027     /// #[derive(Debug, PartialEq)]
1028     /// struct Point {
1029     ///     x: f64,
1030     ///     y: f64,
1031     /// }
1032     ///
1033     /// impl Point {
1034     ///     fn new(x: f64, y: f64) -> Self {
1035     ///         Self { x, y }
1036     ///     }
1037     /// }
1038     ///
1039     /// let x = Some(17.5);
1040     /// let y = Some(42.7);
1041     ///
1042     /// assert_eq!(x.zip_with(y, Point::new), Some(Point { x: 17.5, y: 42.7 }));
1043     /// assert_eq!(x.zip_with(None, Point::new), None);
1044     /// ```
1045     #[unstable(feature = "option_zip", issue = "70086")]
1046     pub fn zip_with<U, F, R>(self, other: Option<U>, f: F) -> Option<R>
1047     where
1048         F: FnOnce(T, U) -> R,
1049     {
1050         Some(f(self?, other?))
1051     }
1052 }
1053
1054 impl<T: Copy> Option<&T> {
1055     /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
1056     /// option.
1057     ///
1058     /// # Examples
1059     ///
1060     /// ```
1061     /// let x = 12;
1062     /// let opt_x = Some(&x);
1063     /// assert_eq!(opt_x, Some(&12));
1064     /// let copied = opt_x.copied();
1065     /// assert_eq!(copied, Some(12));
1066     /// ```
1067     #[stable(feature = "copied", since = "1.35.0")]
1068     pub fn copied(self) -> Option<T> {
1069         self.map(|&t| t)
1070     }
1071 }
1072
1073 impl<T: Copy> Option<&mut T> {
1074     /// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the
1075     /// option.
1076     ///
1077     /// # Examples
1078     ///
1079     /// ```
1080     /// let mut x = 12;
1081     /// let opt_x = Some(&mut x);
1082     /// assert_eq!(opt_x, Some(&mut 12));
1083     /// let copied = opt_x.copied();
1084     /// assert_eq!(copied, Some(12));
1085     /// ```
1086     #[stable(feature = "copied", since = "1.35.0")]
1087     pub fn copied(self) -> Option<T> {
1088         self.map(|&mut t| t)
1089     }
1090 }
1091
1092 impl<T: Clone> Option<&T> {
1093     /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
1094     /// option.
1095     ///
1096     /// # Examples
1097     ///
1098     /// ```
1099     /// let x = 12;
1100     /// let opt_x = Some(&x);
1101     /// assert_eq!(opt_x, Some(&12));
1102     /// let cloned = opt_x.cloned();
1103     /// assert_eq!(cloned, Some(12));
1104     /// ```
1105     #[stable(feature = "rust1", since = "1.0.0")]
1106     pub fn cloned(self) -> Option<T> {
1107         self.map(|t| t.clone())
1108     }
1109 }
1110
1111 impl<T: Clone> Option<&mut T> {
1112     /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
1113     /// option.
1114     ///
1115     /// # Examples
1116     ///
1117     /// ```
1118     /// let mut x = 12;
1119     /// let opt_x = Some(&mut x);
1120     /// assert_eq!(opt_x, Some(&mut 12));
1121     /// let cloned = opt_x.cloned();
1122     /// assert_eq!(cloned, Some(12));
1123     /// ```
1124     #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
1125     pub fn cloned(self) -> Option<T> {
1126         self.map(|t| t.clone())
1127     }
1128 }
1129
1130 impl<T: Default> Option<T> {
1131     /// Returns the contained [`Some`] value or a default
1132     ///
1133     /// Consumes the `self` argument then, if [`Some`], returns the contained
1134     /// value, otherwise if [`None`], returns the [default value] for that
1135     /// type.
1136     ///
1137     /// # Examples
1138     ///
1139     /// Converts a string to an integer, turning poorly-formed strings
1140     /// into 0 (the default value for integers). [`parse`] converts
1141     /// a string to any other type that implements [`FromStr`], returning
1142     /// [`None`] on error.
1143     ///
1144     /// ```
1145     /// let good_year_from_input = "1909";
1146     /// let bad_year_from_input = "190blarg";
1147     /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
1148     /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
1149     ///
1150     /// assert_eq!(1909, good_year);
1151     /// assert_eq!(0, bad_year);
1152     /// ```
1153     ///
1154     /// [default value]: Default::default
1155     /// [`parse`]: str::parse
1156     /// [`FromStr`]: crate::str::FromStr
1157     #[inline]
1158     #[stable(feature = "rust1", since = "1.0.0")]
1159     pub fn unwrap_or_default(self) -> T {
1160         match self {
1161             Some(x) => x,
1162             None => Default::default(),
1163         }
1164     }
1165 }
1166
1167 impl<T: Deref> Option<T> {
1168     /// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.
1169     ///
1170     /// Leaves the original Option in-place, creating a new one with a reference
1171     /// to the original one, additionally coercing the contents via [`Deref`].
1172     ///
1173     /// # Examples
1174     ///
1175     /// ```
1176     /// let x: Option<String> = Some("hey".to_owned());
1177     /// assert_eq!(x.as_deref(), Some("hey"));
1178     ///
1179     /// let x: Option<String> = None;
1180     /// assert_eq!(x.as_deref(), None);
1181     /// ```
1182     #[stable(feature = "option_deref", since = "1.40.0")]
1183     pub fn as_deref(&self) -> Option<&T::Target> {
1184         self.as_ref().map(|t| t.deref())
1185     }
1186 }
1187
1188 impl<T: DerefMut> Option<T> {
1189     /// Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`.
1190     ///
1191     /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to
1192     /// the inner type's `Deref::Target` type.
1193     ///
1194     /// # Examples
1195     ///
1196     /// ```
1197     /// let mut x: Option<String> = Some("hey".to_owned());
1198     /// assert_eq!(x.as_deref_mut().map(|x| {
1199     ///     x.make_ascii_uppercase();
1200     ///     x
1201     /// }), Some("HEY".to_owned().as_mut_str()));
1202     /// ```
1203     #[stable(feature = "option_deref", since = "1.40.0")]
1204     pub fn as_deref_mut(&mut self) -> Option<&mut T::Target> {
1205         self.as_mut().map(|t| t.deref_mut())
1206     }
1207 }
1208
1209 impl<T, E> Option<Result<T, E>> {
1210     /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`.
1211     ///
1212     /// [`None`] will be mapped to [`Ok`]`(`[`None`]`)`.
1213     /// [`Some`]`(`[`Ok`]`(_))` and [`Some`]`(`[`Err`]`(_))` will be mapped to
1214     /// [`Ok`]`(`[`Some`]`(_))` and [`Err`]`(_)`.
1215     ///
1216     /// # Examples
1217     ///
1218     /// ```
1219     /// #[derive(Debug, Eq, PartialEq)]
1220     /// struct SomeErr;
1221     ///
1222     /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1223     /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1224     /// assert_eq!(x, y.transpose());
1225     /// ```
1226     #[inline]
1227     #[stable(feature = "transpose_result", since = "1.33.0")]
1228     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1229     pub const fn transpose(self) -> Result<Option<T>, E> {
1230         match self {
1231             Some(Ok(x)) => Ok(Some(x)),
1232             Some(Err(e)) => Err(e),
1233             None => Ok(None),
1234         }
1235     }
1236 }
1237
1238 // This is a separate function to reduce the code size of .expect() itself.
1239 #[inline(never)]
1240 #[cold]
1241 #[track_caller]
1242 fn expect_failed(msg: &str) -> ! {
1243     panic!("{}", msg)
1244 }
1245
1246 /////////////////////////////////////////////////////////////////////////////
1247 // Trait implementations
1248 /////////////////////////////////////////////////////////////////////////////
1249
1250 #[stable(feature = "rust1", since = "1.0.0")]
1251 impl<T: Clone> Clone for Option<T> {
1252     #[inline]
1253     fn clone(&self) -> Self {
1254         match self {
1255             Some(x) => Some(x.clone()),
1256             None => None,
1257         }
1258     }
1259
1260     #[inline]
1261     fn clone_from(&mut self, source: &Self) {
1262         match (self, source) {
1263             (Some(to), Some(from)) => to.clone_from(from),
1264             (to, from) => *to = from.clone(),
1265         }
1266     }
1267 }
1268
1269 #[stable(feature = "rust1", since = "1.0.0")]
1270 impl<T> Default for Option<T> {
1271     /// Returns [`None`][Option::None].
1272     ///
1273     /// # Examples
1274     ///
1275     /// ```
1276     /// let opt: Option<u32> = Option::default();
1277     /// assert!(opt.is_none());
1278     /// ```
1279     #[inline]
1280     fn default() -> Option<T> {
1281         None
1282     }
1283 }
1284
1285 #[stable(feature = "rust1", since = "1.0.0")]
1286 impl<T> IntoIterator for Option<T> {
1287     type Item = T;
1288     type IntoIter = IntoIter<T>;
1289
1290     /// Returns a consuming iterator over the possibly contained value.
1291     ///
1292     /// # Examples
1293     ///
1294     /// ```
1295     /// let x = Some("string");
1296     /// let v: Vec<&str> = x.into_iter().collect();
1297     /// assert_eq!(v, ["string"]);
1298     ///
1299     /// let x = None;
1300     /// let v: Vec<&str> = x.into_iter().collect();
1301     /// assert!(v.is_empty());
1302     /// ```
1303     #[inline]
1304     fn into_iter(self) -> IntoIter<T> {
1305         IntoIter { inner: Item { opt: self } }
1306     }
1307 }
1308
1309 #[stable(since = "1.4.0", feature = "option_iter")]
1310 impl<'a, T> IntoIterator for &'a Option<T> {
1311     type Item = &'a T;
1312     type IntoIter = Iter<'a, T>;
1313
1314     fn into_iter(self) -> Iter<'a, T> {
1315         self.iter()
1316     }
1317 }
1318
1319 #[stable(since = "1.4.0", feature = "option_iter")]
1320 impl<'a, T> IntoIterator for &'a mut Option<T> {
1321     type Item = &'a mut T;
1322     type IntoIter = IterMut<'a, T>;
1323
1324     fn into_iter(self) -> IterMut<'a, T> {
1325         self.iter_mut()
1326     }
1327 }
1328
1329 #[stable(since = "1.12.0", feature = "option_from")]
1330 impl<T> From<T> for Option<T> {
1331     /// Copies `val` into a new `Some`.
1332     ///
1333     /// # Examples
1334     ///
1335     /// ```
1336     /// let o: Option<u8> = Option::from(67);
1337     ///
1338     /// assert_eq!(Some(67), o);
1339     /// ```
1340     fn from(val: T) -> Option<T> {
1341         Some(val)
1342     }
1343 }
1344
1345 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1346 impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
1347     /// Converts from `&Option<T>` to `Option<&T>`.
1348     ///
1349     /// # Examples
1350     ///
1351     /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
1352     /// The [`map`] method takes the `self` argument by value, consuming the original,
1353     /// so this technique uses `as_ref` to first take an `Option` to a reference
1354     /// to the value inside the original.
1355     ///
1356     /// [`map`]: Option::map
1357     /// [`String`]: ../../std/string/struct.String.html
1358     ///
1359     /// ```
1360     /// let s: Option<String> = Some(String::from("Hello, Rustaceans!"));
1361     /// let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());
1362     ///
1363     /// println!("Can still print s: {:?}", s);
1364     ///
1365     /// assert_eq!(o, Some(18));
1366     /// ```
1367     fn from(o: &'a Option<T>) -> Option<&'a T> {
1368         o.as_ref()
1369     }
1370 }
1371
1372 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1373 impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> {
1374     /// Converts from `&mut Option<T>` to `Option<&mut T>`
1375     ///
1376     /// # Examples
1377     ///
1378     /// ```
1379     /// let mut s = Some(String::from("Hello"));
1380     /// let o: Option<&mut String> = Option::from(&mut s);
1381     ///
1382     /// match o {
1383     ///     Some(t) => *t = String::from("Hello, Rustaceans!"),
1384     ///     None => (),
1385     /// }
1386     ///
1387     /// assert_eq!(s, Some(String::from("Hello, Rustaceans!")));
1388     /// ```
1389     fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
1390         o.as_mut()
1391     }
1392 }
1393
1394 /////////////////////////////////////////////////////////////////////////////
1395 // The Option Iterators
1396 /////////////////////////////////////////////////////////////////////////////
1397
1398 #[derive(Clone, Debug)]
1399 struct Item<A> {
1400     opt: Option<A>,
1401 }
1402
1403 impl<A> Iterator for Item<A> {
1404     type Item = A;
1405
1406     #[inline]
1407     fn next(&mut self) -> Option<A> {
1408         self.opt.take()
1409     }
1410
1411     #[inline]
1412     fn size_hint(&self) -> (usize, Option<usize>) {
1413         match self.opt {
1414             Some(_) => (1, Some(1)),
1415             None => (0, Some(0)),
1416         }
1417     }
1418 }
1419
1420 impl<A> DoubleEndedIterator for Item<A> {
1421     #[inline]
1422     fn next_back(&mut self) -> Option<A> {
1423         self.opt.take()
1424     }
1425 }
1426
1427 impl<A> ExactSizeIterator for Item<A> {}
1428 impl<A> FusedIterator for Item<A> {}
1429 unsafe impl<A> TrustedLen for Item<A> {}
1430
1431 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
1432 ///
1433 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1434 ///
1435 /// This `struct` is created by the [`Option::iter`] function.
1436 #[stable(feature = "rust1", since = "1.0.0")]
1437 #[derive(Debug)]
1438 pub struct Iter<'a, A: 'a> {
1439     inner: Item<&'a A>,
1440 }
1441
1442 #[stable(feature = "rust1", since = "1.0.0")]
1443 impl<'a, A> Iterator for Iter<'a, A> {
1444     type Item = &'a A;
1445
1446     #[inline]
1447     fn next(&mut self) -> Option<&'a A> {
1448         self.inner.next()
1449     }
1450     #[inline]
1451     fn size_hint(&self) -> (usize, Option<usize>) {
1452         self.inner.size_hint()
1453     }
1454 }
1455
1456 #[stable(feature = "rust1", since = "1.0.0")]
1457 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
1458     #[inline]
1459     fn next_back(&mut self) -> Option<&'a A> {
1460         self.inner.next_back()
1461     }
1462 }
1463
1464 #[stable(feature = "rust1", since = "1.0.0")]
1465 impl<A> ExactSizeIterator for Iter<'_, A> {}
1466
1467 #[stable(feature = "fused", since = "1.26.0")]
1468 impl<A> FusedIterator for Iter<'_, A> {}
1469
1470 #[unstable(feature = "trusted_len", issue = "37572")]
1471 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1472
1473 #[stable(feature = "rust1", since = "1.0.0")]
1474 impl<A> Clone for Iter<'_, A> {
1475     #[inline]
1476     fn clone(&self) -> Self {
1477         Iter { inner: self.inner.clone() }
1478     }
1479 }
1480
1481 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
1482 ///
1483 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1484 ///
1485 /// This `struct` is created by the [`Option::iter_mut`] function.
1486 #[stable(feature = "rust1", since = "1.0.0")]
1487 #[derive(Debug)]
1488 pub struct IterMut<'a, A: 'a> {
1489     inner: Item<&'a mut A>,
1490 }
1491
1492 #[stable(feature = "rust1", since = "1.0.0")]
1493 impl<'a, A> Iterator for IterMut<'a, A> {
1494     type Item = &'a mut A;
1495
1496     #[inline]
1497     fn next(&mut self) -> Option<&'a mut A> {
1498         self.inner.next()
1499     }
1500     #[inline]
1501     fn size_hint(&self) -> (usize, Option<usize>) {
1502         self.inner.size_hint()
1503     }
1504 }
1505
1506 #[stable(feature = "rust1", since = "1.0.0")]
1507 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
1508     #[inline]
1509     fn next_back(&mut self) -> Option<&'a mut A> {
1510         self.inner.next_back()
1511     }
1512 }
1513
1514 #[stable(feature = "rust1", since = "1.0.0")]
1515 impl<A> ExactSizeIterator for IterMut<'_, A> {}
1516
1517 #[stable(feature = "fused", since = "1.26.0")]
1518 impl<A> FusedIterator for IterMut<'_, A> {}
1519 #[unstable(feature = "trusted_len", issue = "37572")]
1520 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1521
1522 /// An iterator over the value in [`Some`] variant of an [`Option`].
1523 ///
1524 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1525 ///
1526 /// This `struct` is created by the [`Option::into_iter`] function.
1527 #[derive(Clone, Debug)]
1528 #[stable(feature = "rust1", since = "1.0.0")]
1529 pub struct IntoIter<A> {
1530     inner: Item<A>,
1531 }
1532
1533 #[stable(feature = "rust1", since = "1.0.0")]
1534 impl<A> Iterator for IntoIter<A> {
1535     type Item = A;
1536
1537     #[inline]
1538     fn next(&mut self) -> Option<A> {
1539         self.inner.next()
1540     }
1541     #[inline]
1542     fn size_hint(&self) -> (usize, Option<usize>) {
1543         self.inner.size_hint()
1544     }
1545 }
1546
1547 #[stable(feature = "rust1", since = "1.0.0")]
1548 impl<A> DoubleEndedIterator for IntoIter<A> {
1549     #[inline]
1550     fn next_back(&mut self) -> Option<A> {
1551         self.inner.next_back()
1552     }
1553 }
1554
1555 #[stable(feature = "rust1", since = "1.0.0")]
1556 impl<A> ExactSizeIterator for IntoIter<A> {}
1557
1558 #[stable(feature = "fused", since = "1.26.0")]
1559 impl<A> FusedIterator for IntoIter<A> {}
1560
1561 #[unstable(feature = "trusted_len", issue = "37572")]
1562 unsafe impl<A> TrustedLen for IntoIter<A> {}
1563
1564 /////////////////////////////////////////////////////////////////////////////
1565 // FromIterator
1566 /////////////////////////////////////////////////////////////////////////////
1567
1568 #[stable(feature = "rust1", since = "1.0.0")]
1569 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
1570     /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
1571     /// no further elements are taken, and the [`None`][Option::None] is
1572     /// returned. Should no [`None`][Option::None] occur, a container with the
1573     /// values of each [`Option`] is returned.
1574     ///
1575     /// # Examples
1576     ///
1577     /// Here is an example which increments every integer in a vector.
1578     /// We use the checked variant of `add` that returns `None` when the
1579     /// calculation would result in an overflow.
1580     ///
1581     /// ```
1582     /// let items = vec![0_u16, 1, 2];
1583     ///
1584     /// let res: Option<Vec<u16>> = items
1585     ///     .iter()
1586     ///     .map(|x| x.checked_add(1))
1587     ///     .collect();
1588     ///
1589     /// assert_eq!(res, Some(vec![1, 2, 3]));
1590     /// ```
1591     ///
1592     /// As you can see, this will return the expected, valid items.
1593     ///
1594     /// Here is another example that tries to subtract one from another list
1595     /// of integers, this time checking for underflow:
1596     ///
1597     /// ```
1598     /// let items = vec![2_u16, 1, 0];
1599     ///
1600     /// let res: Option<Vec<u16>> = items
1601     ///     .iter()
1602     ///     .map(|x| x.checked_sub(1))
1603     ///     .collect();
1604     ///
1605     /// assert_eq!(res, None);
1606     /// ```
1607     ///
1608     /// Since the last element is zero, it would underflow. Thus, the resulting
1609     /// value is `None`.
1610     ///
1611     /// Here is a variation on the previous example, showing that no
1612     /// further elements are taken from `iter` after the first `None`.
1613     ///
1614     /// ```
1615     /// let items = vec![3_u16, 2, 1, 10];
1616     ///
1617     /// let mut shared = 0;
1618     ///
1619     /// let res: Option<Vec<u16>> = items
1620     ///     .iter()
1621     ///     .map(|x| { shared += x; x.checked_sub(2) })
1622     ///     .collect();
1623     ///
1624     /// assert_eq!(res, None);
1625     /// assert_eq!(shared, 6);
1626     /// ```
1627     ///
1628     /// Since the third element caused an underflow, no further elements were taken,
1629     /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1630     #[inline]
1631     fn from_iter<I: IntoIterator<Item = Option<A>>>(iter: I) -> Option<V> {
1632         // FIXME(#11084): This could be replaced with Iterator::scan when this
1633         // performance bug is closed.
1634
1635         iter.into_iter().map(|x| x.ok_or(())).collect::<Result<_, _>>().ok()
1636     }
1637 }
1638
1639 /// The error type that results from applying the try operator (`?`) to a `None` value. If you wish
1640 /// to allow `x?` (where `x` is an `Option<T>`) to be converted into your error type, you can
1641 /// implement `impl From<NoneError>` for `YourErrorType`. In that case, `x?` within a function that
1642 /// returns `Result<_, YourErrorType>` will translate a `None` value into an `Err` result.
1643 #[rustc_diagnostic_item = "none_error"]
1644 #[unstable(feature = "try_trait", issue = "42327")]
1645 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
1646 #[cfg(bootstrap)]
1647 pub struct NoneError;
1648
1649 #[unstable(feature = "try_trait", issue = "42327")]
1650 #[cfg(bootstrap)]
1651 impl<T> ops::TryV1 for Option<T> {
1652     type Output = T;
1653     type Error = NoneError;
1654
1655     #[inline]
1656     fn into_result(self) -> Result<T, NoneError> {
1657         self.ok_or(NoneError)
1658     }
1659
1660     #[inline]
1661     fn from_ok(v: T) -> Self {
1662         Some(v)
1663     }
1664
1665     #[inline]
1666     fn from_error(_: NoneError) -> Self {
1667         None
1668     }
1669 }
1670
1671 #[unstable(feature = "try_trait_v2", issue = "84277")]
1672 impl<T> ops::TryV2 for Option<T> {
1673     type Output = T;
1674     type Residual = Option<convert::Infallible>;
1675
1676     #[inline]
1677     fn from_output(output: Self::Output) -> Self {
1678         Some(output)
1679     }
1680
1681     #[inline]
1682     fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
1683         match self {
1684             Some(v) => ControlFlow::Continue(v),
1685             None => ControlFlow::Break(None),
1686         }
1687     }
1688 }
1689
1690 #[unstable(feature = "try_trait_v2", issue = "84277")]
1691 impl<T> ops::FromResidual for Option<T> {
1692     #[inline]
1693     fn from_residual(residual: Option<convert::Infallible>) -> Self {
1694         match residual {
1695             None => None,
1696         }
1697     }
1698 }
1699
1700 impl<T> Option<Option<T>> {
1701     /// Converts from `Option<Option<T>>` to `Option<T>`
1702     ///
1703     /// # Examples
1704     ///
1705     /// Basic usage:
1706     ///
1707     /// ```
1708     /// let x: Option<Option<u32>> = Some(Some(6));
1709     /// assert_eq!(Some(6), x.flatten());
1710     ///
1711     /// let x: Option<Option<u32>> = Some(None);
1712     /// assert_eq!(None, x.flatten());
1713     ///
1714     /// let x: Option<Option<u32>> = None;
1715     /// assert_eq!(None, x.flatten());
1716     /// ```
1717     ///
1718     /// Flattening only removes one level of nesting at a time:
1719     ///
1720     /// ```
1721     /// let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
1722     /// assert_eq!(Some(Some(6)), x.flatten());
1723     /// assert_eq!(Some(6), x.flatten().flatten());
1724     /// ```
1725     #[inline]
1726     #[stable(feature = "option_flattening", since = "1.40.0")]
1727     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1728     pub const fn flatten(self) -> Option<T> {
1729         match self {
1730             Some(inner) => inner,
1731             None => None,
1732         }
1733     }
1734 }