Combining if and let allows you to handle values that match one of the patterns while disregarding the remaining code. This is done with the if let syntax. The “if let” expression and the “match” operator operate similarly.
fn main()
{
let a = Some(5);
match a {
Some(5) => println!("five"),
_ => (),
}}
five
When the value in the example above equals Some(5), the match operator runs the code. After running the first variant, the “_=>()” expression satisfies the match expression. The length of the code is decreased if we use if let in instead of match.
fn main()
{
let a=Some(3);
if let Some(3)=a{
println!("three");
}
}
three
CodingAsk.com is designed for learning and practice. Examples may be made simpler to aid understanding. Tutorials, references, and examples are regularly checked for mistakes, but we cannot guarantee complete accuracy. By using CodingAsk.com, you agree to our terms of use, cookie, and privacy policy.
Copyright 2010-2024 by Refsnes Data. All Rights Reserved.