Writing a condition is quite easy in Rust and follow simple and intuitive syntax and rule.
- No need to write the condition within bracket.
fn main() {
let x = 4;
if x % 2 == 0 {
println!("{} is even.", x);
}
}
- The expression must be evaluated to boolean value, otherwise, Rust will complain.
fn main() {
let x = 4;
if x {
println!("{} is even.", x);
}
}
As usual, we've the else
with if
.
fn main() {
let x = 4;
if x % 2 == 0 {
println!("{} is even.", x);
} else {
println!("{} is odd.", x);
}
}
Or you can even use else if
in some specific scenario.
fn main() {
let x = 4;
if x > 0 {
println!("{} is positive.", x);
} else if x < 0 {
println!("{} is negative.", x);
} else {
println!("{} must be zero.", x);
}
}
Labels: rust