Skip to main content

How to Use Option for a Value That May Be Missing in Rust

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

Rust has no null. A value that may be missing is an Option: Some(value) when it's there, and None when it isn't. The compiler makes you deal with None before you use the value, for example with unwrap_or, which gives a default.

Syntax​

Syntax
let <name>: Option<T> = Some(<value>);
let <name>: Option<T> = None;

<name>.is_some()
<name>.is_none()
<name>.unwrap_or(<default>)
PartWhat it does
Option<T>A value of type T that may be missing, where T is the value's type, such as &str.
Some(<value>)An Option that holds a value.
NoneAn Option that holds nothing.
.is_some(), .is_none()true when the Option holds a value, or when it doesn't.
.unwrap_or(<default>)The value when there is one, otherwise <default>, which must have the same type.

The std::option documentation: "Type Option represents an optional value: every Option is either Some and contains a value, or None, and does not." The Rust Book, The Option Enum, says why: "Rust does not have nulls, but it does have an enum that can encode the concept of a value being present or absent."

The Example​

The example holds the nicknames of two users: one set a nickname, Addie, and the other didn't. It prints both Options, checks which one holds a value, and prints each nickname with a default for the missing one. Then a changed version calls a string method on the Option itself.

Prerequisites​

  • Rust, with Cargo. This guide uses Rust 1.100.1.

Step 1: Create the Project and Write the Code​

Terminal
cargo new demo
cd demo

cargo new demo creates a project with a src/main.rs. Replace its contents:

src/main.rs, which sets nickname to Some Addie and no_nickname to None, prints both with the Debug format, prints nickname.is_some() and no_nickname.is_none(), and prints both with unwrap_or no nickname.

src/main.rs
fn main() {
// One user set a nickname; another didn't.
let nickname: Option<&str> = Some("Addie");
let no_nickname: Option<&str> = None;

println!("{nickname:?}");
println!("{no_nickname:?}");

println!("{}", nickname.is_some());
println!("{}", no_nickname.is_none());

println!("{}", nickname.unwrap_or("no nickname"));
println!("{}", no_nickname.unwrap_or("no nickname"));
}
  • Option<&str> is a piece of text that may be missing.
  • {nickname:?} prints the Option with the Debug format, which shows whether it's Some or None.
  • is_some() and is_none() check whether a value is there.
  • unwrap_or("no nickname") gives the nickname, or no nickname when there isn't one.

Step 2: Run It​

Terminal
cargo run -q
Output
Some("Addie")
None
true
true
Addie
no nickname

-q keeps Cargo quiet, so only the program's output shows. The command is the same in zsh, bash and PowerShell.

Step 3: Call a String Method on the Option​

Replace src/main.rs with a version that adds one line at the end, which calls to_uppercase() on the Option:

src/main.rs
fn main() {
// One user set a nickname; another didn't.
let nickname: Option<&str> = Some("Addie");
let no_nickname: Option<&str> = None;

println!("{nickname:?}");
println!("{no_nickname:?}");

println!("{}", nickname.is_some());
println!("{}", no_nickname.is_none());

println!("{}", nickname.unwrap_or("no nickname"));
println!("{}", no_nickname.unwrap_or("no nickname"));

println!("{}", nickname.to_uppercase());
}
Terminal
cargo run -q
Output
error[E0599]: no method named `to_uppercase` found for enum `Option<T>` in the current scope
--> src/main.rs:15:29
|
15 | println!("{}", nickname.to_uppercase());
| ^^^^^^^^^^^^ method not found in `Option<&str>`
|
note: the method `to_uppercase` exists on the type `&str`
--> /rustc/20ddd01716a87c0fcf06ae4752d85a4abc15bcdf/library/alloc/src/str.rs:656:4
help: consider using `Option::expect` to unwrap the `&str` value, panicking if the value is an `Option::None`
|
15 | println!("{}", nickname.expect("REASON").to_uppercase());
| +++++++++++++++++

For more information about this error, try `rustc --explain E0599`.
error: could not compile `demo` (bin "demo") due to 1 previous error

A zsh terminal where cargo run -q prints Some Addie, None, true, true, Addie and no nickname, then, for the changed file, fails with error E0599, no method named to_uppercase found for enum Option, with a note that the method exists on the type str.

What Happened​

  • Some("Addie") and None: the Debug format shows what each Option holds.
  • true and true: nickname holds a value, and no_nickname doesn't.
  • Addie and no nickname: unwrap_or gave the value from Some, and the default for None.
  • The changed version didn't compile. An Option<&str> isn't a &str, so it doesn't have the methods of &str. The note says the method exists on &str, and the help suggests expect, which takes the value out but panics on None.

Take the value out where it's there, and decide what happens when it isn't. In my checks, if let Some(name) = nickname with name.to_uppercase() inside printed ADDIE, and no_nickname.unwrap_or("no nickname").to_uppercase() printed NO NICKNAME.

Common Mistakes​

MistakeWhat happensDo this instead
Calling a method of the value on the Option, as in nickname.to_uppercase()error[E0599]: no method named `to_uppercase` found for enum `Option<T>` in the current scopeTake the value out first, with if let Some(name) = nickname or unwrap_or
Printing an Option with {}error[E0277]: `Option<&str>` doesn't implement `std::fmt::Display` Print it with {:?}, or print the value after taking it out
unwrap() on an Option that may be NoneWith None, the program panics: called `Option::unwrap()` on a `None` valueUse unwrap_or with a default, or if let
null for a missing valueerror[E0425]: cannot find value `null` in this scopeUse None
None in a variable of the value's own type, as in let nickname: &str = None;error[E0308]: mismatched types: expected &str, found Option<_>Declare the variable as Option<&str>

Troubleshooting​

SymptomLikely causeFix
error[E0624]: method `len` is private on an Optionlen() was called on the Option, which has a private len of its ownTake the value out first, as shown in this fix
A panic with the message you gave expect, such as a nickname is setexpect on an Option that was NoneKeep expect for values that can only be missing because of a bug

FAQ​

How do I run code only when there is a value?​

With if let: if let Some(name) = nickname { ... } runs its block only for Some, with the value in name. A match handles both cases: with Some(name) and None as its two arms, it printed no nickname for no_nickname.

How do I change the value and keep it in an Option?​

With map: nickname.map(|name| name.to_uppercase()) gave Some("ADDIE"), and on no_nickname it gave None.

What about an Option of a String?​

It works the same way. as_deref() turns an Option<String> into an Option<&str>, so nickname.as_deref().unwrap_or("no nickname") gave Addie, and no nickname for None.

Conclusion​

An Option holds a value that may be missing: Some(value) or None. Check it with is_some or is_none, give it a default with unwrap_or, or take the value out with if let, and the compiler makes sure you never use a missing value by accident.

Additional Resources​