Control structures

The if expression

#![allow(unused)]
fn main() {
   let number = 3;
   if number >= 3 {
       println!("It's a three");
   }
}

if...else

 fn main() {

   let number = 3;
   if number % 2 == 0 {
       println!("It's even");
   } else {
       println!("It is odd");
   }
 }

if..else if...

fn main() {
 let number = 18;
 
 if number % 3 == 0 && number % 5 == 0 {
    println!("Fizz buzz");
 } else if (number % 3 == 0)  {
    println!("Fizz");
 } else if (number % 5 == 0)  {
    println!("Buzz");
 } else {
   println!("{number}");
 }
}

In Rust, the if conditional construct is an expression. This means you can use it on the right side of an assignment operator to assign a value (i.e. the outcome of the if expression) to a variable.

Notice the absence of a semicolon after the "Even" and "Odd". You musn't include a semicolon in order for the if..else to remain an expression - inserting a semicolon will turn the if..else into a statement whose return value is ()

See Statements and expressions for more info.

For example,

  fn main() {
 
    let number = 3;
    let odd_or_even = if number % 2 == 0 { "Even" } else { "Odd" };
    
    println!("{} is {}", number, odd_or_even);
  }