In Rust, why is Option<T> an ordinary enum rather than a nullable value, and why can't an Option<u64> be passed where a u64 is expected?
answer
- defined in core, not the compiler
- two variants, one carries T
- the prelude imports Some and None
- distinct type, so E0308
basics
~20 sOption<T> is a plain library enum, enum Option<T> { None, Some(T) }, defined in core and imported by the prelude. Option<u64> is a different type from u64, so rustc rejects passing it (E0308) until code matches the value out.
solid answer
~40 sThe standard library defines `Option` in `core::option` as `enum Option<T> { None, Some(T) }`, and the prelude re-exports `Option`, `Some` and `None`, which is why `Some(5)` needs no path. Because it is an ordinary enum, `Option<u64>` and `u64` are different types: passing one where the other is expected is E0308, and adding one to a `u64` is E0277, so an absent value cannot slip through as a zero. You take the value out as from any enum, with `match`, `if let` or one of the methods in Option's `impl` block. You could write the same enum yourself and match it identically; what you would lose is narrow: the `?` operator (implementing `Try` is unstable), the documented guarantee that `Option<&T>` is the size of `&T`, and the methods.
code
rust · 27 lines// The same shape as core's definition: enum Option<T> { None, Some(T) }
#[derive(Debug)]
enum Lookup<T> {
Missing,
Found(T),
}
fn find_balance(account: &str) -> Option<u64> {
if account == "acct-7" { Some(12_500) } else { None }
}
fn find_balance_mine(account: &str) -> Lookup<u64> {
if account == "acct-7" { Lookup::Found(12_500) } else { Lookup::Missing }
}
fn main() {
// Some and None come from the prelude, so no Option:: prefix is needed.
match find_balance("acct-9") {
Some(cents) => println!("balance {cents}"),
None => println!("no such account"),
}
// A home-made enum is matched exactly the same way.
if let Lookup::Found(cents) = find_balance_mine("acct-7") {
println!("balance {cents}");
}
println!("{:?}", find_balance_mine("acct-9"));
}go deeper
Recall the two variants, that Some(5) and None come from the prelude, and that you match an Option to get its value out.
Explain that Option is a generic enum defined in core, why passing it where T is expected is E0308, and what a home-made copy would and would not support.
Show where absence is decided: at the boundary where an Option is matched, not deep in callers, and why unwrap belongs only where None is a bug.
Argue why APIs should return Option instead of sentinel values like 0 or u64::MAX, and how that choice pushes the absent case to callers the compiler can check.
## The definition `Option` is not built into the language. The standard library defines it in `core::option`, and the definition is a two-variant generic enum: ```rust pub enum Option<T> { None, Some(T), } ``` `None` is a unit variant meaning "no value"; `Some(T)` is a tuple variant carrying the value. Its methods — `is_some`, `map`, `unwrap_or`, `as_ref` and the rest — are defined in ordinary `impl` blocks in the same file, next to its trait implementations. The methods that transform an `Option` are taught with error handling; this lesson is about the enum underneath them. ## How it reaches your code: the prelude You write `Some(5)` and `None` without `Option::` because of the **prelude**, the set of names imported into every module. Both `std`'s and `core`'s prelude contain the line `pub use crate::option::Option::{self, None, Some};`, which imports: - the type name `Option`; - the variant `Some`, as a constructor function and a pattern; - the variant `None`, as a constant and a pattern. Nothing else is special about those names: they are an enum's variants re-exported by a `use` declaration, not keywords. Option has been in the prelude since Rust 1.0; the 2024 edition's prelude additions were `Future` and `IntoFuture`. ## A different type, not a nullable value Because `Option<u64>` is its own enum type, it never stands in for a `u64`: | Code | What rustc does | |---|---| | `charge(found)` with `fn charge(cents: u64)` and `found: Option<u64>` | E0308, mismatched types: expected `u64`, found `Option<u64>` | | `let total: u64 = 10 + Some(5);` | E0277, cannot add `Option<{integer}>` to `{integer}` | | `let n: u64 = None;` | E0308, mismatched types | This is the practical point interviewers look for. A value that may be absent has a different type from one that is always present, so the absent case cannot reach code that assumes a value; the compiler makes you decide what `None` means at the place you unwrap it. A reference `&T` in Rust is never null, so "maybe a reference" is spelled `Option<&T>`. ## Getting the value out Since `Option` is an enum, you take it apart like any enum: 1. **`match`**: `match find_balance(id) { Some(cents) => ..., None => ... }` forces both cases to be handled. 2. **`if let Some(cents) = ...`** handles one case and skips the other (that construct belongs with control flow). 3. **Methods** from the `impl` block, such as `unwrap_or(0)` or `map(...)`, which are matches written once in the library. 4. **`unwrap()` and `expect("...")`** extract the value and panic on `None`; when that is acceptable is a question for the material on panics. The compiler's own hint for the E0308 case above suggests `found.expect("REASON")`, which is an answer only when `None` really is a bug. ## What is special about Option, and what is not You could write the same enum yourself, `enum Lookup<T> { Missing, Found(T) }`, and match it exactly the same way. The differences are real but narrow: - **Lang items.** The definition carries `#[lang = "Option"]`, `#[lang = "Some"]` and `#[lang = "None"]` attributes, so the compiler can refer to it in desugarings: the Reference shows a `for` loop expanding into a `match` on `Iterator::next` with `Option::Some(val)` and `None => break` arms. - **The `?` operator.** `?` works on `Option` because the library implements the `Try` trait for it. Implementing `Try` for your own enum is unstable (`try_trait_v2`), so `get()?` on a home-made `Lookup` fails on stable with E0277, "the `?` operator can only be applied to values that implement `Try`". - **A size guarantee.** The `Option` documentation guarantees that `Option<T>` has the same size as `T` for references, `Box`, function pointers, `NonZero` integers and `NonNull`. rustc applies the same trick to a home-made enum in practice (`Lookup<&u64>` is 8 bytes on rustc 1.99.1), but only `Option` carries the written promise; the full layout rules are a topic of their own. - **The ecosystem.** Every std API that may find nothing returns `Option`, and its methods and trait impls come with it. ## The interview summary `Option` is a library enum with two variants, imported by the prelude, and that is exactly why it is safe: an enum is a distinct type, so a possibly-absent value cannot be used as a present one until code matches it.
- What would you lose by replacing Option with your own `enum Lookup<T> { Missing, Found(T) }`?Matching works identically. You lose `?`, because implementing the `Try` trait for your own type is unstable and `get()?` fails with E0277; you lose Option's methods and trait impls; and the documented size guarantee for `Option<&T>` belongs to Option, even though rustc applies the same layout trick to your enum in practice.
- Why does `Some(5)` compile without `Option::Some` or a `use` line?The prelude, imported into every module, contains `pub use crate::option::Option::{self, None, Some};` in both `std` and `core`. `Some` and `None` are therefore ordinary variant names brought into scope, not keywords; a local item with the same name would shadow them.
- Option is a compiler built-in that you cannot reproduce in your own code.
- None is Rust's null, so any reference might secretly be None.
- An Option<u64> converts to u64 automatically, with None becoming 0.
- Some and None are language keywords rather than enum variants.
- Wrapping a value in Option always adds a tag byte and padding.