Rust Option
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 valueNone- 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.