Introduction
Option is a predefined enum type in Rust which is used to make fields optional.
Examples
enum Option<T> {
Some(T),
None,
}
Some represents the presence of a value of generic type T
None represents the absence of a value.
Below is an example when Option can be used.
#[derive(Debug)]
struct Player {
name: String,
age: u32,
score: Option<u32>,
team: Option<String>,
}
fn main() {
let player1 = Player {
name: String::from("Ash Ketchum"),
age: 10,
score: Some(100),
team: Some(String::from("Forever Young")),
};
let player2 = Player {
name: String::from("John Cena"),
age: 40,
score: None,
team: None,
};
let player1 = populate_player(String::from("Ash Ketchum"), 10, Some(100), Some(String::from("Forever Young")));
let player2 = populate_player(String::from("John Cena"), 40, None, None);
println!("{:#?}", player1);
println!("{:#?}", player2);
}
fn populate_player(name: String, age: u32, score: Option<u32>, team: Option<String>) -> Player {
Player {
name,
age,
score,
team,
}
}
So we have a struct Player with optional fields score and team.
Now we have two players. Ash Ketchum is 10 years old, we all know, and he belongs to the team Forever Young.
On the otherhand, John Cena doesn't have a score or doesn't belong to any Team, which is also a valid case.
Both players are populated using the populate_player function and below is the output.
Player {
name: "Ash Ketchum",
age: 10,
score: Some(
100,
),
team: Some(
"Forever Young",
),
}
Player {
name: "John Cena",
age: 40,
score: None,
team: None,
}
Conclusion
That's all about the Option type in Rust. In the next article we'll discuss about another predefined enum Result. Cheers!