Using the let keyword, you can specify a pattern that is compared against the specified expression. If the expression matches the pattern, we execute the if block; otherwise, run the else block.
Let us explore how to use them if let expression in Rust.
If Let
We can express the syntax for the if let construct as shown below:
// run me
} else {
// run met
}
Consider the example below that illustrates how to use them if let expression in Rust:
letdb = "MySQL";
iflet"MySQL" = db {
println!("You need a schema!")
} elseiflet"MongoDB" = db {
println!("You do not need a schema!");
}
}
In the example above, we have a variable db that holds the string “MySQL”. We then use the if let expression to check for a specific pattern.
If the value is “MySQL”, we execute the block inside the if let block. Otherwise, run the else if let block.
Running the code above should return:
If we change the value of the db variable to “MongoDB”. We can get the result as shown:
The output is as shown:
We can also define a condition for all non-matching patterns using the else block. An example is as shown:
letdb = "Unknown";
iflet"MySQL" = db {
println!("You need a schema!")
} elseiflet"MongoDB" = db {
println!("You do not need a schema!");
} else {
println!("Unknown database paradigm!")
}
}
In the above example, the value of the db variable is “Unknown”. Since a blocking matches that pattern, the other block is executed.
We can use the if let block to assign a value to a variable. An example is as shown below:
"MySQL"
}else {
"MongoDB"
};
println!("Db is {}: ", db);
If the value is true, set the variable to “MySQL”; else, set the value to “MongoDB”. The returning value is shown:
Ending
This guide explores the fundamentals of using the if let expression in Rust. The if let expression allows us to specify a code block if an expression matches a specified pattern.