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