Option<T>
- Rust course
- Beginner
- Lesson 80/115
- 4 min
Learn the Option<T> type and its Some/None variants.
Option<T>
Rust has no null. The "there may or may not be a value" case is expressed with an enum from the standard library:
enum Option<T> {
Some(T),
None,
}Option, Some and None are already in scope (the prelude); they're used without writing Option:::
fn bol(a: i32, b: i32) -> Option<i32> {
if b == 0 { None } else { Some(a / b) }
}Unpacking an Option
Ways of reaching the inner value:
let r = bol(10, 2);
match r {
Some(n) => println!("sonuç {n}"),
None => println!("sıfıra bölme"),
}
let n = bol(1, 0).unwrap_or(0); // 0 if None
let k = bol(9, 3).map(|v| v * 10); // Some(30)unwrap() panics on None; use it only where the value is certain to exist.
Practice Safe division
Write fn bol(a: i32, b: i32) -> Option<i32>: None if b == 0, otherwise Some(a / b). Print the results of bol(10, 2) and bol(1, 0) with {:?}, separated by a space.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn bol(a: i32, b: i32) -> Option<i32> {
if b == 0 {
None
} else {
Some(a / b)
}
}
fn main() {
println!("{:?} {:?}", bol(10, 2), bol(1, 0));
}Expected output
Some(5) None
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why doesn't <code>let x: Option<i32> = Some(5); let y = x + 1;</code> compile?
- Some is misspelled
- It compiles and gives 6
- Option<i32> isn't an i32; it must be unpacked first Correct answer
- 5 is too small
Explanation: The compiler forces you to think about the None case; this eliminates null bugs at compile time.
2 No value
fn bol(a: i32, b: i32) -> Option<i32> {
if b == 0 { ____ } else { Some(a / b) }
}
fn bol(a: i32, b: i32) -> Option<i32> {
if b == 0 { None } else { Some(a / b) }
}
Explanation: If there is no value, None is returned; Rust has no null.
3 Expression and result
| Term | Meaning |
|---|---|
bol(10, 2) |
Some(5) |
bol(1, 0) |
None |
bol(1, 0).unwrap_or(0) |
0 |
bol(9, 3).map(|v| v * 10) |
Some(30) |