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