beginnerFlow Control
If Let
Concise pattern matching for a single case.
If Let
Concise pattern matching for a single case.
Difficulty
Beginner
Code
rust
fn main() {
let config_max: Option<u8> = Some(3);
if let Some(max) = config_max {
println!("max is {}", max);
}
let val: Result<i32, &str> = Ok(42);
if let Ok(v) = val {
println!("value: {}", v);
}
}Explanation
This example demonstrates how to use if let in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.
Key Concepts
- Rust's strong type system catches errors at compile time
- Ownership and borrowing rules ensure memory safety
- Pattern matching makes code expressive and exhaustive
Related Topics
Browse more examples in the flow-control category to build a complete understanding of this topic.