Lesson 5 - If Statements

Rust uses if, else if, and else for decision making.

For if statements, Rust will check the condition in the if statement, and if it evaluates to true, the block in the condition will run.

If an else block is added, the else block will run if the first if condition is false.

To check several conditions, use the else if block.

let score = 85;

if score >= 90 {
  println!("A"); 
}
else if score >= 80 { 
  println!("B"); 
} 
else if score >= 70 { 
  println!("C"); 
} 
else { 
  println!("Needs improvement"); 
}

Rust checks the conditions from top to bottom.

Once one condition is true, that block runs.

Rust's if expressions can also produce values.

let age = 16; 

let status = if age >= 18 { 
  "Adult" 
} 
else { 
  "Minor" 
}; 

println!("{}", status);

The value of status becomes "Minor".