if blocksThey allow us to make decisions based on conditions
"If the condition is met (i.e. returns true), run the specified code; otherwise, don't (and do something else)"
ifConditions are boolean expressions:
==, !=, >, <, >=, <=Optionally combined together with logical operators:
&& ("and"), || ("or"), ! ("not")
if
fn main(){
let n = 42;
if n == 42 {
println!("The number is THE ANSWER");
} else {
println!("The number is not the answer");
}
}
ifYou can check multiple conditions with the else if keywords:
fn main(){
let n = 15;
if n % 3 == 0 && n % 5 == 0 {
println!("FizzBuzz");
} else if n % 3 == 0 {
println!("Fizz");
} else if n % 5 == 0 {
println!("Buzz");
} else {
println!("{}", n);
}
}
ifif blocks are expressions, meaning you can do stuff like:
fn main(){
let condition = true;
let var = if condition { 5 } else { 10 };
println!("var: {}", var); // Prints "5"
}