Text of rust.docs.kernel.org › next › src › core › option.rs.html as Styx crawled it on Nov 19, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

option.rs - source

Skip to main content core/ option.rs 1 //! Optional values. 2 //! 3 //! Type [`Option`] represents an optional value: every [`Option`] 4 //! is either [`Some`] and contains a value, or [`None`], and 5 //! does not. [`Option`] types are very common in Rust code, as 6 //! they have a number of uses: 7 //! 8 //! * Initial values 9 //! * Return values for functions that are not defined 10 //! over their entire input range (partial functions) 11 //! * Return value for otherwise reporting simple errors, where [`None`] is 12 //! returned on error 13 //! * Optional struct fields 14 //! * Struct fields that can be loaned or "taken" 15 //! * Optional function arguments 16 //! * Nullable pointers 17 //! * Swapping things out of difficult situations 18 //!

19 //! [`Option`]s are commonly paired with pattern matching to query the presence 20 //! of a value and take action, always accounting for the [`None`] case. 21 //! 22 //! ``` 23 //! fn divide(numerator: f64, denominator: f64) -> Option<f64> { 24 //! if denominator == 0.0 { 25 //! None 26 //! } else { 27 //! Some(numerator / denominator) 28 //! } 29 //! } 30 //! 31 //! // The return value of the function is an option 32 //! let result = divide(2.0, 3.0); 33 //!

34 //! // Pattern match to retrieve the value 35 //! match result { 36 //! // The division was valid 37 //! Some(x) => println!("Result: {x}"), 38 //! // The division was invalid 39 //! None => println!("Cannot divide by 0"), 40 //! } 41 //! ``` 42 //! 43 //! # Options and pointers ("nullable" pointers) 44 //! 45 //! Rust's pointer types must always point to a valid location; there are 46 //! no "null" references. Instead, Rust has *optional* pointers, like 47 //! the optional owned box, <code>[Option]<[Box\<T>]></code>.

48 //! 49 //! [Box\<T>]: ../../std/boxed/struct.Box.html 50 //! 51 //! The following example uses [`Option`] to create an optional box of 52 //! [`i32`]. Notice that in order to use the inner [`i32`] value, the 53 //! `check_optional` function first needs to use pattern matching to 54 //! determine whether the box has a value (i.e., it is [`Some(...)`][`Some`]) or 55 //! not ([`None`]). 56 //! 57 //! ``` 58 //! let optional = None; 59 //! check_optional(optional); 60 //!

61 //! let optional = Some(Box::new(9000)); 62 //! check_optional(optional); 63 //! 64 //! fn check_optional(optional: Option<Box<i32>>) { 65 //! match optional { 66 //! Some(p) => println!("has value {p}"), 67 //! None => println!("has no value"), 68 //! } 69 //! } 70 //! ``` 71 //! 72 //! # The question mark operator, `?` 73 //! 74 //! Similar to the [`Result`] type, when writing code that calls many functions that return the 75 //! [`Option`] type, handling `Some`/`None` can be tedious.

The question mark 76 //! operator, [`?`], hides some of the boilerplate of propagating values 77 //! up the call stack. 78 //! 79 //! It replaces this: 80 //! 81 //! ``` 82 //! # #![allow(dead_code)] 83 //! fn add_last_numbers(stack: &mut Vec<i32>) -> Option<i32> { 84 //! let a = stack.pop(); 85 //! let b = stack.pop(); 86 //! 87 //! match (a, b) { 88 //! (Some(x), Some(y)) => Some(x + y), 89 //! _ => None, 90 //! } 91 //! } 92 //!

93 //! ``` 94 //! 95 //! With this: 96 //! 97 //! ``` 98 //! # #![allow(dead_code)] 99 //! fn add_last_numbers(stack: &mut Vec<i32>) -> Option<i32> { 100 //! Some(stack.pop()? + stack.pop()?) 101 //! } 102 //! ``` 103 //! 104 //! *It's much nicer!* 105 //! 106 //! Ending the expression with [`?`] will result in the [`Some`]'s unwrapped value, unless the 107 //! result is [`None`], in which case [`None`] is returned early from the enclosing function.

108 //! 109 //! [`?`] can be used in functions that return [`Option`] because of the 110 //! early return of [`None`] that it provides. 111 //! 112 //! [`?`]: crate::ops::Try 113 //! [`Some`]: Some 114 //! [`None`]: None 115 //! 116 //! # Representation 117 //! 118 //! Rust guarantees to optimize the following types `T` such that [`Option<T>`] 119 //! has the same size, alignment, and [function call ABI] as `T`. It is 120 //! therefore sound, when `T` is one of these types, to transmute a value `t` of 121 //! type `T` to type `Option<T>` (producing the value `Some(t)`) and to 122 //! transmute a value `Some(t)` of type `Option<T>` to type `T` (producing the 123 //! value `t`).

124 //! 125 //! In some of these cases, Rust further guarantees the following: 126 //! - `transmute::<_, Option<T>>([0u8; size_of::<T>()])` is sound and produces 127 //! `Option::<T>::None` 128 //! - `transmute::<_, [u8; size_of::<T>()]>(Option::<T>::None)` is sound and produces 129 //! `[0u8; size_of::<T>()]` 130 //! 131 //! These cases are identified by the second column: 132 //! 133 //! | `T` | Transmuting between `[0u8; size_of::<T>()]` and `Option::<T>::None` sound? | 134 //! |---------------------------------------------------------------------|----------------------------------------------------------------------------| 135 //! | [`Box<U>`] (specifically, only `Box<U, Global>`) | when `U: Sized` | 136 //! | `&U` | when `U: Sized` | 137 //! | `&mut U` | when `U: Sized` | 138 //! | `fn`, `extern "C" fn`[^extern_fn] | always | 139 //! | [`num::NonZero*`] | always | 140 //! | [`ptr::NonNull<U>`] | when `U: Sized` | 141 //! | `#[repr(transparent)]` struct around one of the types in this list. | when it holds for the inner type | 142 //!

143 //! [^extern_fn]: this remains true for `unsafe` variants, any argument/return types, and any other ABI: `[unsafe] extern "abi" fn` (_e.g._, `extern "system" fn`) 144 //! 145 //! Under some conditions the above types `T` are also null pointer optimized when wrapped in a [`Result`][result_repr]. 146 //! 147 //! [`Box<U>`]: ../../std/boxed/struct.Box.html 148 //! [`num::NonZero*`]: crate::num 149 //! [`ptr::NonNull<U>`]: crate::ptr::NonNull 150 //! [function call ABI]: ../primitive.fn.html#abi-compatibility 151 //! [result_repr]: crate::result#representation 152 //!

153 //! This is called the "null pointer optimization" or NPO. 154 //! 155 //! It is further guaranteed that, for the cases above, one can 156 //! [`mem::transmute`] from all valid values of `T` to `Option<T>` and 157 //! from `Some::<T>(_)` to `T` (but transmuting `None::<T>` to `T` 158 //! is undefined behavior). 159 //! 160 //! # Method overview 161 //! 162 //! In addition to working with pattern matching, [`Option`] provides a wide 163 //! variety of different methods.

164 //! 165 //! ## Querying the variant 166 //! 167 //! The [`is_some`] and [`is_none`] methods return [`true`] if the [`Option`] 168 //! is [`Some`] or [`None`], respectively. 169 //! 170 //! The [`is_some_and`] and [`is_none_or`] methods apply the provided function 171 //! to the contents of the [`Option`] to produce a boolean value. 172 //! If this is [`None`] then a default result is returned instead without executing the function.

173 //! 174 //! [`is_none`]: Option::is_none 175 //! [`is_some`]: Option::is_some 176 //! [`is_some_and`]: Option::is_some_and 177 //! [`is_none_or`]: Option::is_none_or 178 //! 179 //! ## Adapters for working with references 180 //! 181 //! * [`as_ref`] converts from <code>[&][][Option]\<T></code> to <code>[Option]<[&]T></code> 182 //! * [`as_mut`] converts from <code>[&mut] [Option]\<T></code> to <code>[Option]<[&mut] T></code> 183 //! * [`as_deref`] converts from <code>[&][][Option]\<T></code> to 184 //! <code>[Option]<[&]T::[Target]></code> 185 //! * [`as_deref_mut`] converts from <code>[&mut] [Option]\<T></code> to 186 //! <code>[Option]<[&mut] T::[Target]></code> 187 //! * [`as_pin_ref`] converts from <code>[Pin]<[&][][Option]\<T>></code> to 188 //! <code>[Option]<[Pin]<[&]T>></code> 189 //! * [`as_pin_mut`] converts from <code>[Pin]<[&mut] [Option]\<T>></code> to 190 //! <code>[Option]<[Pin]<[&mut] T>></code> 191 //! * [`as_slice`] returns a one-element slice of the contained value, if any.

192 //! If this is [`None`], an empty slice is returned. 193 //! * [`as_mut_slice`] returns a mutable one-element slice of the contained value,

The rest of this page is on the live site.