Title here
Summary here
Branching with if
and else
in Rust is straightforward.
fn main() {
// Here's a basic example.
if 7 % 2 == 0 {
println!("7 is even");
} else {
println!("7 is odd");
}
// You can have an `if` statement without an else.
if 8 % 4 == 0 {
println!("8 is divisible by 4");
}
// Logical operators like `&&` and `||` are often
// useful in conditions.
if 8 % 2 == 0 || 7 % 2 == 0 {
println!("either 8 or 7 are even");
}
// A statement can precede conditionals; any variables
// declared in this statement are available in the current
// and all subsequent branches.
let num = 9;
if num < 0 {
println!("{} is negative", num);
} else if num < 10 {
println!("{} has 1 digit", num);
} else {
println!("{} has multiple digits", num);
}
}
To run the program:
$ rustc if_else.rs
$ ./if_else
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit
Note that you don’t need parentheses around conditions in Rust, but the braces are required.
Rust, like many modern languages, does not have a ternary operator. Instead, you can use the if
expression, which can return a value:
let x = if condition { value1 } else { value2 };
This is more flexible and consistent with the rest of the language than a dedicated ternary operator.