Rust Option & Result
Many languages use a special null value to mean "nothing here", and forgetting to check for it is one of the most common causes of crashes. Rust has no null. Instead, the standard library provides two enums that make "might be missing" and "might fail" part of the type:
| Enum | Variants | Meaning |
|---|---|---|
Option<T> |
Some(T), None |
a value that may or may not exist |
Result<T, E> |
Ok(T), Err(E) |
an operation that either succeeds with T or fails with error E |
Because they are types, the compiler won't let you use an Option<i32> as if it were an i32. You must deal with the None case first.
Option: maybe a value
Functions return Option when "no answer" is a normal outcome — finding an item in a list, getting the first character of a possibly empty string, and so on.
fn find_index(names: &[&str], target: &str) -> Option<usize> {
for (i, name) in names.iter().enumerate() {
if *name == target {
return Some(i);
}
}
None
}
fn main() {
let team = ["Kim", "Lou", "Max"];
match find_index(&team, "Lou") {
Some(i) => println!("Lou is at position {}", i),
None => println!("Lou is not on the team"),
}
match find_index(&team, "Zed") {
Some(i) => println!("Zed is at position {}", i),
None => println!("Zed is not on the team"),
}
}Lou is at position 1
Zed is not on the team
Result: success or error
Result is used when something can fail and you want to explain why. The error type E carries the reason. Parsing text into a number is a classic example: "42".parse::<i32>() returns Ok(42), while "forty".parse::<i32>() returns an Err.
fn check_age(age: i32) -> Result<i32, String> {
if age < 0 {
Err(String::from("age cannot be negative"))
} else if age > 150 {
Err(format!("{} is not a realistic age", age))
} else {
Ok(age)
}
}
fn main() {
for input in [30, -4, 200] {
match check_age(input) {
Ok(a) => println!("Valid age: {}", a),
Err(msg) => println!("Error: {}", msg),
}
}
match "forty".parse::<i32>() {
Ok(n) => println!("Parsed {}", n),
Err(e) => println!("Could not parse: {}", e),
}
}Valid age: 30
Error: age cannot be negative
Error: 200 is not a realistic age
Could not parse: invalid digit found in string
Getting the value out
match always works, but there are many helper methods for common situations:
| Method | On Some(v) / Ok(v) |
On None / Err(e) |
|---|---|---|
unwrap() |
returns v |
panics |
expect("msg") |
returns v |
panics with your message |
unwrap_or(default) |
returns v |
returns default |
unwrap_or_default() |
returns v |
returns the type's default (0, "", …) |
is_some() / is_ok() |
true |
false |
map(f) |
Some(f(v)) / Ok(f(v)) |
unchanged |
ok() (Result only) |
Some(v) |
None |
fn main() {
let scores = vec![80, 95, 70];
let empty: Vec<i32> = Vec::new();
let best = scores.iter().max();
let none = empty.iter().max();
println!("best = {:?}, none = {:?}", best, none);
println!("with default: {}", none.unwrap_or(&0));
println!("doubled best: {:?}", best.map(|b| b * 2));
let good: Result<u8, _> = "200".parse::<u8>();
let bad: Result<u8, _> = "300".parse::<u8>(); // too big for u8
println!("good is ok? {}", good.is_ok());
println!("bad or zero: {}", bad.clone().unwrap_or(0));
println!("bad as option: {:?}", bad.ok());
}best = Some(95), none = None
with default: 0
doubled best: Some(190)
good is ok? true
bad or zero: 0
bad as option: None
Tip:
unwrap()is fine in quick experiments and tests, but in real programs prefermatch,if let,unwrap_oror the?operator (next lesson) so a missing value doesn't crash your program.
if let and let else
When you only care about the success case, if let keeps the code short. let ... else does the opposite: it binds the value, or runs an else block that must leave the function (with return, break and so on).
fn describe(input: &str) -> String {
let Ok(n) = input.parse::<i32>() else {
return format!("'{}' is not a number", input);
};
if n % 2 == 0 {
format!("{} is even", n)
} else {
format!("{} is odd", n)
}
}
fn main() {
let first_word = "hello world".split(' ').next();
if let Some(w) = first_word {
println!("First word: {}", w);
}
println!("{}", describe("12"));
println!("{}", describe("7"));
println!("{}", describe("abc"));
}First word: hello
12 is even
7 is odd
'abc' is not a number
Option or Result?
- Use
Optionwhen absence is normal and needs no explanation: "is there a user with this ID?". - Use
Resultwhen something went wrong and the caller may want to know what: "the file could not be opened because…".
Test yourself
What are the two variants of Option<T>?
- Ok and Err
- Some and None
- Value and Null
- True and False
What does "abc".parse::<i32>().unwrap_or(-1) evaluate to?
- 0
- It panics
- -1
- None
Which situation fits Result better than Option?
- Looking up a key that may not exist
- Getting the first element of a list
- Reading a file that may fail for several reasons
- Finding the maximum of an empty vector