| 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, <code>[Option]<[Box\<T>]></code>. |
| 51 | //! |
| 52 | //! [Box\<T>]: ../../std/boxed/struct.Box.html |
| 53 | //! |
| 54 | //! The following example uses [`Option`] to create an optional box of |
| 55 | //! [`i32`]. Notice that in order to use the inner [`i32`] value, the |
| 56 | //! `check_optional` function first needs to use pattern matching to |
| 57 | //! determine whether the box has a value (i.e., it is [`Some(...)`][`Some`]) or |
| 58 | //! not ([`None`]). |
| 59 | //! |
| 60 | //! ``` |
| 61 | //! let optional = None; |
| 62 | //! check_optional(optional); |
| 63 | //! |
| 64 | //! let optional = Some(Box::new(9000)); |
| 65 | //! check_optional(optional); |
| 66 | //! |
| 67 | //! fn check_optional(optional: Option<Box<i32>>) { |
| 68 | //! match optional { |
| 69 | //! Some(p) => println!("has value {p}" ), |
| 70 | //! None => println!("has no value" ), |
| 71 | //! } |
| 72 | //! } |
| 73 | //! ``` |
| 74 | //! |
| 75 | //! # The question mark operator, `?` |
| 76 | //! |
| 77 | //! Similar to the [`Result`] type, when writing code that calls many functions that return the |
| 78 | //! [`Option`] type, handling `Some`/`None` can be tedious. The question mark |
| 79 | //! operator, [`?`], hides some of the boilerplate of propagating values |
| 80 | //! up the call stack. |
| 81 | //! |
| 82 | //! It replaces this: |
| 83 | //! |
| 84 | //! ``` |
| 85 | //! # #![allow(dead_code)] |
| 86 | //! fn add_last_numbers(stack: &mut Vec<i32>) -> Option<i32> { |
| 87 | //! let a = stack.pop(); |
| 88 | //! let b = stack.pop(); |
| 89 | //! |
| 90 | //! match (a, b) { |
| 91 | //! (Some(x), Some(y)) => Some(x + y), |
| 92 | //! _ => None, |
| 93 | //! } |
| 94 | //! } |
| 95 | //! |
| 96 | //! ``` |
| 97 | //! |
| 98 | //! With this: |
| 99 | //! |
| 100 | //! ``` |
| 101 | //! # #![allow(dead_code)] |
| 102 | //! fn add_last_numbers(stack: &mut Vec<i32>) -> Option<i32> { |
| 103 | //! Some(stack.pop()? + stack.pop()?) |
| 104 | //! } |
| 105 | //! ``` |
| 106 | //! |
| 107 | //! *It's much nicer!* |
| 108 | //! |
| 109 | //! Ending the expression with [`?`] will result in the [`Some`]'s unwrapped value, unless the |
| 110 | //! result is [`None`], in which case [`None`] is returned early from the enclosing function. |
| 111 | //! |
| 112 | //! [`?`] can be used in functions that return [`Option`] because of the |
| 113 | //! early return of [`None`] that it provides. |
| 114 | //! |
| 115 | //! [`?`]: crate::ops::Try |
| 116 | //! [`Some`]: Some |
| 117 | //! [`None`]: None |
| 118 | //! |
| 119 | //! # Representation |
| 120 | //! |
| 121 | //! Rust guarantees to optimize the following types `T` such that |
| 122 | //! [`Option<T>`] has the same size, alignment, and [function call ABI] as `T`. In some |
| 123 | //! of these cases, Rust further guarantees that |
| 124 | //! `transmute::<_, Option<T>>([0u8; size_of::<T>()])` is sound and |
| 125 | //! produces `Option::<T>::None`. These cases are identified by the |
| 126 | //! second column: |
| 127 | //! |
| 128 | //! | `T` | `transmute::<_, Option<T>>([0u8; size_of::<T>()])` sound? | |
| 129 | //! |---------------------------------------------------------------------|----------------------------------------------------------------------| |
| 130 | //! | [`Box<U>`] (specifically, only `Box<U, Global>`) | when `U: Sized` | |
| 131 | //! | `&U` | when `U: Sized` | |
| 132 | //! | `&mut U` | when `U: Sized` | |
| 133 | //! | `fn`, `extern "C" fn`[^extern_fn] | always | |
| 134 | //! | [`num::NonZero*`] | always | |
| 135 | //! | [`ptr::NonNull<U>`] | when `U: Sized` | |
| 136 | //! | `#[repr(transparent)]` struct around one of the types in this list. | when it holds for the inner type | |
| 137 | //! |
| 138 | //! [^extern_fn]: this remains true for any argument/return types and any other ABI: `extern "abi" fn` (_e.g._, `extern "system" fn`) |
| 139 | //! |
| 140 | //! Under some conditions the above types `T` are also null pointer optimized when wrapped in a [`Result`][result_repr]. |
| 141 | //! |
| 142 | //! [`Box<U>`]: ../../std/boxed/struct.Box.html |
| 143 | //! [`num::NonZero*`]: crate::num |
| 144 | //! [`ptr::NonNull<U>`]: crate::ptr::NonNull |
| 145 | //! [function call ABI]: ../primitive.fn.html#abi-compatibility |
| 146 | //! [result_repr]: crate::result#representation |
| 147 | //! |
| 148 | //! This is called the "null pointer optimization" or NPO. |
| 149 | //! |
| 150 | //! It is further guaranteed that, for the cases above, one can |
| 151 | //! [`mem::transmute`] from all valid values of `T` to `Option<T>` and |
| 152 | //! from `Some::<T>(_)` to `T` (but transmuting `None::<T>` to `T` |
| 153 | //! is undefined behavior). |
| 154 | //! |
| 155 | //! # Method overview |
| 156 | //! |
| 157 | //! In addition to working with pattern matching, [`Option`] provides a wide |
| 158 | //! variety of different methods. |
| 159 | //! |
| 160 | //! ## Querying the variant |
| 161 | //! |
| 162 | //! The [`is_some`] and [`is_none`] methods return [`true`] if the [`Option`] |
| 163 | //! is [`Some`] or [`None`], respectively. |
| 164 | //! |
| 165 | //! [`is_none`]: Option::is_none |
| 166 | //! [`is_some`]: Option::is_some |
| 167 | //! |
| 168 | //! ## Adapters for working with references |
| 169 | //! |
| 170 | //! * [`as_ref`] converts from <code>[&][][Option]\<T></code> to <code>[Option]<[&]T></code> |
| 171 | //! * [`as_mut`] converts from <code>[&mut] [Option]\<T></code> to <code>[Option]<[&mut] T></code> |
| 172 | //! * [`as_deref`] converts from <code>[&][][Option]\<T></code> to |
| 173 | //! <code>[Option]<[&]T::[Target]></code> |
| 174 | //! * [`as_deref_mut`] converts from <code>[&mut] [Option]\<T></code> to |
| 175 | //! <code>[Option]<[&mut] T::[Target]></code> |
| 176 | //! * [`as_pin_ref`] converts from <code>[Pin]<[&][][Option]\<T>></code> to |
| 177 | //! <code>[Option]<[Pin]<[&]T>></code> |
| 178 | //! * [`as_pin_mut`] converts from <code>[Pin]<[&mut] [Option]\<T>></code> to |
| 179 | //! <code>[Option]<[Pin]<[&mut] T>></code> |
| 180 | //! |
| 181 | //! [&]: reference "shared reference" |
| 182 | //! [&mut]: reference "mutable reference" |
| 183 | //! [Target]: Deref::Target "ops::Deref::Target" |
| 184 | //! [`as_deref`]: Option::as_deref |
| 185 | //! [`as_deref_mut`]: Option::as_deref_mut |
| 186 | //! [`as_mut`]: Option::as_mut |
| 187 | //! [`as_pin_mut`]: Option::as_pin_mut |
| 188 | //! [`as_pin_ref`]: Option::as_pin_ref |
| 189 | //! [`as_ref`]: Option::as_ref |
| 190 | //! |
| 191 | //! ## Extracting the contained value |
| 192 | //! |
| 193 | //! These methods extract the contained value in an [`Option<T>`] when it |
| 194 | //! is the [`Some`] variant. If the [`Option`] is [`None`]: |
| 195 | //! |
| 196 | //! * [`expect`] panics with a provided custom message |
| 197 | //! * [`unwrap`] panics with a generic message |
| 198 | //! * [`unwrap_or`] returns the provided default value |
| 199 | //! * [`unwrap_or_default`] returns the default value of the type `T` |
| 200 | //! (which must implement the [`Default`] trait) |
| 201 | //! * [`unwrap_or_else`] returns the result of evaluating the provided |
| 202 | //! function |
| 203 | //! |
| 204 | //! [`expect`]: Option::expect |
| 205 | //! [`unwrap`]: Option::unwrap |
| 206 | //! [`unwrap_or`]: Option::unwrap_or |
| 207 | //! [`unwrap_or_default`]: Option::unwrap_or_default |
| 208 | //! [`unwrap_or_else`]: Option::unwrap_or_else |
| 209 | //! |
| 210 | //! ## Transforming contained values |
| 211 | //! |
| 212 | //! These methods transform [`Option`] to [`Result`]: |
| 213 | //! |
| 214 | //! * [`ok_or`] transforms [`Some(v)`] to [`Ok(v)`], and [`None`] to |
| 215 | //! [`Err(err)`] using the provided default `err` value |
| 216 | //! * [`ok_or_else`] transforms [`Some(v)`] to [`Ok(v)`], and [`None`] to |
| 217 | //! a value of [`Err`] using the provided function |
| 218 | //! * [`transpose`] transposes an [`Option`] of a [`Result`] into a |
| 219 | //! [`Result`] of an [`Option`] |
| 220 | //! |
| 221 | //! [`Err(err)`]: Err |
| 222 | //! [`Ok(v)`]: Ok |
| 223 | //! [`Some(v)`]: Some |
| 224 | //! [`ok_or`]: Option::ok_or |
| 225 | //! [`ok_or_else`]: Option::ok_or_else |
| 226 | //! [`transpose`]: Option::transpose |
| 227 | //! |
| 228 | //! These methods transform the [`Some`] variant: |
| 229 | //! |
| 230 | //! * [`filter`] calls the provided predicate function on the contained |
| 231 | //! value `t` if the [`Option`] is [`Some(t)`], and returns [`Some(t)`] |
| 232 | //! if the function returns `true`; otherwise, returns [`None`] |
| 233 | //! * [`flatten`] removes one level of nesting from an |
| 234 | //! [`Option<Option<T>>`] |
| 235 | //! * [`map`] transforms [`Option<T>`] to [`Option<U>`] by applying the |
| 236 | //! provided function to the contained value of [`Some`] and leaving |
| 237 | //! [`None`] values unchanged |
| 238 | //! |
| 239 | //! [`Some(t)`]: Some |
| 240 | //! [`filter`]: Option::filter |
| 241 | //! [`flatten`]: Option::flatten |
| 242 | //! [`map`]: Option::map |
| 243 | //! |
| 244 | //! These methods transform [`Option<T>`] to a value of a possibly |
| 245 | //! different type `U`: |
| 246 | //! |
| 247 | //! * [`map_or`] applies the provided function to the contained value of |
| 248 | //! [`Some`], or returns the provided default value if the [`Option`] is |
| 249 | //! [`None`] |
| 250 | //! * [`map_or_else`] applies the provided function to the contained value |
| 251 | //! of [`Some`], or returns the result of evaluating the provided |
| 252 | //! fallback function if the [`Option`] is [`None`] |
| 253 | //! |
| 254 | //! [`map_or`]: Option::map_or |
| 255 | //! [`map_or_else`]: Option::map_or_else |
| 256 | //! |
| 257 | //! These methods combine the [`Some`] variants of two [`Option`] values: |
| 258 | //! |
| 259 | //! * [`zip`] returns [`Some((s, o))`] if `self` is [`Some(s)`] and the |
| 260 | //! provided [`Option`] value is [`Some(o)`]; otherwise, returns [`None`] |
| 261 | //! * [`zip_with`] calls the provided function `f` and returns |
| 262 | //! [`Some(f(s, o))`] if `self` is [`Some(s)`] and the provided |
| 263 | //! [`Option`] value is [`Some(o)`]; otherwise, returns [`None`] |
| 264 | //! |
| 265 | //! [`Some(f(s, o))`]: Some |
| 266 | //! [`Some(o)`]: Some |
| 267 | //! [`Some(s)`]: Some |
| 268 | //! [`Some((s, o))`]: Some |
| 269 | //! [`zip`]: Option::zip |
| 270 | //! [`zip_with`]: Option::zip_with |
| 271 | //! |
| 272 | //! ## Boolean operators |
| 273 | //! |
| 274 | //! These methods treat the [`Option`] as a boolean value, where [`Some`] |
| 275 | //! acts like [`true`] and [`None`] acts like [`false`]. There are two |
| 276 | //! categories of these methods: ones that take an [`Option`] as input, and |
| 277 | //! ones that take a function as input (to be lazily evaluated). |
| 278 | //! |
| 279 | //! The [`and`], [`or`], and [`xor`] methods take another [`Option`] as |
| 280 | //! input, and produce an [`Option`] as output. Only the [`and`] method can |
| 281 | //! produce an [`Option<U>`] value having a different inner type `U` than |
| 282 | //! [`Option<T>`]. |
| 283 | //! |
| 284 | //! | method | self | input | output | |
| 285 | //! |---------|-----------|-----------|-----------| |
| 286 | //! | [`and`] | `None` | (ignored) | `None` | |
| 287 | //! | [`and`] | `Some(x)` | `None` | `None` | |
| 288 | //! | [`and`] | `Some(x)` | `Some(y)` | `Some(y)` | |
| 289 | //! | [`or`] | `None` | `None` | `None` | |
| 290 | //! | [`or`] | `None` | `Some(y)` | `Some(y)` | |
| 291 | //! | [`or`] | `Some(x)` | (ignored) | `Some(x)` | |
| 292 | //! | [`xor`] | `None` | `None` | `None` | |
| 293 | //! | [`xor`] | `None` | `Some(y)` | `Some(y)` | |
| 294 | //! | [`xor`] | `Some(x)` | `None` | `Some(x)` | |
| 295 | //! | [`xor`] | `Some(x)` | `Some(y)` | `None` | |
| 296 | //! |
| 297 | //! [`and`]: Option::and |
| 298 | //! [`or`]: Option::or |
| 299 | //! [`xor`]: Option::xor |
| 300 | //! |
| 301 | //! The [`and_then`] and [`or_else`] methods take a function as input, and |
| 302 | //! only evaluate the function when they need to produce a new value. Only |
| 303 | //! the [`and_then`] method can produce an [`Option<U>`] value having a |
| 304 | //! different inner type `U` than [`Option<T>`]. |
| 305 | //! |
| 306 | //! | method | self | function input | function result | output | |
| 307 | //! |--------------|-----------|----------------|-----------------|-----------| |
| 308 | //! | [`and_then`] | `None` | (not provided) | (not evaluated) | `None` | |
| 309 | //! | [`and_then`] | `Some(x)` | `x` | `None` | `None` | |
| 310 | //! | [`and_then`] | `Some(x)` | `x` | `Some(y)` | `Some(y)` | |
| 311 | //! | [`or_else`] | `None` | (not provided) | `None` | `None` | |
| 312 | //! | [`or_else`] | `None` | (not provided) | `Some(y)` | `Some(y)` | |
| 313 | //! | [`or_else`] | `Some(x)` | (not provided) | (not evaluated) | `Some(x)` | |
| 314 | //! |
| 315 | //! [`and_then`]: Option::and_then |
| 316 | //! [`or_else`]: Option::or_else |
| 317 | //! |
| 318 | //! This is an example of using methods like [`and_then`] and [`or`] in a |
| 319 | //! pipeline of method calls. Early stages of the pipeline pass failure |
| 320 | //! values ([`None`]) through unchanged, and continue processing on |
| 321 | //! success values ([`Some`]). Toward the end, [`or`] substitutes an error |
| 322 | //! message if it receives [`None`]. |
| 323 | //! |
| 324 | //! ``` |
| 325 | //! # use std::collections::BTreeMap; |
| 326 | //! let mut bt = BTreeMap::new(); |
| 327 | //! bt.insert(20u8, "foo" ); |
| 328 | //! bt.insert(42u8, "bar" ); |
| 329 | //! let res = [0u8, 1, 11, 200, 22] |
| 330 | //! .into_iter() |
| 331 | //! .map(|x| { |
| 332 | //! // `checked_sub()` returns `None` on error |
| 333 | //! x.checked_sub(1) |
| 334 | //! // same with `checked_mul()` |
| 335 | //! .and_then(|x| x.checked_mul(2)) |
| 336 | //! // `BTreeMap::get` returns `None` on error |
| 337 | //! .and_then(|x| bt.get(&x)) |
| 338 | //! // Substitute an error message if we have `None` so far |
| 339 | //! .or(Some(&"error!" )) |
| 340 | //! .copied() |
| 341 | //! // Won't panic because we unconditionally used `Some` above |
| 342 | //! .unwrap() |
| 343 | //! }) |
| 344 | //! .collect::<Vec<_>>(); |
| 345 | //! assert_eq!(res, ["error!" , "error!" , "foo" , "error!" , "bar" ]); |
| 346 | //! ``` |
| 347 | //! |
| 348 | //! ## Comparison operators |
| 349 | //! |
| 350 | //! If `T` implements [`PartialOrd`] then [`Option<T>`] will derive its |
| 351 | //! [`PartialOrd`] implementation. With this order, [`None`] compares as |
| 352 | //! less than any [`Some`], and two [`Some`] compare the same way as their |
| 353 | //! contained values would in `T`. If `T` also implements |
| 354 | //! [`Ord`], then so does [`Option<T>`]. |
| 355 | //! |
| 356 | //! ``` |
| 357 | //! assert!(None < Some(0)); |
| 358 | //! assert!(Some(0) < Some(1)); |
| 359 | //! ``` |
| 360 | //! |
| 361 | //! ## Iterating over `Option` |
| 362 | //! |
| 363 | //! An [`Option`] can be iterated over. This can be helpful if you need an |
| 364 | //! iterator that is conditionally empty. The iterator will either produce |
| 365 | //! a single value (when the [`Option`] is [`Some`]), or produce no values |
| 366 | //! (when the [`Option`] is [`None`]). For example, [`into_iter`] acts like |
| 367 | //! [`once(v)`] if the [`Option`] is [`Some(v)`], and like [`empty()`] if |
| 368 | //! the [`Option`] is [`None`]. |
| 369 | //! |
| 370 | //! [`Some(v)`]: Some |
| 371 | //! [`empty()`]: crate::iter::empty |
| 372 | //! [`once(v)`]: crate::iter::once |
| 373 | //! |
| 374 | //! Iterators over [`Option<T>`] come in three types: |
| 375 | //! |
| 376 | //! * [`into_iter`] consumes the [`Option`] and produces the contained |
| 377 | //! value |
| 378 | //! * [`iter`] produces an immutable reference of type `&T` to the |
| 379 | //! contained value |
| 380 | //! * [`iter_mut`] produces a mutable reference of type `&mut T` to the |
| 381 | //! contained value |
| 382 | //! |
| 383 | //! [`into_iter`]: Option::into_iter |
| 384 | //! [`iter`]: Option::iter |
| 385 | //! [`iter_mut`]: Option::iter_mut |
| 386 | //! |
| 387 | //! An iterator over [`Option`] can be useful when chaining iterators, for |
| 388 | //! example, to conditionally insert items. (It's not always necessary to |
| 389 | //! explicitly call an iterator constructor: many [`Iterator`] methods that |
| 390 | //! accept other iterators will also accept iterable types that implement |
| 391 | //! [`IntoIterator`], which includes [`Option`].) |
| 392 | //! |
| 393 | //! ``` |
| 394 | //! let yep = Some(42); |
| 395 | //! let nope = None; |
| 396 | //! // chain() already calls into_iter(), so we don't have to do so |
| 397 | //! let nums: Vec<i32> = (0..4).chain(yep).chain(4..8).collect(); |
| 398 | //! assert_eq!(nums, [0, 1, 2, 3, 42, 4, 5, 6, 7]); |
| 399 | //! let nums: Vec<i32> = (0..4).chain(nope).chain(4..8).collect(); |
| 400 | //! assert_eq!(nums, [0, 1, 2, 3, 4, 5, 6, 7]); |
| 401 | //! ``` |
| 402 | //! |
| 403 | //! One reason to chain iterators in this way is that a function returning |
| 404 | //! `impl Iterator` must have all possible return values be of the same |
| 405 | //! concrete type. Chaining an iterated [`Option`] can help with that. |
| 406 | //! |
| 407 | //! ``` |
| 408 | //! fn make_iter(do_insert: bool) -> impl Iterator<Item = i32> { |
| 409 | //! // Explicit returns to illustrate return types matching |
| 410 | //! match do_insert { |
| 411 | //! true => return (0..4).chain(Some(42)).chain(4..8), |
| 412 | //! false => return (0..4).chain(None).chain(4..8), |
| 413 | //! } |
| 414 | //! } |
| 415 | //! println!("{:?}" , make_iter(true).collect::<Vec<_>>()); |
| 416 | //! println!("{:?}" , make_iter(false).collect::<Vec<_>>()); |
| 417 | //! ``` |
| 418 | //! |
| 419 | //! If we try to do the same thing, but using [`once()`] and [`empty()`], |
| 420 | //! we can't return `impl Iterator` anymore because the concrete types of |
| 421 | //! the return values differ. |
| 422 | //! |
| 423 | //! [`empty()`]: crate::iter::empty |
| 424 | //! [`once()`]: crate::iter::once |
| 425 | //! |
| 426 | //! ```compile_fail,E0308 |
| 427 | //! # use std::iter::{empty, once}; |
| 428 | //! // This won't compile because all possible returns from the function |
| 429 | //! // must have the same concrete type. |
| 430 | //! fn make_iter(do_insert: bool) -> impl Iterator<Item = i32> { |
| 431 | //! // Explicit returns to illustrate return types not matching |
| 432 | //! match do_insert { |
| 433 | //! true => return (0..4).chain(once(42)).chain(4..8), |
| 434 | //! false => return (0..4).chain(empty()).chain(4..8), |
| 435 | //! } |
| 436 | //! } |
| 437 | //! ``` |
| 438 | //! |
| 439 | //! ## Collecting into `Option` |
| 440 | //! |
| 441 | //! [`Option`] implements the [`FromIterator`][impl-FromIterator] trait, |
| 442 | //! which allows an iterator over [`Option`] values to be collected into an |
| 443 | //! [`Option`] of a collection of each contained value of the original |
| 444 | //! [`Option`] values, or [`None`] if any of the elements was [`None`]. |
| 445 | //! |
| 446 | //! [impl-FromIterator]: Option#impl-FromIterator%3COption%3CA%3E%3E-for-Option%3CV%3E |
| 447 | //! |
| 448 | //! ``` |
| 449 | //! let v = [Some(2), Some(4), None, Some(8)]; |
| 450 | //! let res: Option<Vec<_>> = v.into_iter().collect(); |
| 451 | //! assert_eq!(res, None); |
| 452 | //! let v = [Some(2), Some(4), Some(8)]; |
| 453 | //! let res: Option<Vec<_>> = v.into_iter().collect(); |
| 454 | //! assert_eq!(res, Some(vec![2, 4, 8])); |
| 455 | //! ``` |
| 456 | //! |
| 457 | //! [`Option`] also implements the [`Product`][impl-Product] and |
| 458 | //! [`Sum`][impl-Sum] traits, allowing an iterator over [`Option`] values |
| 459 | //! to provide the [`product`][Iterator::product] and |
| 460 | //! [`sum`][Iterator::sum] methods. |
| 461 | //! |
| 462 | //! [impl-Product]: Option#impl-Product%3COption%3CU%3E%3E-for-Option%3CT%3E |
| 463 | //! [impl-Sum]: Option#impl-Sum%3COption%3CU%3E%3E-for-Option%3CT%3E |
| 464 | //! |
| 465 | //! ``` |
| 466 | //! let v = [None, Some(1), Some(2), Some(3)]; |
| 467 | //! let res: Option<i32> = v.into_iter().sum(); |
| 468 | //! assert_eq!(res, None); |
| 469 | //! let v = [Some(1), Some(2), Some(21)]; |
| 470 | //! let res: Option<i32> = v.into_iter().product(); |
| 471 | //! assert_eq!(res, Some(42)); |
| 472 | //! ``` |
| 473 | //! |
| 474 | //! ## Modifying an [`Option`] in-place |
| 475 | //! |
| 476 | //! These methods return a mutable reference to the contained value of an |
| 477 | //! [`Option<T>`]: |
| 478 | //! |
| 479 | //! * [`insert`] inserts a value, dropping any old contents |
| 480 | //! * [`get_or_insert`] gets the current value, inserting a provided |
| 481 | //! default value if it is [`None`] |
| 482 | //! * [`get_or_insert_default`] gets the current value, inserting the |
| 483 | //! default value of type `T` (which must implement [`Default`]) if it is |
| 484 | //! [`None`] |
| 485 | //! * [`get_or_insert_with`] gets the current value, inserting a default |
| 486 | //! computed by the provided function if it is [`None`] |
| 487 | //! |
| 488 | //! [`get_or_insert`]: Option::get_or_insert |
| 489 | //! [`get_or_insert_default`]: Option::get_or_insert_default |
| 490 | //! [`get_or_insert_with`]: Option::get_or_insert_with |
| 491 | //! [`insert`]: Option::insert |
| 492 | //! |
| 493 | //! These methods transfer ownership of the contained value of an |
| 494 | //! [`Option`]: |
| 495 | //! |
| 496 | //! * [`take`] takes ownership of the contained value of an [`Option`], if |
| 497 | //! any, replacing the [`Option`] with [`None`] |
| 498 | //! * [`replace`] takes ownership of the contained value of an [`Option`], |
| 499 | //! if any, replacing the [`Option`] with a [`Some`] containing the |
| 500 | //! provided value |
| 501 | //! |
| 502 | //! [`replace`]: Option::replace |
| 503 | //! [`take`]: Option::take |
| 504 | //! |
| 505 | //! # Examples |
| 506 | //! |
| 507 | //! Basic pattern matching on [`Option`]: |
| 508 | //! |
| 509 | //! ``` |
| 510 | //! let msg = Some("howdy" ); |
| 511 | //! |
| 512 | //! // Take a reference to the contained string |
| 513 | //! if let Some(m) = &msg { |
| 514 | //! println!("{}" , *m); |
| 515 | //! } |
| 516 | //! |
| 517 | //! // Remove the contained string, destroying the Option |
| 518 | //! let unwrapped_msg = msg.unwrap_or("default message" ); |
| 519 | //! ``` |
| 520 | //! |
| 521 | //! Initialize a result to [`None`] before a loop: |
| 522 | //! |
| 523 | //! ``` |
| 524 | //! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) } |
| 525 | //! |
| 526 | //! // A list of data to search through. |
| 527 | //! let all_the_big_things = [ |
| 528 | //! Kingdom::Plant(250, "redwood" ), |
| 529 | //! Kingdom::Plant(230, "noble fir" ), |
| 530 | //! Kingdom::Plant(229, "sugar pine" ), |
| 531 | //! Kingdom::Animal(25, "blue whale" ), |
| 532 | //! Kingdom::Animal(19, "fin whale" ), |
| 533 | //! Kingdom::Animal(15, "north pacific right whale" ), |
| 534 | //! ]; |
| 535 | //! |
| 536 | //! // We're going to search for the name of the biggest animal, |
| 537 | //! // but to start with we've just got `None`. |
| 538 | //! let mut name_of_biggest_animal = None; |
| 539 | //! let mut size_of_biggest_animal = 0; |
| 540 | //! for big_thing in &all_the_big_things { |
| 541 | //! match *big_thing { |
| 542 | //! Kingdom::Animal(size, name) if size > size_of_biggest_animal => { |
| 543 | //! // Now we've found the name of some big animal |
| 544 | //! size_of_biggest_animal = size; |
| 545 | //! name_of_biggest_animal = Some(name); |
| 546 | //! } |
| 547 | //! Kingdom::Animal(..) | Kingdom::Plant(..) => () |
| 548 | //! } |
| 549 | //! } |
| 550 | //! |
| 551 | //! match name_of_biggest_animal { |
| 552 | //! Some(name) => println!("the biggest animal is {name}" ), |
| 553 | //! None => println!("there are no animals :(" ), |
| 554 | //! } |
| 555 | //! ``` |
| 556 | |
| 557 | #![stable (feature = "rust1" , since = "1.0.0" )] |
| 558 | |
| 559 | use crate::iter::{self, FusedIterator, TrustedLen}; |
| 560 | use crate::ops::{self, ControlFlow, Deref, DerefMut}; |
| 561 | use crate::panicking::{panic, panic_display}; |
| 562 | use crate::pin::Pin; |
| 563 | use crate::{cmp, convert, hint, mem, slice}; |
| 564 | |
| 565 | /// The `Option` type. See [the module level documentation](self) for more. |
| 566 | #[doc (search_unbox)] |
| 567 | #[derive (Copy, Eq, Debug, Hash)] |
| 568 | #[rustc_diagnostic_item = "Option" ] |
| 569 | #[lang = "Option" ] |
| 570 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 571 | #[allow (clippy::derived_hash_with_manual_eq)] // PartialEq is manually implemented equivalently |
| 572 | pub enum Option<T> { |
| 573 | /// No value. |
| 574 | #[lang = "None" ] |
| 575 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 576 | None, |
| 577 | /// Some value of type `T`. |
| 578 | #[lang = "Some" ] |
| 579 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 580 | Some(#[stable (feature = "rust1" , since = "1.0.0" )] T), |
| 581 | } |
| 582 | |
| 583 | ///////////////////////////////////////////////////////////////////////////// |
| 584 | // Type implementation |
| 585 | ///////////////////////////////////////////////////////////////////////////// |
| 586 | |
| 587 | impl<T> Option<T> { |
| 588 | ///////////////////////////////////////////////////////////////////////// |
| 589 | // Querying the contained values |
| 590 | ///////////////////////////////////////////////////////////////////////// |
| 591 | |
| 592 | /// Returns `true` if the option is a [`Some`] value. |
| 593 | /// |
| 594 | /// # Examples |
| 595 | /// |
| 596 | /// ``` |
| 597 | /// let x: Option<u32> = Some(2); |
| 598 | /// assert_eq!(x.is_some(), true); |
| 599 | /// |
| 600 | /// let x: Option<u32> = None; |
| 601 | /// assert_eq!(x.is_some(), false); |
| 602 | /// ``` |
| 603 | #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead" ] |
| 604 | #[inline ] |
| 605 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 606 | #[rustc_const_stable (feature = "const_option_basics" , since = "1.48.0" )] |
| 607 | pub const fn is_some(&self) -> bool { |
| 608 | matches!(*self, Some(_)) |
| 609 | } |
| 610 | |
| 611 | /// Returns `true` if the option is a [`Some`] and the value inside of it matches a predicate. |
| 612 | /// |
| 613 | /// # Examples |
| 614 | /// |
| 615 | /// ``` |
| 616 | /// let x: Option<u32> = Some(2); |
| 617 | /// assert_eq!(x.is_some_and(|x| x > 1), true); |
| 618 | /// |
| 619 | /// let x: Option<u32> = Some(0); |
| 620 | /// assert_eq!(x.is_some_and(|x| x > 1), false); |
| 621 | /// |
| 622 | /// let x: Option<u32> = None; |
| 623 | /// assert_eq!(x.is_some_and(|x| x > 1), false); |
| 624 | /// ``` |
| 625 | #[must_use ] |
| 626 | #[inline ] |
| 627 | #[stable (feature = "is_some_and" , since = "1.70.0" )] |
| 628 | pub fn is_some_and(self, f: impl FnOnce(T) -> bool) -> bool { |
| 629 | match self { |
| 630 | None => false, |
| 631 | Some(x) => f(x), |
| 632 | } |
| 633 | } |
| 634 | |
| 635 | /// Returns `true` if the option is a [`None`] value. |
| 636 | /// |
| 637 | /// # Examples |
| 638 | /// |
| 639 | /// ``` |
| 640 | /// let x: Option<u32> = Some(2); |
| 641 | /// assert_eq!(x.is_none(), false); |
| 642 | /// |
| 643 | /// let x: Option<u32> = None; |
| 644 | /// assert_eq!(x.is_none(), true); |
| 645 | /// ``` |
| 646 | #[must_use = "if you intended to assert that this doesn't have a value, consider \ |
| 647 | wrapping this in an `assert!()` instead" ] |
| 648 | #[inline ] |
| 649 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 650 | #[rustc_const_stable (feature = "const_option_basics" , since = "1.48.0" )] |
| 651 | pub const fn is_none(&self) -> bool { |
| 652 | !self.is_some() |
| 653 | } |
| 654 | |
| 655 | /// Returns `true` if the option is a [`None`] or the value inside of it matches a predicate. |
| 656 | /// |
| 657 | /// # Examples |
| 658 | /// |
| 659 | /// ``` |
| 660 | /// let x: Option<u32> = Some(2); |
| 661 | /// assert_eq!(x.is_none_or(|x| x > 1), true); |
| 662 | /// |
| 663 | /// let x: Option<u32> = Some(0); |
| 664 | /// assert_eq!(x.is_none_or(|x| x > 1), false); |
| 665 | /// |
| 666 | /// let x: Option<u32> = None; |
| 667 | /// assert_eq!(x.is_none_or(|x| x > 1), true); |
| 668 | /// ``` |
| 669 | #[must_use ] |
| 670 | #[inline ] |
| 671 | #[stable (feature = "is_none_or" , since = "1.82.0" )] |
| 672 | pub fn is_none_or(self, f: impl FnOnce(T) -> bool) -> bool { |
| 673 | match self { |
| 674 | None => true, |
| 675 | Some(x) => f(x), |
| 676 | } |
| 677 | } |
| 678 | |
| 679 | ///////////////////////////////////////////////////////////////////////// |
| 680 | // Adapter for working with references |
| 681 | ///////////////////////////////////////////////////////////////////////// |
| 682 | |
| 683 | /// Converts from `&Option<T>` to `Option<&T>`. |
| 684 | /// |
| 685 | /// # Examples |
| 686 | /// |
| 687 | /// Calculates the length of an <code>Option<[String]></code> as an <code>Option<[usize]></code> |
| 688 | /// without moving the [`String`]. The [`map`] method takes the `self` argument by value, |
| 689 | /// consuming the original, so this technique uses `as_ref` to first take an `Option` to a |
| 690 | /// reference to the value inside the original. |
| 691 | /// |
| 692 | /// [`map`]: Option::map |
| 693 | /// [String]: ../../std/string/struct.String.html "String" |
| 694 | /// [`String`]: ../../std/string/struct.String.html "String" |
| 695 | /// |
| 696 | /// ``` |
| 697 | /// let text: Option<String> = Some("Hello, world!" .to_string()); |
| 698 | /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`, |
| 699 | /// // then consume *that* with `map`, leaving `text` on the stack. |
| 700 | /// let text_length: Option<usize> = text.as_ref().map(|s| s.len()); |
| 701 | /// println!("still can print text: {text:?}" ); |
| 702 | /// ``` |
| 703 | #[inline ] |
| 704 | #[rustc_const_stable (feature = "const_option_basics" , since = "1.48.0" )] |
| 705 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 706 | pub const fn as_ref(&self) -> Option<&T> { |
| 707 | match *self { |
| 708 | Some(ref x) => Some(x), |
| 709 | None => None, |
| 710 | } |
| 711 | } |
| 712 | |
| 713 | /// Converts from `&mut Option<T>` to `Option<&mut T>`. |
| 714 | /// |
| 715 | /// # Examples |
| 716 | /// |
| 717 | /// ``` |
| 718 | /// let mut x = Some(2); |
| 719 | /// match x.as_mut() { |
| 720 | /// Some(v) => *v = 42, |
| 721 | /// None => {}, |
| 722 | /// } |
| 723 | /// assert_eq!(x, Some(42)); |
| 724 | /// ``` |
| 725 | #[inline ] |
| 726 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 727 | #[rustc_const_stable (feature = "const_option" , since = "1.83.0" )] |
| 728 | pub const fn as_mut(&mut self) -> Option<&mut T> { |
| 729 | match *self { |
| 730 | Some(ref mut x) => Some(x), |
| 731 | None => None, |
| 732 | } |
| 733 | } |
| 734 | |
| 735 | /// Converts from <code>[Pin]<[&]Option\<T>></code> to <code>Option<[Pin]<[&]T>></code>. |
| 736 | /// |
| 737 | /// [&]: reference "shared reference" |
| 738 | #[inline ] |
| 739 | #[must_use ] |
| 740 | #[stable (feature = "pin" , since = "1.33.0" )] |
| 741 | #[rustc_const_stable (feature = "const_option_ext" , since = "1.84.0" )] |
| 742 | pub const fn as_pin_ref(self: Pin<&Self>) -> Option<Pin<&T>> { |
| 743 | // FIXME(const-hack): use `map` once that is possible |
| 744 | match Pin::get_ref(self).as_ref() { |
| 745 | // SAFETY: `x` is guaranteed to be pinned because it comes from `self` |
| 746 | // which is pinned. |
| 747 | Some(x) => unsafe { Some(Pin::new_unchecked(x)) }, |
| 748 | None => None, |
| 749 | } |
| 750 | } |
| 751 | |
| 752 | /// Converts from <code>[Pin]<[&mut] Option\<T>></code> to <code>Option<[Pin]<[&mut] T>></code>. |
| 753 | /// |
| 754 | /// [&mut]: reference "mutable reference" |
| 755 | #[inline ] |
| 756 | #[must_use ] |
| 757 | #[stable (feature = "pin" , since = "1.33.0" )] |
| 758 | #[rustc_const_stable (feature = "const_option_ext" , since = "1.84.0" )] |
| 759 | pub const fn as_pin_mut(self: Pin<&mut Self>) -> Option<Pin<&mut T>> { |
| 760 | // SAFETY: `get_unchecked_mut` is never used to move the `Option` inside `self`. |
| 761 | // `x` is guaranteed to be pinned because it comes from `self` which is pinned. |
| 762 | unsafe { |
| 763 | // FIXME(const-hack): use `map` once that is possible |
| 764 | match Pin::get_unchecked_mut(self).as_mut() { |
| 765 | Some(x) => Some(Pin::new_unchecked(x)), |
| 766 | None => None, |
| 767 | } |
| 768 | } |
| 769 | } |
| 770 | |
| 771 | #[inline ] |
| 772 | const fn len(&self) -> usize { |
| 773 | // Using the intrinsic avoids emitting a branch to get the 0 or 1. |
| 774 | let discriminant: isize = crate::intrinsics::discriminant_value(self); |
| 775 | discriminant as usize |
| 776 | } |
| 777 | |
| 778 | /// Returns a slice of the contained value, if any. If this is `None`, an |
| 779 | /// empty slice is returned. This can be useful to have a single type of |
| 780 | /// iterator over an `Option` or slice. |
| 781 | /// |
| 782 | /// Note: Should you have an `Option<&T>` and wish to get a slice of `T`, |
| 783 | /// you can unpack it via `opt.map_or(&[], std::slice::from_ref)`. |
| 784 | /// |
| 785 | /// # Examples |
| 786 | /// |
| 787 | /// ```rust |
| 788 | /// assert_eq!( |
| 789 | /// [Some(1234).as_slice(), None.as_slice()], |
| 790 | /// [&[1234][..], &[][..]], |
| 791 | /// ); |
| 792 | /// ``` |
| 793 | /// |
| 794 | /// The inverse of this function is (discounting |
| 795 | /// borrowing) [`[_]::first`](slice::first): |
| 796 | /// |
| 797 | /// ```rust |
| 798 | /// for i in [Some(1234_u16), None] { |
| 799 | /// assert_eq!(i.as_ref(), i.as_slice().first()); |
| 800 | /// } |
| 801 | /// ``` |
| 802 | #[inline ] |
| 803 | #[must_use ] |
| 804 | #[stable (feature = "option_as_slice" , since = "1.75.0" )] |
| 805 | #[rustc_const_stable (feature = "const_option_ext" , since = "1.84.0" )] |
| 806 | pub const fn as_slice(&self) -> &[T] { |
| 807 | // SAFETY: When the `Option` is `Some`, we're using the actual pointer |
| 808 | // to the payload, with a length of 1, so this is equivalent to |
| 809 | // `slice::from_ref`, and thus is safe. |
| 810 | // When the `Option` is `None`, the length used is 0, so to be safe it |
| 811 | // just needs to be aligned, which it is because `&self` is aligned and |
| 812 | // the offset used is a multiple of alignment. |
| 813 | // |
| 814 | // In the new version, the intrinsic always returns a pointer to an |
| 815 | // in-bounds and correctly aligned position for a `T` (even if in the |
| 816 | // `None` case it's just padding). |
| 817 | unsafe { |
| 818 | slice::from_raw_parts( |
| 819 | (self as *const Self).byte_add(core::mem::offset_of!(Self, Some.0)).cast(), |
| 820 | self.len(), |
| 821 | ) |
| 822 | } |
| 823 | } |
| 824 | |
| 825 | /// Returns a mutable slice of the contained value, if any. If this is |
| 826 | /// `None`, an empty slice is returned. This can be useful to have a |
| 827 | /// single type of iterator over an `Option` or slice. |
| 828 | /// |
| 829 | /// Note: Should you have an `Option<&mut T>` instead of a |
| 830 | /// `&mut Option<T>`, which this method takes, you can obtain a mutable |
| 831 | /// slice via `opt.map_or(&mut [], std::slice::from_mut)`. |
| 832 | /// |
| 833 | /// # Examples |
| 834 | /// |
| 835 | /// ```rust |
| 836 | /// assert_eq!( |
| 837 | /// [Some(1234).as_mut_slice(), None.as_mut_slice()], |
| 838 | /// [&mut [1234][..], &mut [][..]], |
| 839 | /// ); |
| 840 | /// ``` |
| 841 | /// |
| 842 | /// The result is a mutable slice of zero or one items that points into |
| 843 | /// our original `Option`: |
| 844 | /// |
| 845 | /// ```rust |
| 846 | /// let mut x = Some(1234); |
| 847 | /// x.as_mut_slice()[0] += 1; |
| 848 | /// assert_eq!(x, Some(1235)); |
| 849 | /// ``` |
| 850 | /// |
| 851 | /// The inverse of this method (discounting borrowing) |
| 852 | /// is [`[_]::first_mut`](slice::first_mut): |
| 853 | /// |
| 854 | /// ```rust |
| 855 | /// assert_eq!(Some(123).as_mut_slice().first_mut(), Some(&mut 123)) |
| 856 | /// ``` |
| 857 | #[inline ] |
| 858 | #[must_use ] |
| 859 | #[stable (feature = "option_as_slice" , since = "1.75.0" )] |
| 860 | #[rustc_const_stable (feature = "const_option_ext" , since = "1.84.0" )] |
| 861 | pub const fn as_mut_slice(&mut self) -> &mut [T] { |
| 862 | // SAFETY: When the `Option` is `Some`, we're using the actual pointer |
| 863 | // to the payload, with a length of 1, so this is equivalent to |
| 864 | // `slice::from_mut`, and thus is safe. |
| 865 | // When the `Option` is `None`, the length used is 0, so to be safe it |
| 866 | // just needs to be aligned, which it is because `&self` is aligned and |
| 867 | // the offset used is a multiple of alignment. |
| 868 | // |
| 869 | // In the new version, the intrinsic creates a `*const T` from a |
| 870 | // mutable reference so it is safe to cast back to a mutable pointer |
| 871 | // here. As with `as_slice`, the intrinsic always returns a pointer to |
| 872 | // an in-bounds and correctly aligned position for a `T` (even if in |
| 873 | // the `None` case it's just padding). |
| 874 | unsafe { |
| 875 | slice::from_raw_parts_mut( |
| 876 | (self as *mut Self).byte_add(core::mem::offset_of!(Self, Some.0)).cast(), |
| 877 | self.len(), |
| 878 | ) |
| 879 | } |
| 880 | } |
| 881 | |
| 882 | ///////////////////////////////////////////////////////////////////////// |
| 883 | // Getting to contained values |
| 884 | ///////////////////////////////////////////////////////////////////////// |
| 885 | |
| 886 | /// Returns the contained [`Some`] value, consuming the `self` value. |
| 887 | /// |
| 888 | /// # Panics |
| 889 | /// |
| 890 | /// Panics if the value is a [`None`] with a custom panic message provided by |
| 891 | /// `msg`. |
| 892 | /// |
| 893 | /// # Examples |
| 894 | /// |
| 895 | /// ``` |
| 896 | /// let x = Some("value" ); |
| 897 | /// assert_eq!(x.expect("fruits are healthy" ), "value" ); |
| 898 | /// ``` |
| 899 | /// |
| 900 | /// ```should_panic |
| 901 | /// let x: Option<&str> = None; |
| 902 | /// x.expect("fruits are healthy" ); // panics with `fruits are healthy` |
| 903 | /// ``` |
| 904 | /// |
| 905 | /// # Recommended Message Style |
| 906 | /// |
| 907 | /// We recommend that `expect` messages are used to describe the reason you |
| 908 | /// _expect_ the `Option` should be `Some`. |
| 909 | /// |
| 910 | /// ```should_panic |
| 911 | /// # let slice: &[u8] = &[]; |
| 912 | /// let item = slice.get(0) |
| 913 | /// .expect("slice should not be empty" ); |
| 914 | /// ``` |
| 915 | /// |
| 916 | /// **Hint**: If you're having trouble remembering how to phrase expect |
| 917 | /// error messages remember to focus on the word "should" as in "env |
| 918 | /// variable should be set by blah" or "the given binary should be available |
| 919 | /// and executable by the current user". |
| 920 | /// |
| 921 | /// For more detail on expect message styles and the reasoning behind our |
| 922 | /// recommendation please refer to the section on ["Common Message |
| 923 | /// Styles"](../../std/error/index.html#common-message-styles) in the [`std::error`](../../std/error/index.html) module docs. |
| 924 | #[inline ] |
| 925 | #[track_caller ] |
| 926 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 927 | #[rustc_diagnostic_item = "option_expect" ] |
| 928 | #[rustc_allow_const_fn_unstable (const_precise_live_drops)] |
| 929 | #[rustc_const_stable (feature = "const_option" , since = "1.83.0" )] |
| 930 | pub const fn expect(self, msg: &str) -> T { |
| 931 | match self { |
| 932 | Some(val) => val, |
| 933 | None => expect_failed(msg), |
| 934 | } |
| 935 | } |
| 936 | |
| 937 | /// Returns the contained [`Some`] value, consuming the `self` value. |
| 938 | /// |
| 939 | /// Because this function may panic, its use is generally discouraged. |
| 940 | /// Panics are meant for unrecoverable errors, and |
| 941 | /// [may abort the entire program][panic-abort]. |
| 942 | /// |
| 943 | /// Instead, prefer to use pattern matching and handle the [`None`] |
| 944 | /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or |
| 945 | /// [`unwrap_or_default`]. In functions returning `Option`, you can use |
| 946 | /// [the `?` (try) operator][try-option]. |
| 947 | /// |
| 948 | /// [panic-abort]: https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html |
| 949 | /// [try-option]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#where-the--operator-can-be-used |
| 950 | /// [`unwrap_or`]: Option::unwrap_or |
| 951 | /// [`unwrap_or_else`]: Option::unwrap_or_else |
| 952 | /// [`unwrap_or_default`]: Option::unwrap_or_default |
| 953 | /// |
| 954 | /// # Panics |
| 955 | /// |
| 956 | /// Panics if the self value equals [`None`]. |
| 957 | /// |
| 958 | /// # Examples |
| 959 | /// |
| 960 | /// ``` |
| 961 | /// let x = Some("air" ); |
| 962 | /// assert_eq!(x.unwrap(), "air" ); |
| 963 | /// ``` |
| 964 | /// |
| 965 | /// ```should_panic |
| 966 | /// let x: Option<&str> = None; |
| 967 | /// assert_eq!(x.unwrap(), "air" ); // fails |
| 968 | /// ``` |
| 969 | #[inline (always)] |
| 970 | #[track_caller ] |
| 971 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 972 | #[rustc_diagnostic_item = "option_unwrap" ] |
| 973 | #[rustc_allow_const_fn_unstable (const_precise_live_drops)] |
| 974 | #[rustc_const_stable (feature = "const_option" , since = "1.83.0" )] |
| 975 | pub const fn unwrap(self) -> T { |
| 976 | match self { |
| 977 | Some(val) => val, |
| 978 | None => unwrap_failed(), |
| 979 | } |
| 980 | } |
| 981 | |
| 982 | /// Returns the contained [`Some`] value or a provided default. |
| 983 | /// |
| 984 | /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing |
| 985 | /// the result of a function call, it is recommended to use [`unwrap_or_else`], |
| 986 | /// which is lazily evaluated. |
| 987 | /// |
| 988 | /// [`unwrap_or_else`]: Option::unwrap_or_else |
| 989 | /// |
| 990 | /// # Examples |
| 991 | /// |
| 992 | /// ``` |
| 993 | /// assert_eq!(Some("car" ).unwrap_or("bike" ), "car" ); |
| 994 | /// assert_eq!(None.unwrap_or("bike" ), "bike" ); |
| 995 | /// ``` |
| 996 | #[inline ] |
| 997 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 998 | pub fn unwrap_or(self, default: T) -> T { |
| 999 | match self { |
| 1000 | Some(x) => x, |
| 1001 | None => default, |
| 1002 | } |
| 1003 | } |
| 1004 | |
| 1005 | /// Returns the contained [`Some`] value or computes it from a closure. |
| 1006 | /// |
| 1007 | /// # Examples |
| 1008 | /// |
| 1009 | /// ``` |
| 1010 | /// let k = 10; |
| 1011 | /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4); |
| 1012 | /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20); |
| 1013 | /// ``` |
| 1014 | #[inline ] |
| 1015 | #[track_caller ] |
| 1016 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 1017 | pub fn unwrap_or_else<F>(self, f: F) -> T |
| 1018 | where |
| 1019 | F: FnOnce() -> T, |
| 1020 | { |
| 1021 | match self { |
| 1022 | Some(x) => x, |
| 1023 | None => f(), |
| 1024 | } |
| 1025 | } |
| 1026 | |
| 1027 | /// Returns the contained [`Some`] value or a default. |
| 1028 | /// |
| 1029 | /// Consumes the `self` argument then, if [`Some`], returns the contained |
| 1030 | /// value, otherwise if [`None`], returns the [default value] for that |
| 1031 | /// type. |
| 1032 | /// |
| 1033 | /// # Examples |
| 1034 | /// |
| 1035 | /// ``` |
| 1036 | /// let x: Option<u32> = None; |
| 1037 | /// let y: Option<u32> = Some(12); |
| 1038 | /// |
| 1039 | /// assert_eq!(x.unwrap_or_default(), 0); |
| 1040 | /// assert_eq!(y.unwrap_or_default(), 12); |
| 1041 | /// ``` |
| 1042 | /// |
| 1043 | /// [default value]: Default::default |
| 1044 | /// [`parse`]: str::parse |
| 1045 | /// [`FromStr`]: crate::str::FromStr |
| 1046 | #[inline ] |
| 1047 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 1048 | pub fn unwrap_or_default(self) -> T |
| 1049 | where |
| 1050 | T: Default, |
| 1051 | { |
| 1052 | match self { |
| 1053 | Some(x) => x, |
| 1054 | None => T::default(), |
| 1055 | } |
| 1056 | } |
| 1057 | |
| 1058 | /// Returns the contained [`Some`] value, consuming the `self` value, |
| 1059 | /// without checking that the value is not [`None`]. |
| 1060 | /// |
| 1061 | /// # Safety |
| 1062 | /// |
| 1063 | /// Calling this method on [`None`] is *[undefined behavior]*. |
| 1064 | /// |
| 1065 | /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html |
| 1066 | /// |
| 1067 | /// # Examples |
| 1068 | /// |
| 1069 | /// ``` |
| 1070 | /// let x = Some("air" ); |
| 1071 | /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air" ); |
| 1072 | /// ``` |
| 1073 | /// |
| 1074 | /// ```no_run |
| 1075 | /// let x: Option<&str> = None; |
| 1076 | /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air" ); // Undefined behavior! |
| 1077 | /// ``` |
| 1078 | #[inline ] |
| 1079 | #[track_caller ] |
| 1080 | #[stable (feature = "option_result_unwrap_unchecked" , since = "1.58.0" )] |
| 1081 | #[rustc_allow_const_fn_unstable (const_precise_live_drops)] |
| 1082 | #[rustc_const_stable (feature = "const_option" , since = "1.83.0" )] |
| 1083 | pub const unsafe fn unwrap_unchecked(self) -> T { |
| 1084 | match self { |
| 1085 | Some(val) => val, |
| 1086 | // SAFETY: the safety contract must be upheld by the caller. |
| 1087 | None => unsafe { hint::unreachable_unchecked() }, |
| 1088 | } |
| 1089 | } |
| 1090 | |
| 1091 | ///////////////////////////////////////////////////////////////////////// |
| 1092 | // Transforming contained values |
| 1093 | ///////////////////////////////////////////////////////////////////////// |
| 1094 | |
| 1095 | /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value (if `Some`) or returns `None` (if `None`). |
| 1096 | /// |
| 1097 | /// # Examples |
| 1098 | /// |
| 1099 | /// Calculates the length of an <code>Option<[String]></code> as an |
| 1100 | /// <code>Option<[usize]></code>, consuming the original: |
| 1101 | /// |
| 1102 | /// [String]: ../../std/string/struct.String.html "String" |
| 1103 | /// ``` |
| 1104 | /// let maybe_some_string = Some(String::from("Hello, World!" )); |
| 1105 | /// // `Option::map` takes self *by value*, consuming `maybe_some_string` |
| 1106 | /// let maybe_some_len = maybe_some_string.map(|s| s.len()); |
| 1107 | /// assert_eq!(maybe_some_len, Some(13)); |
| 1108 | /// |
| 1109 | /// let x: Option<&str> = None; |
| 1110 | /// assert_eq!(x.map(|s| s.len()), None); |
| 1111 | /// ``` |
| 1112 | #[inline ] |
| 1113 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 1114 | pub fn map<U, F>(self, f: F) -> Option<U> |
| 1115 | where |
| 1116 | F: FnOnce(T) -> U, |
| 1117 | { |
| 1118 | match self { |
| 1119 | Some(x) => Some(f(x)), |
| 1120 | None => None, |
| 1121 | } |
| 1122 | } |
| 1123 | |
| 1124 | /// Calls a function with a reference to the contained value if [`Some`]. |
| 1125 | /// |
| 1126 | /// Returns the original option. |
| 1127 | /// |
| 1128 | /// # Examples |
| 1129 | /// |
| 1130 | /// ``` |
| 1131 | /// let list = vec![1, 2, 3]; |
| 1132 | /// |
| 1133 | /// // prints "got: 2" |
| 1134 | /// let x = list |
| 1135 | /// .get(1) |
| 1136 | /// .inspect(|x| println!("got: {x}" )) |
| 1137 | /// .expect("list should be long enough" ); |
| 1138 | /// |
| 1139 | /// // prints nothing |
| 1140 | /// list.get(5).inspect(|x| println!("got: {x}" )); |
| 1141 | /// ``` |
| 1142 | #[inline ] |
| 1143 | #[stable (feature = "result_option_inspect" , since = "1.76.0" )] |
| 1144 | pub fn inspect<F: FnOnce(&T)>(self, f: F) -> Self { |
| 1145 | if let Some(ref x) = self { |
| 1146 | f(x); |
| 1147 | } |
| 1148 | |
| 1149 | self |
| 1150 | } |
| 1151 | |
| 1152 | /// Returns the provided default result (if none), |
| 1153 | /// or applies a function to the contained value (if any). |
| 1154 | /// |
| 1155 | /// Arguments passed to `map_or` are eagerly evaluated; if you are passing |
| 1156 | /// the result of a function call, it is recommended to use [`map_or_else`], |
| 1157 | /// which is lazily evaluated. |
| 1158 | /// |
| 1159 | /// [`map_or_else`]: Option::map_or_else |
| 1160 | /// |
| 1161 | /// # Examples |
| 1162 | /// |
| 1163 | /// ``` |
| 1164 | /// let x = Some("foo" ); |
| 1165 | /// assert_eq!(x.map_or(42, |v| v.len()), 3); |
| 1166 | /// |
| 1167 | /// let x: Option<&str> = None; |
| 1168 | /// assert_eq!(x.map_or(42, |v| v.len()), 42); |
| 1169 | /// ``` |
| 1170 | #[inline ] |
| 1171 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 1172 | #[must_use = "if you don't need the returned value, use `if let` instead" ] |
| 1173 | pub fn map_or<U, F>(self, default: U, f: F) -> U |
| 1174 | where |
| 1175 | F: FnOnce(T) -> U, |
| 1176 | { |
| 1177 | match self { |
| 1178 | Some(t) => f(t), |
| 1179 | None => default, |
| 1180 | } |
| 1181 | } |
| 1182 | |
| 1183 | /// Computes a default function result (if none), or |
| 1184 | /// applies a different function to the contained value (if any). |
| 1185 | /// |
| 1186 | /// # Basic examples |
| 1187 | /// |
| 1188 | /// ``` |
| 1189 | /// let k = 21; |
| 1190 | /// |
| 1191 | /// let x = Some("foo" ); |
| 1192 | /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3); |
| 1193 | /// |
| 1194 | /// let x: Option<&str> = None; |
| 1195 | /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42); |
| 1196 | /// ``` |
| 1197 | /// |
| 1198 | /// # Handling a Result-based fallback |
| 1199 | /// |
| 1200 | /// A somewhat common occurrence when dealing with optional values |
| 1201 | /// in combination with [`Result<T, E>`] is the case where one wants to invoke |
| 1202 | /// a fallible fallback if the option is not present. This example |
| 1203 | /// parses a command line argument (if present), or the contents of a file to |
| 1204 | /// an integer. However, unlike accessing the command line argument, reading |
| 1205 | /// the file is fallible, so it must be wrapped with `Ok`. |
| 1206 | /// |
| 1207 | /// ```no_run |
| 1208 | /// # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 1209 | /// let v: u64 = std::env::args() |
| 1210 | /// .nth(1) |
| 1211 | /// .map_or_else(|| std::fs::read_to_string("/etc/someconfig.conf" ), Ok)? |
| 1212 | /// .parse()?; |
| 1213 | /// # Ok(()) |
| 1214 | /// # } |
| 1215 | /// ``` |
| 1216 | #[inline ] |
| 1217 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 1218 | pub fn map_or_else<U, D, F>(self, default: D, f: F) -> U |
| 1219 | where |
| 1220 | D: FnOnce() -> U, |
| 1221 | F: FnOnce(T) -> U, |
| 1222 | { |
| 1223 | match self { |
| 1224 | Some(t) => f(t), |
| 1225 | None => default(), |
| 1226 | } |
| 1227 | } |
| 1228 | |
| 1229 | /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to |
| 1230 | /// [`Ok(v)`] and [`None`] to [`Err(err)`]. |
| 1231 | /// |
| 1232 | /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the |
| 1233 | /// result of a function call, it is recommended to use [`ok_or_else`], which is |
| 1234 | /// lazily evaluated. |
| 1235 | /// |
| 1236 | /// [`Ok(v)`]: Ok |
| 1237 | /// [`Err(err)`]: Err |
| 1238 | /// [`Some(v)`]: Some |
| 1239 | /// [`ok_or_else`]: Option::ok_or_else |
| 1240 | /// |
| 1241 | /// # Examples |
| 1242 | /// |
| 1243 | /// ``` |
| 1244 | /// let x = Some("foo" ); |
| 1245 | /// assert_eq!(x.ok_or(0), Ok("foo" )); |
| 1246 | /// |
| 1247 | /// let x: Option<&str> = None; |
| 1248 | /// assert_eq!(x.ok_or(0), Err(0)); |
| 1249 | /// ``` |
| 1250 | #[inline ] |
| 1251 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 1252 | pub fn ok_or<E>(self, err: E) -> Result<T, E> { |
| 1253 | match self { |
| 1254 | Some(v) => Ok(v), |
| 1255 | None => Err(err), |
| 1256 | } |
| 1257 | } |
| 1258 | |
| 1259 | /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to |
| 1260 | /// [`Ok(v)`] and [`None`] to [`Err(err())`]. |
| 1261 | /// |
| 1262 | /// [`Ok(v)`]: Ok |
| 1263 | /// [`Err(err())`]: Err |
| 1264 | /// [`Some(v)`]: Some |
| 1265 | /// |
| 1266 | /// # Examples |
| 1267 | /// |
| 1268 | /// ``` |
| 1269 | /// let x = Some("foo" ); |
| 1270 | /// assert_eq!(x.ok_or_else(|| 0), Ok("foo" )); |
| 1271 | /// |
| 1272 | /// let x: Option<&str> = None; |
| 1273 | /// assert_eq!(x.ok_or_else(|| 0), Err(0)); |
| 1274 | /// ``` |
| 1275 | #[inline ] |
| 1276 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 1277 | pub fn ok_or_else<E, F>(self, err: F) -> Result<T, E> |
| 1278 | where |
| 1279 | F: FnOnce() -> E, |
| 1280 | { |
| 1281 | match self { |
| 1282 | Some(v) => Ok(v), |
| 1283 | None => Err(err()), |
| 1284 | } |
| 1285 | } |
| 1286 | |
| 1287 | /// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`. |
| 1288 | /// |
| 1289 | /// Leaves the original Option in-place, creating a new one with a reference |
| 1290 | /// to the original one, additionally coercing the contents via [`Deref`]. |
| 1291 | /// |
| 1292 | /// # Examples |
| 1293 | /// |
| 1294 | /// ``` |
| 1295 | /// let x: Option<String> = Some("hey" .to_owned()); |
| 1296 | /// assert_eq!(x.as_deref(), Some("hey" )); |
| 1297 | /// |
| 1298 | /// let x: Option<String> = None; |
| 1299 | /// assert_eq!(x.as_deref(), None); |
| 1300 | /// ``` |
| 1301 | #[inline ] |
| 1302 | #[stable (feature = "option_deref" , since = "1.40.0" )] |
| 1303 | pub fn as_deref(&self) -> Option<&T::Target> |
| 1304 | where |
| 1305 | T: Deref, |
| 1306 | { |
| 1307 | self.as_ref().map(|t| t.deref()) |
| 1308 | } |
| 1309 | |
| 1310 | /// Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`. |
| 1311 | /// |
| 1312 | /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to |
| 1313 | /// the inner type's [`Deref::Target`] type. |
| 1314 | /// |
| 1315 | /// # Examples |
| 1316 | /// |
| 1317 | /// ``` |
| 1318 | /// let mut x: Option<String> = Some("hey" .to_owned()); |
| 1319 | /// assert_eq!(x.as_deref_mut().map(|x| { |
| 1320 | /// x.make_ascii_uppercase(); |
| 1321 | /// x |
| 1322 | /// }), Some("HEY" .to_owned().as_mut_str())); |
| 1323 | /// ``` |
| 1324 | #[inline ] |
| 1325 | #[stable (feature = "option_deref" , since = "1.40.0" )] |
| 1326 | pub fn as_deref_mut(&mut self) -> Option<&mut T::Target> |
| 1327 | where |
| 1328 | T: DerefMut, |
| 1329 | { |
| 1330 | self.as_mut().map(|t| t.deref_mut()) |
| 1331 | } |
| 1332 | |
| 1333 | ///////////////////////////////////////////////////////////////////////// |
| 1334 | // Iterator constructors |
| 1335 | ///////////////////////////////////////////////////////////////////////// |
| 1336 | |
| 1337 | /// Returns an iterator over the possibly contained value. |
| 1338 | /// |
| 1339 | /// # Examples |
| 1340 | /// |
| 1341 | /// ``` |
| 1342 | /// let x = Some(4); |
| 1343 | /// assert_eq!(x.iter().next(), Some(&4)); |
| 1344 | /// |
| 1345 | /// let x: Option<u32> = None; |
| 1346 | /// assert_eq!(x.iter().next(), None); |
| 1347 | /// ``` |
| 1348 | #[inline ] |
| 1349 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 1350 | pub fn iter(&self) -> Iter<'_, T> { |
| 1351 | Iter { inner: Item { opt: self.as_ref() } } |
| 1352 | } |
| 1353 | |
| 1354 | /// Returns a mutable iterator over the possibly contained value. |
| 1355 | /// |
| 1356 | /// # Examples |
| 1357 | /// |
| 1358 | /// ``` |
| 1359 | /// let mut x = Some(4); |
| 1360 | /// match x.iter_mut().next() { |
| 1361 | /// Some(v) => *v = 42, |
| 1362 | /// None => {}, |
| 1363 | /// } |
| 1364 | /// assert_eq!(x, Some(42)); |
| 1365 | /// |
| 1366 | /// let mut x: Option<u32> = None; |
| 1367 | /// assert_eq!(x.iter_mut().next(), None); |
| 1368 | /// ``` |
| 1369 | #[inline ] |
| 1370 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 1371 | pub fn iter_mut(&mut self) -> IterMut<'_, T> { |
| 1372 | IterMut { inner: Item { opt: self.as_mut() } } |
| 1373 | } |
| 1374 | |
| 1375 | ///////////////////////////////////////////////////////////////////////// |
| 1376 | // Boolean operations on the values, eager and lazy |
| 1377 | ///////////////////////////////////////////////////////////////////////// |
| 1378 | |
| 1379 | /// Returns [`None`] if the option is [`None`], otherwise returns `optb`. |
| 1380 | /// |
| 1381 | /// Arguments passed to `and` are eagerly evaluated; if you are passing the |
| 1382 | /// result of a function call, it is recommended to use [`and_then`], which is |
| 1383 | /// lazily evaluated. |
| 1384 | /// |
| 1385 | /// [`and_then`]: Option::and_then |
| 1386 | /// |
| 1387 | /// # Examples |
| 1388 | /// |
| 1389 | /// ``` |
| 1390 | /// let x = Some(2); |
| 1391 | /// let y: Option<&str> = None; |
| 1392 | /// assert_eq!(x.and(y), None); |
| 1393 | /// |
| 1394 | /// let x: Option<u32> = None; |
| 1395 | /// let y = Some("foo" ); |
| 1396 | /// assert_eq!(x.and(y), None); |
| 1397 | /// |
| 1398 | /// let x = Some(2); |
| 1399 | /// let y = Some("foo" ); |
| 1400 | /// assert_eq!(x.and(y), Some("foo" )); |
| 1401 | /// |
| 1402 | /// let x: Option<u32> = None; |
| 1403 | /// let y: Option<&str> = None; |
| 1404 | /// assert_eq!(x.and(y), None); |
| 1405 | /// ``` |
| 1406 | #[inline ] |
| 1407 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 1408 | pub fn and<U>(self, optb: Option<U>) -> Option<U> { |
| 1409 | match self { |
| 1410 | Some(_) => optb, |
| 1411 | None => None, |
| 1412 | } |
| 1413 | } |
| 1414 | |
| 1415 | /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the |
| 1416 | /// wrapped value and returns the result. |
| 1417 | /// |
| 1418 | /// Some languages call this operation flatmap. |
| 1419 | /// |
| 1420 | /// # Examples |
| 1421 | /// |
| 1422 | /// ``` |
| 1423 | /// fn sq_then_to_string(x: u32) -> Option<String> { |
| 1424 | /// x.checked_mul(x).map(|sq| sq.to_string()) |
| 1425 | /// } |
| 1426 | /// |
| 1427 | /// assert_eq!(Some(2).and_then(sq_then_to_string), Some(4.to_string())); |
| 1428 | /// assert_eq!(Some(1_000_000).and_then(sq_then_to_string), None); // overflowed! |
| 1429 | /// assert_eq!(None.and_then(sq_then_to_string), None); |
| 1430 | /// ``` |
| 1431 | /// |
| 1432 | /// Often used to chain fallible operations that may return [`None`]. |
| 1433 | /// |
| 1434 | /// ``` |
| 1435 | /// let arr_2d = [["A0" , "A1" ], ["B0" , "B1" ]]; |
| 1436 | /// |
| 1437 | /// let item_0_1 = arr_2d.get(0).and_then(|row| row.get(1)); |
| 1438 | /// assert_eq!(item_0_1, Some(&"A1" )); |
| 1439 | /// |
| 1440 | /// let item_2_0 = arr_2d.get(2).and_then(|row| row.get(0)); |
| 1441 | /// assert_eq!(item_2_0, None); |
| 1442 | /// ``` |
| 1443 | #[doc (alias = "flatmap" )] |
| 1444 | #[inline ] |
| 1445 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 1446 | #[rustc_confusables ("flat_map" , "flatmap" )] |
| 1447 | pub fn and_then<U, F>(self, f: F) -> Option<U> |
| 1448 | where |
| 1449 | F: FnOnce(T) -> Option<U>, |
| 1450 | { |
| 1451 | match self { |
| 1452 | Some(x) => f(x), |
| 1453 | None => None, |
| 1454 | } |
| 1455 | } |
| 1456 | |
| 1457 | /// Returns [`None`] if the option is [`None`], otherwise calls `predicate` |
| 1458 | /// with the wrapped value and returns: |
| 1459 | /// |
| 1460 | /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped |
| 1461 | /// value), and |
| 1462 | /// - [`None`] if `predicate` returns `false`. |
| 1463 | /// |
| 1464 | /// This function works similar to [`Iterator::filter()`]. You can imagine |
| 1465 | /// the `Option<T>` being an iterator over one or zero elements. `filter()` |
| 1466 | /// lets you decide which elements to keep. |
| 1467 | /// |
| 1468 | /// # Examples |
| 1469 | /// |
| 1470 | /// ```rust |
| 1471 | /// fn is_even(n: &i32) -> bool { |
| 1472 | /// n % 2 == 0 |
| 1473 | /// } |
| 1474 | /// |
| 1475 | /// assert_eq!(None.filter(is_even), None); |
| 1476 | /// assert_eq!(Some(3).filter(is_even), None); |
| 1477 | /// assert_eq!(Some(4).filter(is_even), Some(4)); |
| 1478 | /// ``` |
| 1479 | /// |
| 1480 | /// [`Some(t)`]: Some |
| 1481 | #[inline ] |
| 1482 | #[stable (feature = "option_filter" , since = "1.27.0" )] |
| 1483 | pub fn filter<P>(self, predicate: P) -> Self |
| 1484 | where |
| 1485 | P: FnOnce(&T) -> bool, |
| 1486 | { |
| 1487 | if let Some(x) = self { |
| 1488 | if predicate(&x) { |
| 1489 | return Some(x); |
| 1490 | } |
| 1491 | } |
| 1492 | None |
| 1493 | } |
| 1494 | |
| 1495 | /// Returns the option if it contains a value, otherwise returns `optb`. |
| 1496 | /// |
| 1497 | /// Arguments passed to `or` are eagerly evaluated; if you are passing the |
| 1498 | /// result of a function call, it is recommended to use [`or_else`], which is |
| 1499 | /// lazily evaluated. |
| 1500 | /// |
| 1501 | /// [`or_else`]: Option::or_else |
| 1502 | /// |
| 1503 | /// # Examples |
| 1504 | /// |
| 1505 | /// ``` |
| 1506 | /// let x = Some(2); |
| 1507 | /// let y = None; |
| 1508 | /// assert_eq!(x.or(y), Some(2)); |
| 1509 | /// |
| 1510 | /// let x = None; |
| 1511 | /// let y = Some(100); |
| 1512 | /// assert_eq!(x.or(y), Some(100)); |
| 1513 | /// |
| 1514 | /// let x = Some(2); |
| 1515 | /// let y = Some(100); |
| 1516 | /// assert_eq!(x.or(y), Some(2)); |
| 1517 | /// |
| 1518 | /// let x: Option<u32> = None; |
| 1519 | /// let y = None; |
| 1520 | /// assert_eq!(x.or(y), None); |
| 1521 | /// ``` |
| 1522 | #[inline ] |
| 1523 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 1524 | pub fn or(self, optb: Option<T>) -> Option<T> { |
| 1525 | match self { |
| 1526 | x @ Some(_) => x, |
| 1527 | None => optb, |
| 1528 | } |
| 1529 | } |
| 1530 | |
| 1531 | /// Returns the option if it contains a value, otherwise calls `f` and |
| 1532 | /// returns the result. |
| 1533 | /// |
| 1534 | /// # Examples |
| 1535 | /// |
| 1536 | /// ``` |
| 1537 | /// fn nobody() -> Option<&'static str> { None } |
| 1538 | /// fn vikings() -> Option<&'static str> { Some("vikings" ) } |
| 1539 | /// |
| 1540 | /// assert_eq!(Some("barbarians" ).or_else(vikings), Some("barbarians" )); |
| 1541 | /// assert_eq!(None.or_else(vikings), Some("vikings" )); |
| 1542 | /// assert_eq!(None.or_else(nobody), None); |
| 1543 | /// ``` |
| 1544 | #[inline ] |
| 1545 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 1546 | pub fn or_else<F>(self, f: F) -> Option<T> |
| 1547 | where |
| 1548 | F: FnOnce() -> Option<T>, |
| 1549 | { |
| 1550 | match self { |
| 1551 | x @ Some(_) => x, |
| 1552 | None => f(), |
| 1553 | } |
| 1554 | } |
| 1555 | |
| 1556 | /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`]. |
| 1557 | /// |
| 1558 | /// # Examples |
| 1559 | /// |
| 1560 | /// ``` |
| 1561 | /// let x = Some(2); |
| 1562 | /// let y: Option<u32> = None; |
| 1563 | /// assert_eq!(x.xor(y), Some(2)); |
| 1564 | /// |
| 1565 | /// let x: Option<u32> = None; |
| 1566 | /// let y = Some(2); |
| 1567 | /// assert_eq!(x.xor(y), Some(2)); |
| 1568 | /// |
| 1569 | /// let x = Some(2); |
| 1570 | /// let y = Some(2); |
| 1571 | /// assert_eq!(x.xor(y), None); |
| 1572 | /// |
| 1573 | /// let x: Option<u32> = None; |
| 1574 | /// let y: Option<u32> = None; |
| 1575 | /// assert_eq!(x.xor(y), None); |
| 1576 | /// ``` |
| 1577 | #[inline ] |
| 1578 | #[stable (feature = "option_xor" , since = "1.37.0" )] |
| 1579 | pub fn xor(self, optb: Option<T>) -> Option<T> { |
| 1580 | match (self, optb) { |
| 1581 | (a @ Some(_), None) => a, |
| 1582 | (None, b @ Some(_)) => b, |
| 1583 | _ => None, |
| 1584 | } |
| 1585 | } |
| 1586 | |
| 1587 | ///////////////////////////////////////////////////////////////////////// |
| 1588 | // Entry-like operations to insert a value and return a reference |
| 1589 | ///////////////////////////////////////////////////////////////////////// |
| 1590 | |
| 1591 | /// Inserts `value` into the option, then returns a mutable reference to it. |
| 1592 | /// |
| 1593 | /// If the option already contains a value, the old value is dropped. |
| 1594 | /// |
| 1595 | /// See also [`Option::get_or_insert`], which doesn't update the value if |
| 1596 | /// the option already contains [`Some`]. |
| 1597 | /// |
| 1598 | /// # Example |
| 1599 | /// |
| 1600 | /// ``` |
| 1601 | /// let mut opt = None; |
| 1602 | /// let val = opt.insert(1); |
| 1603 | /// assert_eq!(*val, 1); |
| 1604 | /// assert_eq!(opt.unwrap(), 1); |
| 1605 | /// let val = opt.insert(2); |
| 1606 | /// assert_eq!(*val, 2); |
| 1607 | /// *val = 3; |
| 1608 | /// assert_eq!(opt.unwrap(), 3); |
| 1609 | /// ``` |
| 1610 | #[must_use = "if you intended to set a value, consider assignment instead" ] |
| 1611 | #[inline ] |
| 1612 | #[stable (feature = "option_insert" , since = "1.53.0" )] |
| 1613 | pub fn insert(&mut self, value: T) -> &mut T { |
| 1614 | *self = Some(value); |
| 1615 | |
| 1616 | // SAFETY: the code above just filled the option |
| 1617 | unsafe { self.as_mut().unwrap_unchecked() } |
| 1618 | } |
| 1619 | |
| 1620 | /// Inserts `value` into the option if it is [`None`], then |
| 1621 | /// returns a mutable reference to the contained value. |
| 1622 | /// |
| 1623 | /// See also [`Option::insert`], which updates the value even if |
| 1624 | /// the option already contains [`Some`]. |
| 1625 | /// |
| 1626 | /// # Examples |
| 1627 | /// |
| 1628 | /// ``` |
| 1629 | /// let mut x = None; |
| 1630 | /// |
| 1631 | /// { |
| 1632 | /// let y: &mut u32 = x.get_or_insert(5); |
| 1633 | /// assert_eq!(y, &5); |
| 1634 | /// |
| 1635 | /// *y = 7; |
| 1636 | /// } |
| 1637 | /// |
| 1638 | /// assert_eq!(x, Some(7)); |
| 1639 | /// ``` |
| 1640 | #[inline ] |
| 1641 | #[stable (feature = "option_entry" , since = "1.20.0" )] |
| 1642 | pub fn get_or_insert(&mut self, value: T) -> &mut T { |
| 1643 | self.get_or_insert_with(|| value) |
| 1644 | } |
| 1645 | |
| 1646 | /// Inserts the default value into the option if it is [`None`], then |
| 1647 | /// returns a mutable reference to the contained value. |
| 1648 | /// |
| 1649 | /// # Examples |
| 1650 | /// |
| 1651 | /// ``` |
| 1652 | /// let mut x = None; |
| 1653 | /// |
| 1654 | /// { |
| 1655 | /// let y: &mut u32 = x.get_or_insert_default(); |
| 1656 | /// assert_eq!(y, &0); |
| 1657 | /// |
| 1658 | /// *y = 7; |
| 1659 | /// } |
| 1660 | /// |
| 1661 | /// assert_eq!(x, Some(7)); |
| 1662 | /// ``` |
| 1663 | #[inline ] |
| 1664 | #[stable (feature = "option_get_or_insert_default" , since = "1.83.0" )] |
| 1665 | pub fn get_or_insert_default(&mut self) -> &mut T |
| 1666 | where |
| 1667 | T: Default, |
| 1668 | { |
| 1669 | self.get_or_insert_with(T::default) |
| 1670 | } |
| 1671 | |
| 1672 | /// Inserts a value computed from `f` into the option if it is [`None`], |
| 1673 | /// then returns a mutable reference to the contained value. |
| 1674 | /// |
| 1675 | /// # Examples |
| 1676 | /// |
| 1677 | /// ``` |
| 1678 | /// let mut x = None; |
| 1679 | /// |
| 1680 | /// { |
| 1681 | /// let y: &mut u32 = x.get_or_insert_with(|| 5); |
| 1682 | /// assert_eq!(y, &5); |
| 1683 | /// |
| 1684 | /// *y = 7; |
| 1685 | /// } |
| 1686 | /// |
| 1687 | /// assert_eq!(x, Some(7)); |
| 1688 | /// ``` |
| 1689 | #[inline ] |
| 1690 | #[stable (feature = "option_entry" , since = "1.20.0" )] |
| 1691 | pub fn get_or_insert_with<F>(&mut self, f: F) -> &mut T |
| 1692 | where |
| 1693 | F: FnOnce() -> T, |
| 1694 | { |
| 1695 | if let None = self { |
| 1696 | *self = Some(f()); |
| 1697 | } |
| 1698 | |
| 1699 | // SAFETY: a `None` variant for `self` would have been replaced by a `Some` |
| 1700 | // variant in the code above. |
| 1701 | unsafe { self.as_mut().unwrap_unchecked() } |
| 1702 | } |
| 1703 | |
| 1704 | ///////////////////////////////////////////////////////////////////////// |
| 1705 | // Misc |
| 1706 | ///////////////////////////////////////////////////////////////////////// |
| 1707 | |
| 1708 | /// Takes the value out of the option, leaving a [`None`] in its place. |
| 1709 | /// |
| 1710 | /// # Examples |
| 1711 | /// |
| 1712 | /// ``` |
| 1713 | /// let mut x = Some(2); |
| 1714 | /// let y = x.take(); |
| 1715 | /// assert_eq!(x, None); |
| 1716 | /// assert_eq!(y, Some(2)); |
| 1717 | /// |
| 1718 | /// let mut x: Option<u32> = None; |
| 1719 | /// let y = x.take(); |
| 1720 | /// assert_eq!(x, None); |
| 1721 | /// assert_eq!(y, None); |
| 1722 | /// ``` |
| 1723 | #[inline ] |
| 1724 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 1725 | #[rustc_const_stable (feature = "const_option" , since = "1.83.0" )] |
| 1726 | pub const fn take(&mut self) -> Option<T> { |
| 1727 | // FIXME(const-hack) replace `mem::replace` by `mem::take` when the latter is const ready |
| 1728 | mem::replace(self, None) |
| 1729 | } |
| 1730 | |
| 1731 | /// Takes the value out of the option, but only if the predicate evaluates to |
| 1732 | /// `true` on a mutable reference to the value. |
| 1733 | /// |
| 1734 | /// In other words, replaces `self` with `None` if the predicate returns `true`. |
| 1735 | /// This method operates similar to [`Option::take`] but conditional. |
| 1736 | /// |
| 1737 | /// # Examples |
| 1738 | /// |
| 1739 | /// ``` |
| 1740 | /// let mut x = Some(42); |
| 1741 | /// |
| 1742 | /// let prev = x.take_if(|v| if *v == 42 { |
| 1743 | /// *v += 1; |
| 1744 | /// false |
| 1745 | /// } else { |
| 1746 | /// false |
| 1747 | /// }); |
| 1748 | /// assert_eq!(x, Some(43)); |
| 1749 | /// assert_eq!(prev, None); |
| 1750 | /// |
| 1751 | /// let prev = x.take_if(|v| *v == 43); |
| 1752 | /// assert_eq!(x, None); |
| 1753 | /// assert_eq!(prev, Some(43)); |
| 1754 | /// ``` |
| 1755 | #[inline ] |
| 1756 | #[stable (feature = "option_take_if" , since = "1.80.0" )] |
| 1757 | pub fn take_if<P>(&mut self, predicate: P) -> Option<T> |
| 1758 | where |
| 1759 | P: FnOnce(&mut T) -> bool, |
| 1760 | { |
| 1761 | if self.as_mut().map_or(false, predicate) { self.take() } else { None } |
| 1762 | } |
| 1763 | |
| 1764 | /// Replaces the actual value in the option by the value given in parameter, |
| 1765 | /// returning the old value if present, |
| 1766 | /// leaving a [`Some`] in its place without deinitializing either one. |
| 1767 | /// |
| 1768 | /// # Examples |
| 1769 | /// |
| 1770 | /// ``` |
| 1771 | /// let mut x = Some(2); |
| 1772 | /// let old = x.replace(5); |
| 1773 | /// assert_eq!(x, Some(5)); |
| 1774 | /// assert_eq!(old, Some(2)); |
| 1775 | /// |
| 1776 | /// let mut x = None; |
| 1777 | /// let old = x.replace(3); |
| 1778 | /// assert_eq!(x, Some(3)); |
| 1779 | /// assert_eq!(old, None); |
| 1780 | /// ``` |
| 1781 | #[inline ] |
| 1782 | #[stable (feature = "option_replace" , since = "1.31.0" )] |
| 1783 | #[rustc_const_stable (feature = "const_option" , since = "1.83.0" )] |
| 1784 | pub const fn replace(&mut self, value: T) -> Option<T> { |
| 1785 | mem::replace(self, Some(value)) |
| 1786 | } |
| 1787 | |
| 1788 | /// Zips `self` with another `Option`. |
| 1789 | /// |
| 1790 | /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some((s, o))`. |
| 1791 | /// Otherwise, `None` is returned. |
| 1792 | /// |
| 1793 | /// # Examples |
| 1794 | /// |
| 1795 | /// ``` |
| 1796 | /// let x = Some(1); |
| 1797 | /// let y = Some("hi" ); |
| 1798 | /// let z = None::<u8>; |
| 1799 | /// |
| 1800 | /// assert_eq!(x.zip(y), Some((1, "hi" ))); |
| 1801 | /// assert_eq!(x.zip(z), None); |
| 1802 | /// ``` |
| 1803 | #[stable (feature = "option_zip_option" , since = "1.46.0" )] |
| 1804 | pub fn zip<U>(self, other: Option<U>) -> Option<(T, U)> { |
| 1805 | match (self, other) { |
| 1806 | (Some(a), Some(b)) => Some((a, b)), |
| 1807 | _ => None, |
| 1808 | } |
| 1809 | } |
| 1810 | |
| 1811 | /// Zips `self` and another `Option` with function `f`. |
| 1812 | /// |
| 1813 | /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`. |
| 1814 | /// Otherwise, `None` is returned. |
| 1815 | /// |
| 1816 | /// # Examples |
| 1817 | /// |
| 1818 | /// ``` |
| 1819 | /// #![feature(option_zip)] |
| 1820 | /// |
| 1821 | /// #[derive(Debug, PartialEq)] |
| 1822 | /// struct Point { |
| 1823 | /// x: f64, |
| 1824 | /// y: f64, |
| 1825 | /// } |
| 1826 | /// |
| 1827 | /// impl Point { |
| 1828 | /// fn new(x: f64, y: f64) -> Self { |
| 1829 | /// Self { x, y } |
| 1830 | /// } |
| 1831 | /// } |
| 1832 | /// |
| 1833 | /// let x = Some(17.5); |
| 1834 | /// let y = Some(42.7); |
| 1835 | /// |
| 1836 | /// assert_eq!(x.zip_with(y, Point::new), Some(Point { x: 17.5, y: 42.7 })); |
| 1837 | /// assert_eq!(x.zip_with(None, Point::new), None); |
| 1838 | /// ``` |
| 1839 | #[unstable (feature = "option_zip" , issue = "70086" )] |
| 1840 | pub fn zip_with<U, F, R>(self, other: Option<U>, f: F) -> Option<R> |
| 1841 | where |
| 1842 | F: FnOnce(T, U) -> R, |
| 1843 | { |
| 1844 | match (self, other) { |
| 1845 | (Some(a), Some(b)) => Some(f(a, b)), |
| 1846 | _ => None, |
| 1847 | } |
| 1848 | } |
| 1849 | } |
| 1850 | |
| 1851 | impl<T, U> Option<(T, U)> { |
| 1852 | /// Unzips an option containing a tuple of two options. |
| 1853 | /// |
| 1854 | /// If `self` is `Some((a, b))` this method returns `(Some(a), Some(b))`. |
| 1855 | /// Otherwise, `(None, None)` is returned. |
| 1856 | /// |
| 1857 | /// # Examples |
| 1858 | /// |
| 1859 | /// ``` |
| 1860 | /// let x = Some((1, "hi" )); |
| 1861 | /// let y = None::<(u8, u32)>; |
| 1862 | /// |
| 1863 | /// assert_eq!(x.unzip(), (Some(1), Some("hi" ))); |
| 1864 | /// assert_eq!(y.unzip(), (None, None)); |
| 1865 | /// ``` |
| 1866 | #[inline ] |
| 1867 | #[stable (feature = "unzip_option" , since = "1.66.0" )] |
| 1868 | pub fn unzip(self) -> (Option<T>, Option<U>) { |
| 1869 | match self { |
| 1870 | Some((a: T, b: U)) => (Some(a), Some(b)), |
| 1871 | None => (None, None), |
| 1872 | } |
| 1873 | } |
| 1874 | } |
| 1875 | |
| 1876 | impl<T> Option<&T> { |
| 1877 | /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the |
| 1878 | /// option. |
| 1879 | /// |
| 1880 | /// # Examples |
| 1881 | /// |
| 1882 | /// ``` |
| 1883 | /// let x = 12; |
| 1884 | /// let opt_x = Some(&x); |
| 1885 | /// assert_eq!(opt_x, Some(&12)); |
| 1886 | /// let copied = opt_x.copied(); |
| 1887 | /// assert_eq!(copied, Some(12)); |
| 1888 | /// ``` |
| 1889 | #[must_use = "`self` will be dropped if the result is not used" ] |
| 1890 | #[stable (feature = "copied" , since = "1.35.0" )] |
| 1891 | #[rustc_const_stable (feature = "const_option" , since = "1.83.0" )] |
| 1892 | pub const fn copied(self) -> Option<T> |
| 1893 | where |
| 1894 | T: Copy, |
| 1895 | { |
| 1896 | // FIXME(const-hack): this implementation, which sidesteps using `Option::map` since it's not const |
| 1897 | // ready yet, should be reverted when possible to avoid code repetition |
| 1898 | match self { |
| 1899 | Some(&v) => Some(v), |
| 1900 | None => None, |
| 1901 | } |
| 1902 | } |
| 1903 | |
| 1904 | /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the |
| 1905 | /// option. |
| 1906 | /// |
| 1907 | /// # Examples |
| 1908 | /// |
| 1909 | /// ``` |
| 1910 | /// let x = 12; |
| 1911 | /// let opt_x = Some(&x); |
| 1912 | /// assert_eq!(opt_x, Some(&12)); |
| 1913 | /// let cloned = opt_x.cloned(); |
| 1914 | /// assert_eq!(cloned, Some(12)); |
| 1915 | /// ``` |
| 1916 | #[must_use = "`self` will be dropped if the result is not used" ] |
| 1917 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 1918 | pub fn cloned(self) -> Option<T> |
| 1919 | where |
| 1920 | T: Clone, |
| 1921 | { |
| 1922 | match self { |
| 1923 | Some(t) => Some(t.clone()), |
| 1924 | None => None, |
| 1925 | } |
| 1926 | } |
| 1927 | } |
| 1928 | |
| 1929 | impl<T> Option<&mut T> { |
| 1930 | /// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the |
| 1931 | /// option. |
| 1932 | /// |
| 1933 | /// # Examples |
| 1934 | /// |
| 1935 | /// ``` |
| 1936 | /// let mut x = 12; |
| 1937 | /// let opt_x = Some(&mut x); |
| 1938 | /// assert_eq!(opt_x, Some(&mut 12)); |
| 1939 | /// let copied = opt_x.copied(); |
| 1940 | /// assert_eq!(copied, Some(12)); |
| 1941 | /// ``` |
| 1942 | #[must_use = "`self` will be dropped if the result is not used" ] |
| 1943 | #[stable (feature = "copied" , since = "1.35.0" )] |
| 1944 | #[rustc_const_stable (feature = "const_option" , since = "1.83.0" )] |
| 1945 | pub const fn copied(self) -> Option<T> |
| 1946 | where |
| 1947 | T: Copy, |
| 1948 | { |
| 1949 | match self { |
| 1950 | Some(&mut t) => Some(t), |
| 1951 | None => None, |
| 1952 | } |
| 1953 | } |
| 1954 | |
| 1955 | /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the |
| 1956 | /// option. |
| 1957 | /// |
| 1958 | /// # Examples |
| 1959 | /// |
| 1960 | /// ``` |
| 1961 | /// let mut x = 12; |
| 1962 | /// let opt_x = Some(&mut x); |
| 1963 | /// assert_eq!(opt_x, Some(&mut 12)); |
| 1964 | /// let cloned = opt_x.cloned(); |
| 1965 | /// assert_eq!(cloned, Some(12)); |
| 1966 | /// ``` |
| 1967 | #[must_use = "`self` will be dropped if the result is not used" ] |
| 1968 | #[stable (since = "1.26.0" , feature = "option_ref_mut_cloned" )] |
| 1969 | pub fn cloned(self) -> Option<T> |
| 1970 | where |
| 1971 | T: Clone, |
| 1972 | { |
| 1973 | match self { |
| 1974 | Some(t) => Some(t.clone()), |
| 1975 | None => None, |
| 1976 | } |
| 1977 | } |
| 1978 | } |
| 1979 | |
| 1980 | impl<T, E> Option<Result<T, E>> { |
| 1981 | /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`. |
| 1982 | /// |
| 1983 | /// [`None`] will be mapped to <code>[Ok]\([None])</code>. |
| 1984 | /// <code>[Some]\([Ok]\(\_))</code> and <code>[Some]\([Err]\(\_))</code> will be mapped to |
| 1985 | /// <code>[Ok]\([Some]\(\_))</code> and <code>[Err]\(\_)</code>. |
| 1986 | /// |
| 1987 | /// # Examples |
| 1988 | /// |
| 1989 | /// ``` |
| 1990 | /// #[derive(Debug, Eq, PartialEq)] |
| 1991 | /// struct SomeErr; |
| 1992 | /// |
| 1993 | /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5)); |
| 1994 | /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5)); |
| 1995 | /// assert_eq!(x, y.transpose()); |
| 1996 | /// ``` |
| 1997 | #[inline ] |
| 1998 | #[stable (feature = "transpose_result" , since = "1.33.0" )] |
| 1999 | #[rustc_allow_const_fn_unstable (const_precise_live_drops)] |
| 2000 | #[rustc_const_stable (feature = "const_option" , since = "1.83.0" )] |
| 2001 | pub const fn transpose(self) -> Result<Option<T>, E> { |
| 2002 | match self { |
| 2003 | Some(Ok(x)) => Ok(Some(x)), |
| 2004 | Some(Err(e)) => Err(e), |
| 2005 | None => Ok(None), |
| 2006 | } |
| 2007 | } |
| 2008 | } |
| 2009 | |
| 2010 | #[cfg_attr (not(feature = "panic_immediate_abort" ), inline(never))] |
| 2011 | #[cfg_attr (feature = "panic_immediate_abort" , inline)] |
| 2012 | #[cold ] |
| 2013 | #[track_caller ] |
| 2014 | const fn unwrap_failed() -> ! { |
| 2015 | panic(expr:"called `Option::unwrap()` on a `None` value" ) |
| 2016 | } |
| 2017 | |
| 2018 | // This is a separate function to reduce the code size of .expect() itself. |
| 2019 | #[cfg_attr (not(feature = "panic_immediate_abort" ), inline(never))] |
| 2020 | #[cfg_attr (feature = "panic_immediate_abort" , inline)] |
| 2021 | #[cold ] |
| 2022 | #[track_caller ] |
| 2023 | const fn expect_failed(msg: &str) -> ! { |
| 2024 | panic_display(&msg) |
| 2025 | } |
| 2026 | |
| 2027 | ///////////////////////////////////////////////////////////////////////////// |
| 2028 | // Trait implementations |
| 2029 | ///////////////////////////////////////////////////////////////////////////// |
| 2030 | |
| 2031 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 2032 | impl<T> Clone for Option<T> |
| 2033 | where |
| 2034 | T: Clone, |
| 2035 | { |
| 2036 | #[inline ] |
| 2037 | fn clone(&self) -> Self { |
| 2038 | match self { |
| 2039 | Some(x: &T) => Some(x.clone()), |
| 2040 | None => None, |
| 2041 | } |
| 2042 | } |
| 2043 | |
| 2044 | #[inline ] |
| 2045 | fn clone_from(&mut self, source: &Self) { |
| 2046 | match (self, source) { |
| 2047 | (Some(to: &mut T), Some(from: &T)) => to.clone_from(source:from), |
| 2048 | (to: &mut Option, from: &Option) => *to = from.clone(), |
| 2049 | } |
| 2050 | } |
| 2051 | } |
| 2052 | |
| 2053 | #[unstable (feature = "ergonomic_clones" , issue = "132290" )] |
| 2054 | impl<T> crate::clone::UseCloned for Option<T> where T: crate::clone::UseCloned {} |
| 2055 | |
| 2056 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 2057 | impl<T> Default for Option<T> { |
| 2058 | /// Returns [`None`][Option::None]. |
| 2059 | /// |
| 2060 | /// # Examples |
| 2061 | /// |
| 2062 | /// ``` |
| 2063 | /// let opt: Option<u32> = Option::default(); |
| 2064 | /// assert!(opt.is_none()); |
| 2065 | /// ``` |
| 2066 | #[inline ] |
| 2067 | fn default() -> Option<T> { |
| 2068 | None |
| 2069 | } |
| 2070 | } |
| 2071 | |
| 2072 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 2073 | impl<T> IntoIterator for Option<T> { |
| 2074 | type Item = T; |
| 2075 | type IntoIter = IntoIter<T>; |
| 2076 | |
| 2077 | /// Returns a consuming iterator over the possibly contained value. |
| 2078 | /// |
| 2079 | /// # Examples |
| 2080 | /// |
| 2081 | /// ``` |
| 2082 | /// let x = Some("string" ); |
| 2083 | /// let v: Vec<&str> = x.into_iter().collect(); |
| 2084 | /// assert_eq!(v, ["string" ]); |
| 2085 | /// |
| 2086 | /// let x = None; |
| 2087 | /// let v: Vec<&str> = x.into_iter().collect(); |
| 2088 | /// assert!(v.is_empty()); |
| 2089 | /// ``` |
| 2090 | #[inline ] |
| 2091 | fn into_iter(self) -> IntoIter<T> { |
| 2092 | IntoIter { inner: Item { opt: self } } |
| 2093 | } |
| 2094 | } |
| 2095 | |
| 2096 | #[stable (since = "1.4.0" , feature = "option_iter" )] |
| 2097 | impl<'a, T> IntoIterator for &'a Option<T> { |
| 2098 | type Item = &'a T; |
| 2099 | type IntoIter = Iter<'a, T>; |
| 2100 | |
| 2101 | fn into_iter(self) -> Iter<'a, T> { |
| 2102 | self.iter() |
| 2103 | } |
| 2104 | } |
| 2105 | |
| 2106 | #[stable (since = "1.4.0" , feature = "option_iter" )] |
| 2107 | impl<'a, T> IntoIterator for &'a mut Option<T> { |
| 2108 | type Item = &'a mut T; |
| 2109 | type IntoIter = IterMut<'a, T>; |
| 2110 | |
| 2111 | fn into_iter(self) -> IterMut<'a, T> { |
| 2112 | self.iter_mut() |
| 2113 | } |
| 2114 | } |
| 2115 | |
| 2116 | #[stable (since = "1.12.0" , feature = "option_from" )] |
| 2117 | impl<T> From<T> for Option<T> { |
| 2118 | /// Moves `val` into a new [`Some`]. |
| 2119 | /// |
| 2120 | /// # Examples |
| 2121 | /// |
| 2122 | /// ``` |
| 2123 | /// let o: Option<u8> = Option::from(67); |
| 2124 | /// |
| 2125 | /// assert_eq!(Some(67), o); |
| 2126 | /// ``` |
| 2127 | fn from(val: T) -> Option<T> { |
| 2128 | Some(val) |
| 2129 | } |
| 2130 | } |
| 2131 | |
| 2132 | #[stable (feature = "option_ref_from_ref_option" , since = "1.30.0" )] |
| 2133 | impl<'a, T> From<&'a Option<T>> for Option<&'a T> { |
| 2134 | /// Converts from `&Option<T>` to `Option<&T>`. |
| 2135 | /// |
| 2136 | /// # Examples |
| 2137 | /// |
| 2138 | /// Converts an <code>[Option]<[String]></code> into an <code>[Option]<[usize]></code>, preserving |
| 2139 | /// the original. The [`map`] method takes the `self` argument by value, consuming the original, |
| 2140 | /// so this technique uses `from` to first take an [`Option`] to a reference |
| 2141 | /// to the value inside the original. |
| 2142 | /// |
| 2143 | /// [`map`]: Option::map |
| 2144 | /// [String]: ../../std/string/struct.String.html "String" |
| 2145 | /// |
| 2146 | /// ``` |
| 2147 | /// let s: Option<String> = Some(String::from("Hello, Rustaceans!" )); |
| 2148 | /// let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len()); |
| 2149 | /// |
| 2150 | /// println!("Can still print s: {s:?}" ); |
| 2151 | /// |
| 2152 | /// assert_eq!(o, Some(18)); |
| 2153 | /// ``` |
| 2154 | fn from(o: &'a Option<T>) -> Option<&'a T> { |
| 2155 | o.as_ref() |
| 2156 | } |
| 2157 | } |
| 2158 | |
| 2159 | #[stable (feature = "option_ref_from_ref_option" , since = "1.30.0" )] |
| 2160 | impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> { |
| 2161 | /// Converts from `&mut Option<T>` to `Option<&mut T>` |
| 2162 | /// |
| 2163 | /// # Examples |
| 2164 | /// |
| 2165 | /// ``` |
| 2166 | /// let mut s = Some(String::from("Hello" )); |
| 2167 | /// let o: Option<&mut String> = Option::from(&mut s); |
| 2168 | /// |
| 2169 | /// match o { |
| 2170 | /// Some(t) => *t = String::from("Hello, Rustaceans!" ), |
| 2171 | /// None => (), |
| 2172 | /// } |
| 2173 | /// |
| 2174 | /// assert_eq!(s, Some(String::from("Hello, Rustaceans!" ))); |
| 2175 | /// ``` |
| 2176 | fn from(o: &'a mut Option<T>) -> Option<&'a mut T> { |
| 2177 | o.as_mut() |
| 2178 | } |
| 2179 | } |
| 2180 | |
| 2181 | // Ideally, LLVM should be able to optimize our derive code to this. |
| 2182 | // Once https://github.com/llvm/llvm-project/issues/52622 is fixed, we can |
| 2183 | // go back to deriving `PartialEq`. |
| 2184 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 2185 | impl<T> crate::marker::StructuralPartialEq for Option<T> {} |
| 2186 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 2187 | impl<T: PartialEq> PartialEq for Option<T> { |
| 2188 | #[inline ] |
| 2189 | fn eq(&self, other: &Self) -> bool { |
| 2190 | // Spelling out the cases explicitly optimizes better than |
| 2191 | // `_ => false` |
| 2192 | match (self, other) { |
| 2193 | (Some(l: &T), Some(r: &T)) => *l == *r, |
| 2194 | (Some(_), None) => false, |
| 2195 | (None, Some(_)) => false, |
| 2196 | (None, None) => true, |
| 2197 | } |
| 2198 | } |
| 2199 | } |
| 2200 | |
| 2201 | // Manually implementing here somewhat improves codegen for |
| 2202 | // https://github.com/rust-lang/rust/issues/49892, although still |
| 2203 | // not optimal. |
| 2204 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 2205 | impl<T: PartialOrd> PartialOrd for Option<T> { |
| 2206 | #[inline ] |
| 2207 | fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { |
| 2208 | match (self, other) { |
| 2209 | (Some(l: &T), Some(r: &T)) => l.partial_cmp(r), |
| 2210 | (Some(_), None) => Some(cmp::Ordering::Greater), |
| 2211 | (None, Some(_)) => Some(cmp::Ordering::Less), |
| 2212 | (None, None) => Some(cmp::Ordering::Equal), |
| 2213 | } |
| 2214 | } |
| 2215 | } |
| 2216 | |
| 2217 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 2218 | impl<T: Ord> Ord for Option<T> { |
| 2219 | #[inline ] |
| 2220 | fn cmp(&self, other: &Self) -> cmp::Ordering { |
| 2221 | match (self, other) { |
| 2222 | (Some(l: &T), Some(r: &T)) => l.cmp(r), |
| 2223 | (Some(_), None) => cmp::Ordering::Greater, |
| 2224 | (None, Some(_)) => cmp::Ordering::Less, |
| 2225 | (None, None) => cmp::Ordering::Equal, |
| 2226 | } |
| 2227 | } |
| 2228 | } |
| 2229 | |
| 2230 | ///////////////////////////////////////////////////////////////////////////// |
| 2231 | // The Option Iterators |
| 2232 | ///////////////////////////////////////////////////////////////////////////// |
| 2233 | |
| 2234 | #[derive (Clone, Debug)] |
| 2235 | struct Item<A> { |
| 2236 | opt: Option<A>, |
| 2237 | } |
| 2238 | |
| 2239 | impl<A> Iterator for Item<A> { |
| 2240 | type Item = A; |
| 2241 | |
| 2242 | #[inline ] |
| 2243 | fn next(&mut self) -> Option<A> { |
| 2244 | self.opt.take() |
| 2245 | } |
| 2246 | |
| 2247 | #[inline ] |
| 2248 | fn size_hint(&self) -> (usize, Option<usize>) { |
| 2249 | let len: usize = self.len(); |
| 2250 | (len, Some(len)) |
| 2251 | } |
| 2252 | } |
| 2253 | |
| 2254 | impl<A> DoubleEndedIterator for Item<A> { |
| 2255 | #[inline ] |
| 2256 | fn next_back(&mut self) -> Option<A> { |
| 2257 | self.opt.take() |
| 2258 | } |
| 2259 | } |
| 2260 | |
| 2261 | impl<A> ExactSizeIterator for Item<A> { |
| 2262 | #[inline ] |
| 2263 | fn len(&self) -> usize { |
| 2264 | self.opt.len() |
| 2265 | } |
| 2266 | } |
| 2267 | impl<A> FusedIterator for Item<A> {} |
| 2268 | unsafe impl<A> TrustedLen for Item<A> {} |
| 2269 | |
| 2270 | /// An iterator over a reference to the [`Some`] variant of an [`Option`]. |
| 2271 | /// |
| 2272 | /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none. |
| 2273 | /// |
| 2274 | /// This `struct` is created by the [`Option::iter`] function. |
| 2275 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 2276 | #[derive (Debug)] |
| 2277 | pub struct Iter<'a, A: 'a> { |
| 2278 | inner: Item<&'a A>, |
| 2279 | } |
| 2280 | |
| 2281 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 2282 | impl<'a, A> Iterator for Iter<'a, A> { |
| 2283 | type Item = &'a A; |
| 2284 | |
| 2285 | #[inline ] |
| 2286 | fn next(&mut self) -> Option<&'a A> { |
| 2287 | self.inner.next() |
| 2288 | } |
| 2289 | #[inline ] |
| 2290 | fn size_hint(&self) -> (usize, Option<usize>) { |
| 2291 | self.inner.size_hint() |
| 2292 | } |
| 2293 | } |
| 2294 | |
| 2295 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 2296 | impl<'a, A> DoubleEndedIterator for Iter<'a, A> { |
| 2297 | #[inline ] |
| 2298 | fn next_back(&mut self) -> Option<&'a A> { |
| 2299 | self.inner.next_back() |
| 2300 | } |
| 2301 | } |
| 2302 | |
| 2303 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 2304 | impl<A> ExactSizeIterator for Iter<'_, A> {} |
| 2305 | |
| 2306 | #[stable (feature = "fused" , since = "1.26.0" )] |
| 2307 | impl<A> FusedIterator for Iter<'_, A> {} |
| 2308 | |
| 2309 | #[unstable (feature = "trusted_len" , issue = "37572" )] |
| 2310 | unsafe impl<A> TrustedLen for Iter<'_, A> {} |
| 2311 | |
| 2312 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 2313 | impl<A> Clone for Iter<'_, A> { |
| 2314 | #[inline ] |
| 2315 | fn clone(&self) -> Self { |
| 2316 | Iter { inner: self.inner.clone() } |
| 2317 | } |
| 2318 | } |
| 2319 | |
| 2320 | /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`]. |
| 2321 | /// |
| 2322 | /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none. |
| 2323 | /// |
| 2324 | /// This `struct` is created by the [`Option::iter_mut`] function. |
| 2325 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 2326 | #[derive (Debug)] |
| 2327 | pub struct IterMut<'a, A: 'a> { |
| 2328 | inner: Item<&'a mut A>, |
| 2329 | } |
| 2330 | |
| 2331 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 2332 | impl<'a, A> Iterator for IterMut<'a, A> { |
| 2333 | type Item = &'a mut A; |
| 2334 | |
| 2335 | #[inline ] |
| 2336 | fn next(&mut self) -> Option<&'a mut A> { |
| 2337 | self.inner.next() |
| 2338 | } |
| 2339 | #[inline ] |
| 2340 | fn size_hint(&self) -> (usize, Option<usize>) { |
| 2341 | self.inner.size_hint() |
| 2342 | } |
| 2343 | } |
| 2344 | |
| 2345 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 2346 | impl<'a, A> DoubleEndedIterator for IterMut<'a, A> { |
| 2347 | #[inline ] |
| 2348 | fn next_back(&mut self) -> Option<&'a mut A> { |
| 2349 | self.inner.next_back() |
| 2350 | } |
| 2351 | } |
| 2352 | |
| 2353 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 2354 | impl<A> ExactSizeIterator for IterMut<'_, A> {} |
| 2355 | |
| 2356 | #[stable (feature = "fused" , since = "1.26.0" )] |
| 2357 | impl<A> FusedIterator for IterMut<'_, A> {} |
| 2358 | #[unstable (feature = "trusted_len" , issue = "37572" )] |
| 2359 | unsafe impl<A> TrustedLen for IterMut<'_, A> {} |
| 2360 | |
| 2361 | /// An iterator over the value in [`Some`] variant of an [`Option`]. |
| 2362 | /// |
| 2363 | /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none. |
| 2364 | /// |
| 2365 | /// This `struct` is created by the [`Option::into_iter`] function. |
| 2366 | #[derive (Clone, Debug)] |
| 2367 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 2368 | pub struct IntoIter<A> { |
| 2369 | inner: Item<A>, |
| 2370 | } |
| 2371 | |
| 2372 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 2373 | impl<A> Iterator for IntoIter<A> { |
| 2374 | type Item = A; |
| 2375 | |
| 2376 | #[inline ] |
| 2377 | fn next(&mut self) -> Option<A> { |
| 2378 | self.inner.next() |
| 2379 | } |
| 2380 | #[inline ] |
| 2381 | fn size_hint(&self) -> (usize, Option<usize>) { |
| 2382 | self.inner.size_hint() |
| 2383 | } |
| 2384 | } |
| 2385 | |
| 2386 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 2387 | impl<A> DoubleEndedIterator for IntoIter<A> { |
| 2388 | #[inline ] |
| 2389 | fn next_back(&mut self) -> Option<A> { |
| 2390 | self.inner.next_back() |
| 2391 | } |
| 2392 | } |
| 2393 | |
| 2394 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 2395 | impl<A> ExactSizeIterator for IntoIter<A> {} |
| 2396 | |
| 2397 | #[stable (feature = "fused" , since = "1.26.0" )] |
| 2398 | impl<A> FusedIterator for IntoIter<A> {} |
| 2399 | |
| 2400 | #[unstable (feature = "trusted_len" , issue = "37572" )] |
| 2401 | unsafe impl<A> TrustedLen for IntoIter<A> {} |
| 2402 | |
| 2403 | ///////////////////////////////////////////////////////////////////////////// |
| 2404 | // FromIterator |
| 2405 | ///////////////////////////////////////////////////////////////////////////// |
| 2406 | |
| 2407 | #[stable (feature = "rust1" , since = "1.0.0" )] |
| 2408 | impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> { |
| 2409 | /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None], |
| 2410 | /// no further elements are taken, and the [`None`][Option::None] is |
| 2411 | /// returned. Should no [`None`][Option::None] occur, a container of type |
| 2412 | /// `V` containing the values of each [`Option`] is returned. |
| 2413 | /// |
| 2414 | /// # Examples |
| 2415 | /// |
| 2416 | /// Here is an example which increments every integer in a vector. |
| 2417 | /// We use the checked variant of `add` that returns `None` when the |
| 2418 | /// calculation would result in an overflow. |
| 2419 | /// |
| 2420 | /// ``` |
| 2421 | /// let items = vec![0_u16, 1, 2]; |
| 2422 | /// |
| 2423 | /// let res: Option<Vec<u16>> = items |
| 2424 | /// .iter() |
| 2425 | /// .map(|x| x.checked_add(1)) |
| 2426 | /// .collect(); |
| 2427 | /// |
| 2428 | /// assert_eq!(res, Some(vec![1, 2, 3])); |
| 2429 | /// ``` |
| 2430 | /// |
| 2431 | /// As you can see, this will return the expected, valid items. |
| 2432 | /// |
| 2433 | /// Here is another example that tries to subtract one from another list |
| 2434 | /// of integers, this time checking for underflow: |
| 2435 | /// |
| 2436 | /// ``` |
| 2437 | /// let items = vec![2_u16, 1, 0]; |
| 2438 | /// |
| 2439 | /// let res: Option<Vec<u16>> = items |
| 2440 | /// .iter() |
| 2441 | /// .map(|x| x.checked_sub(1)) |
| 2442 | /// .collect(); |
| 2443 | /// |
| 2444 | /// assert_eq!(res, None); |
| 2445 | /// ``` |
| 2446 | /// |
| 2447 | /// Since the last element is zero, it would underflow. Thus, the resulting |
| 2448 | /// value is `None`. |
| 2449 | /// |
| 2450 | /// Here is a variation on the previous example, showing that no |
| 2451 | /// further elements are taken from `iter` after the first `None`. |
| 2452 | /// |
| 2453 | /// ``` |
| 2454 | /// let items = vec![3_u16, 2, 1, 10]; |
| 2455 | /// |
| 2456 | /// let mut shared = 0; |
| 2457 | /// |
| 2458 | /// let res: Option<Vec<u16>> = items |
| 2459 | /// .iter() |
| 2460 | /// .map(|x| { shared += x; x.checked_sub(2) }) |
| 2461 | /// .collect(); |
| 2462 | /// |
| 2463 | /// assert_eq!(res, None); |
| 2464 | /// assert_eq!(shared, 6); |
| 2465 | /// ``` |
| 2466 | /// |
| 2467 | /// Since the third element caused an underflow, no further elements were taken, |
| 2468 | /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16. |
| 2469 | #[inline ] |
| 2470 | fn from_iter<I: IntoIterator<Item = Option<A>>>(iter: I) -> Option<V> { |
| 2471 | // FIXME(#11084): This could be replaced with Iterator::scan when this |
| 2472 | // performance bug is closed. |
| 2473 | |
| 2474 | iter::try_process(iter.into_iter(), |i| i.collect()) |
| 2475 | } |
| 2476 | } |
| 2477 | |
| 2478 | #[unstable (feature = "try_trait_v2" , issue = "84277" )] |
| 2479 | impl<T> ops::Try for Option<T> { |
| 2480 | type Output = T; |
| 2481 | type Residual = Option<convert::Infallible>; |
| 2482 | |
| 2483 | #[inline ] |
| 2484 | fn from_output(output: Self::Output) -> Self { |
| 2485 | Some(output) |
| 2486 | } |
| 2487 | |
| 2488 | #[inline ] |
| 2489 | fn branch(self) -> ControlFlow<Self::Residual, Self::Output> { |
| 2490 | match self { |
| 2491 | Some(v: T) => ControlFlow::Continue(v), |
| 2492 | None => ControlFlow::Break(None), |
| 2493 | } |
| 2494 | } |
| 2495 | } |
| 2496 | |
| 2497 | #[unstable (feature = "try_trait_v2" , issue = "84277" )] |
| 2498 | // Note: manually specifying the residual type instead of using the default to work around |
| 2499 | // https://github.com/rust-lang/rust/issues/99940 |
| 2500 | impl<T> ops::FromResidual<Option<convert::Infallible>> for Option<T> { |
| 2501 | #[inline ] |
| 2502 | fn from_residual(residual: Option<convert::Infallible>) -> Self { |
| 2503 | match residual { |
| 2504 | None => None, |
| 2505 | } |
| 2506 | } |
| 2507 | } |
| 2508 | |
| 2509 | #[diagnostic::do_not_recommend] |
| 2510 | #[unstable (feature = "try_trait_v2_yeet" , issue = "96374" )] |
| 2511 | impl<T> ops::FromResidual<ops::Yeet<()>> for Option<T> { |
| 2512 | #[inline ] |
| 2513 | fn from_residual(ops::Yeet(()): ops::Yeet<()>) -> Self { |
| 2514 | None |
| 2515 | } |
| 2516 | } |
| 2517 | |
| 2518 | #[unstable (feature = "try_trait_v2_residual" , issue = "91285" )] |
| 2519 | impl<T> ops::Residual<T> for Option<convert::Infallible> { |
| 2520 | type TryType = Option<T>; |
| 2521 | } |
| 2522 | |
| 2523 | impl<T> Option<Option<T>> { |
| 2524 | /// Converts from `Option<Option<T>>` to `Option<T>`. |
| 2525 | /// |
| 2526 | /// # Examples |
| 2527 | /// |
| 2528 | /// Basic usage: |
| 2529 | /// |
| 2530 | /// ``` |
| 2531 | /// let x: Option<Option<u32>> = Some(Some(6)); |
| 2532 | /// assert_eq!(Some(6), x.flatten()); |
| 2533 | /// |
| 2534 | /// let x: Option<Option<u32>> = Some(None); |
| 2535 | /// assert_eq!(None, x.flatten()); |
| 2536 | /// |
| 2537 | /// let x: Option<Option<u32>> = None; |
| 2538 | /// assert_eq!(None, x.flatten()); |
| 2539 | /// ``` |
| 2540 | /// |
| 2541 | /// Flattening only removes one level of nesting at a time: |
| 2542 | /// |
| 2543 | /// ``` |
| 2544 | /// let x: Option<Option<Option<u32>>> = Some(Some(Some(6))); |
| 2545 | /// assert_eq!(Some(Some(6)), x.flatten()); |
| 2546 | /// assert_eq!(Some(6), x.flatten().flatten()); |
| 2547 | /// ``` |
| 2548 | #[inline ] |
| 2549 | #[stable (feature = "option_flattening" , since = "1.40.0" )] |
| 2550 | #[rustc_allow_const_fn_unstable (const_precise_live_drops)] |
| 2551 | #[rustc_const_stable (feature = "const_option" , since = "1.83.0" )] |
| 2552 | pub const fn flatten(self) -> Option<T> { |
| 2553 | // FIXME(const-hack): could be written with `and_then` |
| 2554 | match self { |
| 2555 | Some(inner) => inner, |
| 2556 | None => None, |
| 2557 | } |
| 2558 | } |
| 2559 | } |
| 2560 | |
| 2561 | impl<T, const N: usize> [Option<T>; N] { |
| 2562 | /// Transposes a `[Option<T>; N]` into a `Option<[T; N]>`. |
| 2563 | /// |
| 2564 | /// # Examples |
| 2565 | /// |
| 2566 | /// ``` |
| 2567 | /// #![feature(option_array_transpose)] |
| 2568 | /// # use std::option::Option; |
| 2569 | /// |
| 2570 | /// let data = [Some(0); 1000]; |
| 2571 | /// let data: Option<[u8; 1000]> = data.transpose(); |
| 2572 | /// assert_eq!(data, Some([0; 1000])); |
| 2573 | /// |
| 2574 | /// let data = [Some(0), None]; |
| 2575 | /// let data: Option<[u8; 2]> = data.transpose(); |
| 2576 | /// assert_eq!(data, None); |
| 2577 | /// ``` |
| 2578 | #[inline ] |
| 2579 | #[unstable (feature = "option_array_transpose" , issue = "130828" )] |
| 2580 | pub fn transpose(self) -> Option<[T; N]> { |
| 2581 | self.try_map(core::convert::identity) |
| 2582 | } |
| 2583 | } |
| 2584 | |