6.4.1. What Is if let?
The if let syntax allows if and let to be combined into a less verbose way to handle a value that matches one pattern while ignoring the rest of the patterns.
You can think of if let as syntactic sugar for match, meaning it lets you write code for just one specific pattern.
6.4.2. Practical Use of if let
For example, v is a u8 variable. Determine whether v is 0, and print zero if it is.
use rand::Rng; // Use an external crate
fn main(){
let v: u8 = rand::thread_rng().gen_range(0..=255); // Generate a random number
println!("{}", v);
match v {
0 => println!("zero"),
_ => (),
}
}
Here we only need to distinguish between 0 and non-0. In this case, using if let is even simpler:
fn main(){
let v: u8 = rand::thread_rng().gen_range(0..=255); // Generate a random number
println!("{}", v);
if let 0 = v {
println!("zero");
};
}
Note: if let uses = rather than ==.
Let’s make a small change to the example above: v is a u8 variable. Determine whether v is 0; if it is, print zero, otherwise print not zero.
use rand::Rng; // Use an external crate
fn main(){
let v: u8 = rand::thread_rng().gen_range(0..=255); // Generate a random number
println!("{}", v);
match v {
0 => println!("zero"),
_ => println!("not zero"),
}
}
In this case, all you need to do is add an else branch to if let:
fn main(){
let v: u8 = rand::thread_rng().gen_range(0..=255); // Generate a random number
println!("{}", v);
if let 0 = v {
println!("zero");
} else {
println!("not zero");
}
}
6.4.3. Trade-offs When Using if let
Compared with match, if let has less code, less indentation, and fewer boilerplate parts. But if let gives up exhaustiveness.
So whether to use if let or match depends on the actual requirements. There is a trade-off here between conciseness and exhaustiveness.
6.4.5. The Difference Between if let and if
Many beginners get confused about the difference between if let and if, because it seems like anything if let can do, if can also do. But they are fundamentally different: if let is pattern matching, while if is a conditional statement.
The condition after if can only be a boolean, while if else matches whether a specific pattern is satisfied, which is suitable for extracting values from enums, Option, Result, or other types that support pattern matching.
For example:
fn main(){
let x = Some(5);
if let Some(value) = x {
println!("Found a value: {}", value);
} else {
println!("No value found");
}
}
if cannot unwrap an Option. To achieve this effect, you must use pattern matching (match and if let).