Rust programming journey 1 - Study Conditional Statements
// Conditional Statements
fn main() {
let maybe_number: Option<Option<i32>> = Some(Some(42));
if let Some(inner_option)= maybe_number {
if let Some(number) = inner_option {
if number == 42 {
println!("The number is spcifically 42.");
} else {
println!("The number is {:?}", number);
}
} else {
println!("There is an inner option, but it's None.");
}
} else {
println!("There is no number.");
}
}
Explanation of the Code
Outer if let: I used if let Some(inner_option) = maybe_number to check if maybe_number has a value (Some). If it does, inner_option will hold the inner Option.
Inner if let: We use if let Some(number) = inner_option to check if inner_option contains a value. If it does, number will hold the actual integer (like 42).
Nested Condition: Inside the inner if let, we check if number is equal to 42. If it is, we print "The number is specifically 42!". If it's some other number, we print "The number is {:?}", number.
Handling Absence:
If inner_option is None, we print "There is an inner option, but it's None.".
If maybe_number is None, we print "There is no number.".
Testing with Different Values
Some(Some(42)) will print: "The number is specifically 42!".
Some(Some(7)) will print: "The number is 7".
Some(None) will print: "There is an inner option, but it's None.".
None will print: "There is no number."
This approach demonstrates how to handle nested Option values in Rust, while using conditional statements like if let and else if let to handle specific cases. It also provides a way to check the inner values while gracefully handling possible missing values.
key terms:
option: A Rust enum type that can be either Some(value) or None, used to represent optional values
if let: A pattern matching construct that allow you to conditionally bind variables based on their match against a given value or pattern.