Deciding whether or no to run some code depending on if a condition its true and deciding to run some code repeatdly while a condition is true are basic building blocks in most programming languages. The most common constructs that let us control the flow of executionof Rust code are if expressions and loops.
- If Expressions
Look at this code for example :
fn main() {
let number = 3;
if number < 5 {
println!("The values of number is {} ", number);
} else {
println!("More than or equal with 5");
}
}
All if expressions start with keyword if, which is followed by a condition. In this case, the condition checks whether variable number has a value less than 5. The block of code we want to execute if the condition is true is placed immediately after the condition inside curly brackets. Blocks of code associated with the expressions in if expressions are sometimes called arms.
It's also worth noting that the condition in this code must be a bool. If the condition isn't bool, we'll get an error. Try this code for example :
fn main() {
let number = 3;
if number {
println!("The values if number is {}", number);
}
}
The error indicated that Rust expected a bool but got an integer. Unlike languages such as Ruby and Javascript, Rust will not automatically try to convert non-Boolean types to a Boolean. We must explicit and always provide if with a Boolean as its condition. If we want the if code block to run only when a number is not equal to 0.
In additional, we can have multiple conditions by combining if and else in an else if expression. For example :
fn main() {
let number = 6;
if number % 4 == 0 {
println!("The number is divisible by 4");
} else if number % 3 == 0 {
println!("The number is divisible by 3");
}
else if number % 2 == 0 {
println!("The number is divisible by 2");
}
}
This program has four possible paths it can take. When this program executes, it checks each if expression in turn and executes the first body for which the condition hold true. Using too many else if expressions can clutter our code, so if we have more than one, we might want refactor our code. Later we'll discuss how to refactor our code with macth.
Tags:
Rust