]> git.lizzy.rs Git - rust.git/blob - library/core/src/option.rs
Auto merge of #79113 - andjo403:raw_vec_ptr, r=m-ou-se
[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     /////////////////////////////////////////////////////////////////////////
432     // Transforming contained values
433     /////////////////////////////////////////////////////////////////////////
434
435     /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
436     ///
437     /// # Examples
438     ///
439     /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, consuming the original:
440     ///
441     /// [`String`]: ../../std/string/struct.String.html
442     /// ```
443     /// let maybe_some_string = Some(String::from("Hello, World!"));
444     /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
445     /// let maybe_some_len = maybe_some_string.map(|s| s.len());
446     ///
447     /// assert_eq!(maybe_some_len, Some(13));
448     /// ```
449     #[inline]
450     #[stable(feature = "rust1", since = "1.0.0")]
451     pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
452         match self {
453             Some(x) => Some(f(x)),
454             None => None,
455         }
456     }
457
458     /// Applies a function to the contained value (if any),
459     /// or returns the provided default (if not).
460     ///
461     /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
462     /// the result of a function call, it is recommended to use [`map_or_else`],
463     /// which is lazily evaluated.
464     ///
465     /// [`map_or_else`]: Option::map_or_else
466     ///
467     /// # Examples
468     ///
469     /// ```
470     /// let x = Some("foo");
471     /// assert_eq!(x.map_or(42, |v| v.len()), 3);
472     ///
473     /// let x: Option<&str> = None;
474     /// assert_eq!(x.map_or(42, |v| v.len()), 42);
475     /// ```
476     #[inline]
477     #[stable(feature = "rust1", since = "1.0.0")]
478     pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
479         match self {
480             Some(t) => f(t),
481             None => default,
482         }
483     }
484
485     /// Applies a function to the contained value (if any),
486     /// or computes a default (if not).
487     ///
488     /// # Examples
489     ///
490     /// ```
491     /// let k = 21;
492     ///
493     /// let x = Some("foo");
494     /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
495     ///
496     /// let x: Option<&str> = None;
497     /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
498     /// ```
499     #[inline]
500     #[stable(feature = "rust1", since = "1.0.0")]
501     pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
502         match self {
503             Some(t) => f(t),
504             None => default(),
505         }
506     }
507
508     /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
509     /// [`Ok(v)`] and [`None`] to [`Err(err)`].
510     ///
511     /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
512     /// result of a function call, it is recommended to use [`ok_or_else`], which is
513     /// lazily evaluated.
514     ///
515     /// [`Ok(v)`]: Ok
516     /// [`Err(err)`]: Err
517     /// [`Some(v)`]: Some
518     /// [`ok_or_else`]: Option::ok_or_else
519     ///
520     /// # Examples
521     ///
522     /// ```
523     /// let x = Some("foo");
524     /// assert_eq!(x.ok_or(0), Ok("foo"));
525     ///
526     /// let x: Option<&str> = None;
527     /// assert_eq!(x.ok_or(0), Err(0));
528     /// ```
529     #[inline]
530     #[stable(feature = "rust1", since = "1.0.0")]
531     pub fn ok_or<E>(self, err: E) -> Result<T, E> {
532         match self {
533             Some(v) => Ok(v),
534             None => Err(err),
535         }
536     }
537
538     /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
539     /// [`Ok(v)`] and [`None`] to [`Err(err())`].
540     ///
541     /// [`Ok(v)`]: Ok
542     /// [`Err(err())`]: Err
543     /// [`Some(v)`]: Some
544     ///
545     /// # Examples
546     ///
547     /// ```
548     /// let x = Some("foo");
549     /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
550     ///
551     /// let x: Option<&str> = None;
552     /// assert_eq!(x.ok_or_else(|| 0), Err(0));
553     /// ```
554     #[inline]
555     #[stable(feature = "rust1", since = "1.0.0")]
556     pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
557         match self {
558             Some(v) => Ok(v),
559             None => Err(err()),
560         }
561     }
562
563     /// Inserts `value` into the option then returns a mutable reference to it.
564     ///
565     /// If the option already contains a value, the old value is dropped.
566     ///
567     /// # Example
568     ///
569     /// ```
570     /// #![feature(option_insert)]
571     ///
572     /// let mut opt = None;
573     /// let val = opt.insert(1);
574     /// assert_eq!(*val, 1);
575     /// assert_eq!(opt.unwrap(), 1);
576     /// let val = opt.insert(2);
577     /// assert_eq!(*val, 2);
578     /// *val = 3;
579     /// assert_eq!(opt.unwrap(), 3);
580     /// ```
581     #[inline]
582     #[unstable(feature = "option_insert", reason = "newly added", issue = "78271")]
583     pub fn insert(&mut self, value: T) -> &mut T {
584         *self = Some(value);
585
586         match self {
587             Some(v) => v,
588             // SAFETY: the code above just filled the option
589             None => unsafe { hint::unreachable_unchecked() },
590         }
591     }
592
593     /////////////////////////////////////////////////////////////////////////
594     // Iterator constructors
595     /////////////////////////////////////////////////////////////////////////
596
597     /// Returns an iterator over the possibly contained value.
598     ///
599     /// # Examples
600     ///
601     /// ```
602     /// let x = Some(4);
603     /// assert_eq!(x.iter().next(), Some(&4));
604     ///
605     /// let x: Option<u32> = None;
606     /// assert_eq!(x.iter().next(), None);
607     /// ```
608     #[inline]
609     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
610     #[stable(feature = "rust1", since = "1.0.0")]
611     pub const fn iter(&self) -> Iter<'_, T> {
612         Iter { inner: Item { opt: self.as_ref() } }
613     }
614
615     /// Returns a mutable iterator over the possibly contained value.
616     ///
617     /// # Examples
618     ///
619     /// ```
620     /// let mut x = Some(4);
621     /// match x.iter_mut().next() {
622     ///     Some(v) => *v = 42,
623     ///     None => {},
624     /// }
625     /// assert_eq!(x, Some(42));
626     ///
627     /// let mut x: Option<u32> = None;
628     /// assert_eq!(x.iter_mut().next(), None);
629     /// ```
630     #[inline]
631     #[stable(feature = "rust1", since = "1.0.0")]
632     pub fn iter_mut(&mut self) -> IterMut<'_, T> {
633         IterMut { inner: Item { opt: self.as_mut() } }
634     }
635
636     /////////////////////////////////////////////////////////////////////////
637     // Boolean operations on the values, eager and lazy
638     /////////////////////////////////////////////////////////////////////////
639
640     /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
641     ///
642     /// # Examples
643     ///
644     /// ```
645     /// let x = Some(2);
646     /// let y: Option<&str> = None;
647     /// assert_eq!(x.and(y), None);
648     ///
649     /// let x: Option<u32> = None;
650     /// let y = Some("foo");
651     /// assert_eq!(x.and(y), None);
652     ///
653     /// let x = Some(2);
654     /// let y = Some("foo");
655     /// assert_eq!(x.and(y), Some("foo"));
656     ///
657     /// let x: Option<u32> = None;
658     /// let y: Option<&str> = None;
659     /// assert_eq!(x.and(y), None);
660     /// ```
661     #[inline]
662     #[stable(feature = "rust1", since = "1.0.0")]
663     pub fn and<U>(self, optb: Option<U>) -> Option<U> {
664         match self {
665             Some(_) => optb,
666             None => None,
667         }
668     }
669
670     /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
671     /// wrapped value and returns the result.
672     ///
673     /// Some languages call this operation flatmap.
674     ///
675     /// # Examples
676     ///
677     /// ```
678     /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
679     /// fn nope(_: u32) -> Option<u32> { None }
680     ///
681     /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
682     /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
683     /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
684     /// assert_eq!(None.and_then(sq).and_then(sq), None);
685     /// ```
686     #[inline]
687     #[stable(feature = "rust1", since = "1.0.0")]
688     pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> {
689         match self {
690             Some(x) => f(x),
691             None => None,
692         }
693     }
694
695     /// Returns [`None`] if the option is [`None`], otherwise calls `predicate`
696     /// with the wrapped value and returns:
697     ///
698     /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped
699     ///   value), and
700     /// - [`None`] if `predicate` returns `false`.
701     ///
702     /// This function works similar to [`Iterator::filter()`]. You can imagine
703     /// the `Option<T>` being an iterator over one or zero elements. `filter()`
704     /// lets you decide which elements to keep.
705     ///
706     /// # Examples
707     ///
708     /// ```rust
709     /// fn is_even(n: &i32) -> bool {
710     ///     n % 2 == 0
711     /// }
712     ///
713     /// assert_eq!(None.filter(is_even), None);
714     /// assert_eq!(Some(3).filter(is_even), None);
715     /// assert_eq!(Some(4).filter(is_even), Some(4));
716     /// ```
717     ///
718     /// [`Some(t)`]: Some
719     #[inline]
720     #[stable(feature = "option_filter", since = "1.27.0")]
721     pub fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Self {
722         if let Some(x) = self {
723             if predicate(&x) {
724                 return Some(x);
725             }
726         }
727         None
728     }
729
730     /// Returns the option if it contains a value, otherwise returns `optb`.
731     ///
732     /// Arguments passed to `or` are eagerly evaluated; if you are passing the
733     /// result of a function call, it is recommended to use [`or_else`], which is
734     /// lazily evaluated.
735     ///
736     /// [`or_else`]: Option::or_else
737     ///
738     /// # Examples
739     ///
740     /// ```
741     /// let x = Some(2);
742     /// let y = None;
743     /// assert_eq!(x.or(y), Some(2));
744     ///
745     /// let x = None;
746     /// let y = Some(100);
747     /// assert_eq!(x.or(y), Some(100));
748     ///
749     /// let x = Some(2);
750     /// let y = Some(100);
751     /// assert_eq!(x.or(y), Some(2));
752     ///
753     /// let x: Option<u32> = None;
754     /// let y = None;
755     /// assert_eq!(x.or(y), None);
756     /// ```
757     #[inline]
758     #[stable(feature = "rust1", since = "1.0.0")]
759     pub fn or(self, optb: Option<T>) -> Option<T> {
760         match self {
761             Some(_) => self,
762             None => optb,
763         }
764     }
765
766     /// Returns the option if it contains a value, otherwise calls `f` and
767     /// returns the result.
768     ///
769     /// # Examples
770     ///
771     /// ```
772     /// fn nobody() -> Option<&'static str> { None }
773     /// fn vikings() -> Option<&'static str> { Some("vikings") }
774     ///
775     /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
776     /// assert_eq!(None.or_else(vikings), Some("vikings"));
777     /// assert_eq!(None.or_else(nobody), None);
778     /// ```
779     #[inline]
780     #[stable(feature = "rust1", since = "1.0.0")]
781     pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> {
782         match self {
783             Some(_) => self,
784             None => f(),
785         }
786     }
787
788     /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`].
789     ///
790     /// # Examples
791     ///
792     /// ```
793     /// let x = Some(2);
794     /// let y: Option<u32> = None;
795     /// assert_eq!(x.xor(y), Some(2));
796     ///
797     /// let x: Option<u32> = None;
798     /// let y = Some(2);
799     /// assert_eq!(x.xor(y), Some(2));
800     ///
801     /// let x = Some(2);
802     /// let y = Some(2);
803     /// assert_eq!(x.xor(y), None);
804     ///
805     /// let x: Option<u32> = None;
806     /// let y: Option<u32> = None;
807     /// assert_eq!(x.xor(y), None);
808     /// ```
809     #[inline]
810     #[stable(feature = "option_xor", since = "1.37.0")]
811     pub fn xor(self, optb: Option<T>) -> Option<T> {
812         match (self, optb) {
813             (Some(a), None) => Some(a),
814             (None, Some(b)) => Some(b),
815             _ => None,
816         }
817     }
818
819     /////////////////////////////////////////////////////////////////////////
820     // Entry-like operations to insert if None and return a reference
821     /////////////////////////////////////////////////////////////////////////
822
823     /// Inserts `value` into the option if it is [`None`], then
824     /// returns a mutable reference to the contained value.
825     ///
826     /// # Examples
827     ///
828     /// ```
829     /// let mut x = None;
830     ///
831     /// {
832     ///     let y: &mut u32 = x.get_or_insert(5);
833     ///     assert_eq!(y, &5);
834     ///
835     ///     *y = 7;
836     /// }
837     ///
838     /// assert_eq!(x, Some(7));
839     /// ```
840     #[inline]
841     #[stable(feature = "option_entry", since = "1.20.0")]
842     pub fn get_or_insert(&mut self, value: T) -> &mut T {
843         self.get_or_insert_with(|| value)
844     }
845
846     /// Inserts a value computed from `f` into the option if it is [`None`],
847     /// then returns a mutable reference to the contained value.
848     ///
849     /// # Examples
850     ///
851     /// ```
852     /// let mut x = None;
853     ///
854     /// {
855     ///     let y: &mut u32 = x.get_or_insert_with(|| 5);
856     ///     assert_eq!(y, &5);
857     ///
858     ///     *y = 7;
859     /// }
860     ///
861     /// assert_eq!(x, Some(7));
862     /// ```
863     #[inline]
864     #[stable(feature = "option_entry", since = "1.20.0")]
865     pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
866         if let None = *self {
867             *self = Some(f());
868         }
869
870         match self {
871             Some(v) => v,
872             // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
873             // variant in the code above.
874             None => unsafe { hint::unreachable_unchecked() },
875         }
876     }
877
878     /////////////////////////////////////////////////////////////////////////
879     // Misc
880     /////////////////////////////////////////////////////////////////////////
881
882     /// Takes the value out of the option, leaving a [`None`] in its place.
883     ///
884     /// # Examples
885     ///
886     /// ```
887     /// let mut x = Some(2);
888     /// let y = x.take();
889     /// assert_eq!(x, None);
890     /// assert_eq!(y, Some(2));
891     ///
892     /// let mut x: Option<u32> = None;
893     /// let y = x.take();
894     /// assert_eq!(x, None);
895     /// assert_eq!(y, None);
896     /// ```
897     #[inline]
898     #[stable(feature = "rust1", since = "1.0.0")]
899     pub fn take(&mut self) -> Option<T> {
900         mem::take(self)
901     }
902
903     /// Replaces the actual value in the option by the value given in parameter,
904     /// returning the old value if present,
905     /// leaving a [`Some`] in its place without deinitializing either one.
906     ///
907     /// # Examples
908     ///
909     /// ```
910     /// let mut x = Some(2);
911     /// let old = x.replace(5);
912     /// assert_eq!(x, Some(5));
913     /// assert_eq!(old, Some(2));
914     ///
915     /// let mut x = None;
916     /// let old = x.replace(3);
917     /// assert_eq!(x, Some(3));
918     /// assert_eq!(old, None);
919     /// ```
920     #[inline]
921     #[stable(feature = "option_replace", since = "1.31.0")]
922     pub fn replace(&mut self, value: T) -> Option<T> {
923         mem::replace(self, Some(value))
924     }
925
926     /// Zips `self` with another `Option`.
927     ///
928     /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some((s, o))`.
929     /// Otherwise, `None` is returned.
930     ///
931     /// # Examples
932     ///
933     /// ```
934     /// let x = Some(1);
935     /// let y = Some("hi");
936     /// let z = None::<u8>;
937     ///
938     /// assert_eq!(x.zip(y), Some((1, "hi")));
939     /// assert_eq!(x.zip(z), None);
940     /// ```
941     #[stable(feature = "option_zip_option", since = "1.46.0")]
942     pub fn zip<U>(self, other: Option<U>) -> Option<(T, U)> {
943         match (self, other) {
944             (Some(a), Some(b)) => Some((a, b)),
945             _ => None,
946         }
947     }
948
949     /// Zips `self` and another `Option` with function `f`.
950     ///
951     /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
952     /// Otherwise, `None` is returned.
953     ///
954     /// # Examples
955     ///
956     /// ```
957     /// #![feature(option_zip)]
958     ///
959     /// #[derive(Debug, PartialEq)]
960     /// struct Point {
961     ///     x: f64,
962     ///     y: f64,
963     /// }
964     ///
965     /// impl Point {
966     ///     fn new(x: f64, y: f64) -> Self {
967     ///         Self { x, y }
968     ///     }
969     /// }
970     ///
971     /// let x = Some(17.5);
972     /// let y = Some(42.7);
973     ///
974     /// assert_eq!(x.zip_with(y, Point::new), Some(Point { x: 17.5, y: 42.7 }));
975     /// assert_eq!(x.zip_with(None, Point::new), None);
976     /// ```
977     #[unstable(feature = "option_zip", issue = "70086")]
978     pub fn zip_with<U, F, R>(self, other: Option<U>, f: F) -> Option<R>
979     where
980         F: FnOnce(T, U) -> R,
981     {
982         Some(f(self?, other?))
983     }
984 }
985
986 impl<T: Copy> Option<&T> {
987     /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
988     /// option.
989     ///
990     /// # Examples
991     ///
992     /// ```
993     /// let x = 12;
994     /// let opt_x = Some(&x);
995     /// assert_eq!(opt_x, Some(&12));
996     /// let copied = opt_x.copied();
997     /// assert_eq!(copied, Some(12));
998     /// ```
999     #[stable(feature = "copied", since = "1.35.0")]
1000     pub fn copied(self) -> Option<T> {
1001         self.map(|&t| t)
1002     }
1003 }
1004
1005 impl<T: Copy> Option<&mut T> {
1006     /// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the
1007     /// option.
1008     ///
1009     /// # Examples
1010     ///
1011     /// ```
1012     /// let mut x = 12;
1013     /// let opt_x = Some(&mut x);
1014     /// assert_eq!(opt_x, Some(&mut 12));
1015     /// let copied = opt_x.copied();
1016     /// assert_eq!(copied, Some(12));
1017     /// ```
1018     #[stable(feature = "copied", since = "1.35.0")]
1019     pub fn copied(self) -> Option<T> {
1020         self.map(|&mut t| t)
1021     }
1022 }
1023
1024 impl<T: Clone> Option<&T> {
1025     /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
1026     /// option.
1027     ///
1028     /// # Examples
1029     ///
1030     /// ```
1031     /// let x = 12;
1032     /// let opt_x = Some(&x);
1033     /// assert_eq!(opt_x, Some(&12));
1034     /// let cloned = opt_x.cloned();
1035     /// assert_eq!(cloned, Some(12));
1036     /// ```
1037     #[stable(feature = "rust1", since = "1.0.0")]
1038     pub fn cloned(self) -> Option<T> {
1039         self.map(|t| t.clone())
1040     }
1041 }
1042
1043 impl<T: Clone> Option<&mut T> {
1044     /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
1045     /// option.
1046     ///
1047     /// # Examples
1048     ///
1049     /// ```
1050     /// let mut x = 12;
1051     /// let opt_x = Some(&mut x);
1052     /// assert_eq!(opt_x, Some(&mut 12));
1053     /// let cloned = opt_x.cloned();
1054     /// assert_eq!(cloned, Some(12));
1055     /// ```
1056     #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
1057     pub fn cloned(self) -> Option<T> {
1058         self.map(|t| t.clone())
1059     }
1060 }
1061
1062 impl<T: fmt::Debug> Option<T> {
1063     /// Consumes `self` while expecting [`None`] and returning nothing.
1064     ///
1065     /// # Panics
1066     ///
1067     /// Panics if the value is a [`Some`], with a panic message including the
1068     /// passed message, and the content of the [`Some`].
1069     ///
1070     /// # Examples
1071     ///
1072     /// ```
1073     /// #![feature(option_expect_none)]
1074     ///
1075     /// use std::collections::HashMap;
1076     /// let mut squares = HashMap::new();
1077     /// for i in -10..=10 {
1078     ///     // This will not panic, since all keys are unique.
1079     ///     squares.insert(i, i * i).expect_none("duplicate key");
1080     /// }
1081     /// ```
1082     ///
1083     /// ```{.should_panic}
1084     /// #![feature(option_expect_none)]
1085     ///
1086     /// use std::collections::HashMap;
1087     /// let mut sqrts = HashMap::new();
1088     /// for i in -10..=10 {
1089     ///     // This will panic, since both negative and positive `i` will
1090     ///     // insert the same `i * i` key, returning the old `Some(i)`.
1091     ///     sqrts.insert(i * i, i).expect_none("duplicate key");
1092     /// }
1093     /// ```
1094     #[inline]
1095     #[track_caller]
1096     #[unstable(feature = "option_expect_none", reason = "newly added", issue = "62633")]
1097     pub fn expect_none(self, msg: &str) {
1098         if let Some(val) = self {
1099             expect_none_failed(msg, &val);
1100         }
1101     }
1102
1103     /// Consumes `self` while expecting [`None`] and returning nothing.
1104     ///
1105     /// # Panics
1106     ///
1107     /// Panics if the value is a [`Some`], with a custom panic message provided
1108     /// by the [`Some`]'s value.
1109     ///
1110     /// [`Some(v)`]: Some
1111     ///
1112     /// # Examples
1113     ///
1114     /// ```
1115     /// #![feature(option_unwrap_none)]
1116     ///
1117     /// use std::collections::HashMap;
1118     /// let mut squares = HashMap::new();
1119     /// for i in -10..=10 {
1120     ///     // This will not panic, since all keys are unique.
1121     ///     squares.insert(i, i * i).unwrap_none();
1122     /// }
1123     /// ```
1124     ///
1125     /// ```{.should_panic}
1126     /// #![feature(option_unwrap_none)]
1127     ///
1128     /// use std::collections::HashMap;
1129     /// let mut sqrts = HashMap::new();
1130     /// for i in -10..=10 {
1131     ///     // This will panic, since both negative and positive `i` will
1132     ///     // insert the same `i * i` key, returning the old `Some(i)`.
1133     ///     sqrts.insert(i * i, i).unwrap_none();
1134     /// }
1135     /// ```
1136     #[inline]
1137     #[track_caller]
1138     #[unstable(feature = "option_unwrap_none", reason = "newly added", issue = "62633")]
1139     pub fn unwrap_none(self) {
1140         if let Some(val) = self {
1141             expect_none_failed("called `Option::unwrap_none()` on a `Some` value", &val);
1142         }
1143     }
1144 }
1145
1146 impl<T: Default> Option<T> {
1147     /// Returns the contained [`Some`] value or a default
1148     ///
1149     /// Consumes the `self` argument then, if [`Some`], returns the contained
1150     /// value, otherwise if [`None`], returns the [default value] for that
1151     /// type.
1152     ///
1153     /// # Examples
1154     ///
1155     /// Converts a string to an integer, turning poorly-formed strings
1156     /// into 0 (the default value for integers). [`parse`] converts
1157     /// a string to any other type that implements [`FromStr`], returning
1158     /// [`None`] on error.
1159     ///
1160     /// ```
1161     /// let good_year_from_input = "1909";
1162     /// let bad_year_from_input = "190blarg";
1163     /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
1164     /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
1165     ///
1166     /// assert_eq!(1909, good_year);
1167     /// assert_eq!(0, bad_year);
1168     /// ```
1169     ///
1170     /// [default value]: Default::default
1171     /// [`parse`]: str::parse
1172     /// [`FromStr`]: crate::str::FromStr
1173     #[inline]
1174     #[stable(feature = "rust1", since = "1.0.0")]
1175     pub fn unwrap_or_default(self) -> T {
1176         match self {
1177             Some(x) => x,
1178             None => Default::default(),
1179         }
1180     }
1181 }
1182
1183 impl<T: Deref> Option<T> {
1184     /// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.
1185     ///
1186     /// Leaves the original Option in-place, creating a new one with a reference
1187     /// to the original one, additionally coercing the contents via [`Deref`].
1188     ///
1189     /// # Examples
1190     ///
1191     /// ```
1192     /// let x: Option<String> = Some("hey".to_owned());
1193     /// assert_eq!(x.as_deref(), Some("hey"));
1194     ///
1195     /// let x: Option<String> = None;
1196     /// assert_eq!(x.as_deref(), None);
1197     /// ```
1198     #[stable(feature = "option_deref", since = "1.40.0")]
1199     pub fn as_deref(&self) -> Option<&T::Target> {
1200         self.as_ref().map(|t| t.deref())
1201     }
1202 }
1203
1204 impl<T: DerefMut> Option<T> {
1205     /// Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`.
1206     ///
1207     /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to
1208     /// the inner type's `Deref::Target` type.
1209     ///
1210     /// # Examples
1211     ///
1212     /// ```
1213     /// let mut x: Option<String> = Some("hey".to_owned());
1214     /// assert_eq!(x.as_deref_mut().map(|x| {
1215     ///     x.make_ascii_uppercase();
1216     ///     x
1217     /// }), Some("HEY".to_owned().as_mut_str()));
1218     /// ```
1219     #[stable(feature = "option_deref", since = "1.40.0")]
1220     pub fn as_deref_mut(&mut self) -> Option<&mut T::Target> {
1221         self.as_mut().map(|t| t.deref_mut())
1222     }
1223 }
1224
1225 impl<T, E> Option<Result<T, E>> {
1226     /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`.
1227     ///
1228     /// [`None`] will be mapped to [`Ok`]`(`[`None`]`)`.
1229     /// [`Some`]`(`[`Ok`]`(_))` and [`Some`]`(`[`Err`]`(_))` will be mapped to
1230     /// [`Ok`]`(`[`Some`]`(_))` and [`Err`]`(_)`.
1231     ///
1232     /// # Examples
1233     ///
1234     /// ```
1235     /// #[derive(Debug, Eq, PartialEq)]
1236     /// struct SomeErr;
1237     ///
1238     /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1239     /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1240     /// assert_eq!(x, y.transpose());
1241     /// ```
1242     #[inline]
1243     #[stable(feature = "transpose_result", since = "1.33.0")]
1244     pub fn transpose(self) -> Result<Option<T>, E> {
1245         match self {
1246             Some(Ok(x)) => Ok(Some(x)),
1247             Some(Err(e)) => Err(e),
1248             None => Ok(None),
1249         }
1250     }
1251 }
1252
1253 // This is a separate function to reduce the code size of .expect() itself.
1254 #[inline(never)]
1255 #[cold]
1256 #[track_caller]
1257 fn expect_failed(msg: &str) -> ! {
1258     panic!("{}", msg)
1259 }
1260
1261 // This is a separate function to reduce the code size of .expect_none() itself.
1262 #[inline(never)]
1263 #[cold]
1264 #[track_caller]
1265 fn expect_none_failed(msg: &str, value: &dyn fmt::Debug) -> ! {
1266     panic!("{}: {:?}", msg, value)
1267 }
1268
1269 /////////////////////////////////////////////////////////////////////////////
1270 // Trait implementations
1271 /////////////////////////////////////////////////////////////////////////////
1272
1273 #[stable(feature = "rust1", since = "1.0.0")]
1274 impl<T: Clone> Clone for Option<T> {
1275     #[inline]
1276     fn clone(&self) -> Self {
1277         match self {
1278             Some(x) => Some(x.clone()),
1279             None => None,
1280         }
1281     }
1282
1283     #[inline]
1284     fn clone_from(&mut self, source: &Self) {
1285         match (self, source) {
1286             (Some(to), Some(from)) => to.clone_from(from),
1287             (to, from) => *to = from.clone(),
1288         }
1289     }
1290 }
1291
1292 #[stable(feature = "rust1", since = "1.0.0")]
1293 impl<T> Default for Option<T> {
1294     /// Returns [`None`][Option::None].
1295     ///
1296     /// # Examples
1297     ///
1298     /// ```
1299     /// let opt: Option<u32> = Option::default();
1300     /// assert!(opt.is_none());
1301     /// ```
1302     #[inline]
1303     fn default() -> Option<T> {
1304         None
1305     }
1306 }
1307
1308 #[stable(feature = "rust1", since = "1.0.0")]
1309 impl<T> IntoIterator for Option<T> {
1310     type Item = T;
1311     type IntoIter = IntoIter<T>;
1312
1313     /// Returns a consuming iterator over the possibly contained value.
1314     ///
1315     /// # Examples
1316     ///
1317     /// ```
1318     /// let x = Some("string");
1319     /// let v: Vec<&str> = x.into_iter().collect();
1320     /// assert_eq!(v, ["string"]);
1321     ///
1322     /// let x = None;
1323     /// let v: Vec<&str> = x.into_iter().collect();
1324     /// assert!(v.is_empty());
1325     /// ```
1326     #[inline]
1327     fn into_iter(self) -> IntoIter<T> {
1328         IntoIter { inner: Item { opt: self } }
1329     }
1330 }
1331
1332 #[stable(since = "1.4.0", feature = "option_iter")]
1333 impl<'a, T> IntoIterator for &'a Option<T> {
1334     type Item = &'a T;
1335     type IntoIter = Iter<'a, T>;
1336
1337     fn into_iter(self) -> Iter<'a, T> {
1338         self.iter()
1339     }
1340 }
1341
1342 #[stable(since = "1.4.0", feature = "option_iter")]
1343 impl<'a, T> IntoIterator for &'a mut Option<T> {
1344     type Item = &'a mut T;
1345     type IntoIter = IterMut<'a, T>;
1346
1347     fn into_iter(self) -> IterMut<'a, T> {
1348         self.iter_mut()
1349     }
1350 }
1351
1352 #[stable(since = "1.12.0", feature = "option_from")]
1353 impl<T> From<T> for Option<T> {
1354     /// Copies `val` into a new `Some`.
1355     ///
1356     /// # Examples
1357     ///
1358     /// ```
1359     /// let o: Option<u8> = Option::from(67);
1360     ///
1361     /// assert_eq!(Some(67), o);
1362     /// ```
1363     fn from(val: T) -> Option<T> {
1364         Some(val)
1365     }
1366 }
1367
1368 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1369 impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
1370     /// Converts from `&Option<T>` to `Option<&T>`.
1371     ///
1372     /// # Examples
1373     ///
1374     /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
1375     /// The [`map`] method takes the `self` argument by value, consuming the original,
1376     /// so this technique uses `as_ref` to first take an `Option` to a reference
1377     /// to the value inside the original.
1378     ///
1379     /// [`map`]: Option::map
1380     /// [`String`]: ../../std/string/struct.String.html
1381     ///
1382     /// ```
1383     /// let s: Option<String> = Some(String::from("Hello, Rustaceans!"));
1384     /// let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());
1385     ///
1386     /// println!("Can still print s: {:?}", s);
1387     ///
1388     /// assert_eq!(o, Some(18));
1389     /// ```
1390     fn from(o: &'a Option<T>) -> Option<&'a T> {
1391         o.as_ref()
1392     }
1393 }
1394
1395 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1396 impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> {
1397     /// Converts from `&mut Option<T>` to `Option<&mut T>`
1398     ///
1399     /// # Examples
1400     ///
1401     /// ```
1402     /// let mut s = Some(String::from("Hello"));
1403     /// let o: Option<&mut String> = Option::from(&mut s);
1404     ///
1405     /// match o {
1406     ///     Some(t) => *t = String::from("Hello, Rustaceans!"),
1407     ///     None => (),
1408     /// }
1409     ///
1410     /// assert_eq!(s, Some(String::from("Hello, Rustaceans!")));
1411     /// ```
1412     fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
1413         o.as_mut()
1414     }
1415 }
1416
1417 /////////////////////////////////////////////////////////////////////////////
1418 // The Option Iterators
1419 /////////////////////////////////////////////////////////////////////////////
1420
1421 #[derive(Clone, Debug)]
1422 struct Item<A> {
1423     opt: Option<A>,
1424 }
1425
1426 impl<A> Iterator for Item<A> {
1427     type Item = A;
1428
1429     #[inline]
1430     fn next(&mut self) -> Option<A> {
1431         self.opt.take()
1432     }
1433
1434     #[inline]
1435     fn size_hint(&self) -> (usize, Option<usize>) {
1436         match self.opt {
1437             Some(_) => (1, Some(1)),
1438             None => (0, Some(0)),
1439         }
1440     }
1441 }
1442
1443 impl<A> DoubleEndedIterator for Item<A> {
1444     #[inline]
1445     fn next_back(&mut self) -> Option<A> {
1446         self.opt.take()
1447     }
1448 }
1449
1450 impl<A> ExactSizeIterator for Item<A> {}
1451 impl<A> FusedIterator for Item<A> {}
1452 unsafe impl<A> TrustedLen for Item<A> {}
1453
1454 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
1455 ///
1456 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1457 ///
1458 /// This `struct` is created by the [`Option::iter`] function.
1459 #[stable(feature = "rust1", since = "1.0.0")]
1460 #[derive(Debug)]
1461 pub struct Iter<'a, A: 'a> {
1462     inner: Item<&'a A>,
1463 }
1464
1465 #[stable(feature = "rust1", since = "1.0.0")]
1466 impl<'a, A> Iterator for Iter<'a, A> {
1467     type Item = &'a A;
1468
1469     #[inline]
1470     fn next(&mut self) -> Option<&'a A> {
1471         self.inner.next()
1472     }
1473     #[inline]
1474     fn size_hint(&self) -> (usize, Option<usize>) {
1475         self.inner.size_hint()
1476     }
1477 }
1478
1479 #[stable(feature = "rust1", since = "1.0.0")]
1480 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
1481     #[inline]
1482     fn next_back(&mut self) -> Option<&'a A> {
1483         self.inner.next_back()
1484     }
1485 }
1486
1487 #[stable(feature = "rust1", since = "1.0.0")]
1488 impl<A> ExactSizeIterator for Iter<'_, A> {}
1489
1490 #[stable(feature = "fused", since = "1.26.0")]
1491 impl<A> FusedIterator for Iter<'_, A> {}
1492
1493 #[unstable(feature = "trusted_len", issue = "37572")]
1494 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1495
1496 #[stable(feature = "rust1", since = "1.0.0")]
1497 impl<A> Clone for Iter<'_, A> {
1498     #[inline]
1499     fn clone(&self) -> Self {
1500         Iter { inner: self.inner.clone() }
1501     }
1502 }
1503
1504 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
1505 ///
1506 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1507 ///
1508 /// This `struct` is created by the [`Option::iter_mut`] function.
1509 #[stable(feature = "rust1", since = "1.0.0")]
1510 #[derive(Debug)]
1511 pub struct IterMut<'a, A: 'a> {
1512     inner: Item<&'a mut A>,
1513 }
1514
1515 #[stable(feature = "rust1", since = "1.0.0")]
1516 impl<'a, A> Iterator for IterMut<'a, A> {
1517     type Item = &'a mut A;
1518
1519     #[inline]
1520     fn next(&mut self) -> Option<&'a mut A> {
1521         self.inner.next()
1522     }
1523     #[inline]
1524     fn size_hint(&self) -> (usize, Option<usize>) {
1525         self.inner.size_hint()
1526     }
1527 }
1528
1529 #[stable(feature = "rust1", since = "1.0.0")]
1530 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
1531     #[inline]
1532     fn next_back(&mut self) -> Option<&'a mut A> {
1533         self.inner.next_back()
1534     }
1535 }
1536
1537 #[stable(feature = "rust1", since = "1.0.0")]
1538 impl<A> ExactSizeIterator for IterMut<'_, A> {}
1539
1540 #[stable(feature = "fused", since = "1.26.0")]
1541 impl<A> FusedIterator for IterMut<'_, A> {}
1542 #[unstable(feature = "trusted_len", issue = "37572")]
1543 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1544
1545 /// An iterator over the value in [`Some`] variant of an [`Option`].
1546 ///
1547 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1548 ///
1549 /// This `struct` is created by the [`Option::into_iter`] function.
1550 #[derive(Clone, Debug)]
1551 #[stable(feature = "rust1", since = "1.0.0")]
1552 pub struct IntoIter<A> {
1553     inner: Item<A>,
1554 }
1555
1556 #[stable(feature = "rust1", since = "1.0.0")]
1557 impl<A> Iterator for IntoIter<A> {
1558     type Item = A;
1559
1560     #[inline]
1561     fn next(&mut self) -> Option<A> {
1562         self.inner.next()
1563     }
1564     #[inline]
1565     fn size_hint(&self) -> (usize, Option<usize>) {
1566         self.inner.size_hint()
1567     }
1568 }
1569
1570 #[stable(feature = "rust1", since = "1.0.0")]
1571 impl<A> DoubleEndedIterator for IntoIter<A> {
1572     #[inline]
1573     fn next_back(&mut self) -> Option<A> {
1574         self.inner.next_back()
1575     }
1576 }
1577
1578 #[stable(feature = "rust1", since = "1.0.0")]
1579 impl<A> ExactSizeIterator for IntoIter<A> {}
1580
1581 #[stable(feature = "fused", since = "1.26.0")]
1582 impl<A> FusedIterator for IntoIter<A> {}
1583
1584 #[unstable(feature = "trusted_len", issue = "37572")]
1585 unsafe impl<A> TrustedLen for IntoIter<A> {}
1586
1587 /////////////////////////////////////////////////////////////////////////////
1588 // FromIterator
1589 /////////////////////////////////////////////////////////////////////////////
1590
1591 #[stable(feature = "rust1", since = "1.0.0")]
1592 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
1593     /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
1594     /// no further elements are taken, and the [`None`][Option::None] is
1595     /// returned. Should no [`None`][Option::None] occur, a container with the
1596     /// values of each [`Option`] is returned.
1597     ///
1598     /// # Examples
1599     ///
1600     /// Here is an example which increments every integer in a vector.
1601     /// We use the checked variant of `add` that returns `None` when the
1602     /// calculation would result in an overflow.
1603     ///
1604     /// ```
1605     /// let items = vec![0_u16, 1, 2];
1606     ///
1607     /// let res: Option<Vec<u16>> = items
1608     ///     .iter()
1609     ///     .map(|x| x.checked_add(1))
1610     ///     .collect();
1611     ///
1612     /// assert_eq!(res, Some(vec![1, 2, 3]));
1613     /// ```
1614     ///
1615     /// As you can see, this will return the expected, valid items.
1616     ///
1617     /// Here is another example that tries to subtract one from another list
1618     /// of integers, this time checking for underflow:
1619     ///
1620     /// ```
1621     /// let items = vec![2_u16, 1, 0];
1622     ///
1623     /// let res: Option<Vec<u16>> = items
1624     ///     .iter()
1625     ///     .map(|x| x.checked_sub(1))
1626     ///     .collect();
1627     ///
1628     /// assert_eq!(res, None);
1629     /// ```
1630     ///
1631     /// Since the last element is zero, it would underflow. Thus, the resulting
1632     /// value is `None`.
1633     ///
1634     /// Here is a variation on the previous example, showing that no
1635     /// further elements are taken from `iter` after the first `None`.
1636     ///
1637     /// ```
1638     /// let items = vec![3_u16, 2, 1, 10];
1639     ///
1640     /// let mut shared = 0;
1641     ///
1642     /// let res: Option<Vec<u16>> = items
1643     ///     .iter()
1644     ///     .map(|x| { shared += x; x.checked_sub(2) })
1645     ///     .collect();
1646     ///
1647     /// assert_eq!(res, None);
1648     /// assert_eq!(shared, 6);
1649     /// ```
1650     ///
1651     /// Since the third element caused an underflow, no further elements were taken,
1652     /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1653     #[inline]
1654     fn from_iter<I: IntoIterator<Item = Option<A>>>(iter: I) -> Option<V> {
1655         // FIXME(#11084): This could be replaced with Iterator::scan when this
1656         // performance bug is closed.
1657
1658         iter.into_iter().map(|x| x.ok_or(())).collect::<Result<_, _>>().ok()
1659     }
1660 }
1661
1662 /// The error type that results from applying the try operator (`?`) to a `None` value. If you wish
1663 /// to allow `x?` (where `x` is an `Option<T>`) to be converted into your error type, you can
1664 /// implement `impl From<NoneError>` for `YourErrorType`. In that case, `x?` within a function that
1665 /// returns `Result<_, YourErrorType>` will translate a `None` value into an `Err` result.
1666 #[rustc_diagnostic_item = "none_error"]
1667 #[unstable(feature = "try_trait", issue = "42327")]
1668 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
1669 pub struct NoneError;
1670
1671 #[unstable(feature = "try_trait", issue = "42327")]
1672 impl<T> ops::Try for Option<T> {
1673     type Ok = T;
1674     type Error = NoneError;
1675
1676     #[inline]
1677     fn into_result(self) -> Result<T, NoneError> {
1678         self.ok_or(NoneError)
1679     }
1680
1681     #[inline]
1682     fn from_ok(v: T) -> Self {
1683         Some(v)
1684     }
1685
1686     #[inline]
1687     fn from_error(_: NoneError) -> Self {
1688         None
1689     }
1690 }
1691
1692 impl<T> Option<Option<T>> {
1693     /// Converts from `Option<Option<T>>` to `Option<T>`
1694     ///
1695     /// # Examples
1696     ///
1697     /// Basic usage:
1698     ///
1699     /// ```
1700     /// let x: Option<Option<u32>> = Some(Some(6));
1701     /// assert_eq!(Some(6), x.flatten());
1702     ///
1703     /// let x: Option<Option<u32>> = Some(None);
1704     /// assert_eq!(None, x.flatten());
1705     ///
1706     /// let x: Option<Option<u32>> = None;
1707     /// assert_eq!(None, x.flatten());
1708     /// ```
1709     ///
1710     /// Flattening only removes one level of nesting at a time:
1711     ///
1712     /// ```
1713     /// let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
1714     /// assert_eq!(Some(Some(6)), x.flatten());
1715     /// assert_eq!(Some(6), x.flatten().flatten());
1716     /// ```
1717     #[inline]
1718     #[stable(feature = "option_flattening", since = "1.40.0")]
1719     pub fn flatten(self) -> Option<T> {
1720         self.and_then(convert::identity)
1721     }
1722 }