I don't see the reason why we use if let
and just usual if
.
In Rust book, chapter 6.3, the sample code is below:
let some_u8_value = Some(0u8);
if let Some(3) = some_u8_value {
println!("three");
}
The code above is same with:
let some_u8_value = Some(0u8);
if Some(3) == some_u8_value {
println!("three");
}
Any other reason on why we would use if let
or what is it specifically for?
The if let expression in rust allows you to match an expression to a specific pattern. This is different from the if expression that runs when a condition is true. Using the let keyword, you can specify a pattern that is compared against the specified expression.
In this Rust tutorial we learn how to control the flow of our Rust application with if, else if, else, and match conditional statements. We also cover how to nest conditional statements inside other conditional statements as well as how to conditionally assign a value to a variable if the if let expression.
ref annotates pattern bindings to make them borrow rather than move. It is not a part of the pattern as far as matching is concerned: it does not affect whether a value is matched, only how it is matched.
Rust doesn't have null , but if you want to talk about a value that may not exist, you use Option<WhateverTypeThatValueIs> . When it does exist, it will be a Some(value) , else None . Example: let x: Option<u32> = Some(2); assert_eq!(
Another reason is if you wish to use the pattern bindings. For example consider an enum:
enum Choices {
A,
B,
C(i32),
}
If you wish to implement specific logic for the C
variant of Choices
, you can use the if-let expression:
let choices: Choices = ...;
if let Choices::C(value) = choices {
println!("{}", value * 2);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With