Use if/else expressions in Rust to evaluate conditions and assign values or execute code based on the result.
Use if and else to evaluate a condition and assign a value or execute code based on the result.
fn main() {
let number = 6;
let result = if number % 4 == 0 {
"divisible by 4"
} else if number % 3 == 0 {
"divisible by 3"
} else {
"not divisible"
};
println!("The number is {result}");
}
An if/else expression lets your program make decisions by checking if a condition is true or false. Think of it like a fork in the road: if the condition is met, you take one path; otherwise, you take the other. In Rust, this is special because the result of the check can be stored directly as a value, unlike in many other languages where it is just a command.