Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Rust Option


Share

Option

Sometimes a value can be missing. For example, you ask a vector for its tenth item, but the vector only has three items.

Many programming languages use a special value called null to mean "no value". If the programmer forgets to check for null, the program can crash.

Rust does not have null. Instead, it uses Option. In the Enums chapter, you learned that enum variants can hold data. Option is an enum that is built into Rust, and it has two variants:

  • Some(value) - there is a value
  • None - there is no value

For example, the get() method of a vector returns an Option:

Example

let fruits = vec!["apple", "banana", "cherry"];

println!("{:?}", fruits.get(0)); // Some("apple")
println!("{:?}", fruits.get(9)); // None
Try it Yourself »

Compare this with fruits[9], which stops the program with an error, because there is no item at index 9. get() does not crash. It returns None instead, and lets you decide what to do.


Check the Value With match

To use the value inside an Option, you must first check if it is Some or None. One way is to use match, just like with other enums:

Example

let fruits = vec!["apple", "banana", "cherry"];

match fruits.get(1) {
  Some(fruit) => println!("Found: {}", fruit),
  None => println!("No fruit at that position"),
}
Try it Yourself »

If there is a value, Some(fruit) puts it in the variable fruit, so you can use it in that branch.

Rust makes you handle both cases. If you remove the None branch, the code will not compile. This way, you can never forget to check for a missing value.


if let

When you only want to do something if there is a value, if let is shorter than match:

Example

let fruits = vec!["apple", "banana", "cherry"];

if let Some(fruit) = fruits.get(2) {
  println!("The third fruit is {}", fruit);
}
Try it Yourself »

You can read it like this: "if fruits.get(2) is Some(fruit), run the code inside". If the result is None, the code inside is skipped.

You can also add an else block, which runs when there is no value:

Example

let fruits = vec!["apple", "banana", "cherry"];

if let Some(fruit) = fruits.get(5) {
  println!("The sixth fruit is {}", fruit);
} else {
  println!("There is no sixth fruit");
}
Try it Yourself »

Note: The get() method of a HashMap also returns an Option. That is why the HashMap chapter used if let Some(city) = ... to read a value.



Return an Option From a Function

Your own functions can also return an Option. Write Option<i32> as the return type, where i32 is the type of the value inside Some.

For example, you cannot divide a number by zero, so this function returns None when b is 0:

Example

fn divide(a: i32, b: i32) -> Option<i32> {
  if b == 0 {
    None
  } else {
    Some(a / b)
  }
}

fn main() {
  match divide(10, 2) {
    Some(result) => println!("10 / 2 = {}", result),
    None => println!("Cannot divide by zero"),
  }

  match divide(10, 0) {
    Some(result) => println!("10 / 0 = {}", result),
    None => println!("Cannot divide by zero"),
  }
}
Try it Yourself »

Use a Default Value

The unwrap_or() method gives you the value inside Some, or a default value if it is None. Here, we use the divide() function from the example above:

Example

let x = divide(10, 2).unwrap_or(0);
let y = divide(10, 0).unwrap_or(0);

println!("x = {}", x); // 5
println!("y = {}", y); // 0
Try it Yourself »

Note: There is also an unwrap() method. It returns the value inside Some, but it stops the program with an error if the value is None. You will learn more about this in the Error Handling chapter.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.