Intro

The if conditional block in Rust behaves similarly to other languages. In Rust, if blocks act as an expression and the resulting branch can be assigned to a variable.

rust
// Example if block.
if "stuff" == "things"  {
    println!("equal") // Considered a tail-expression so semi-colon not required.
} else if 42 < 69 {
    println!("the answer")
} else {
    println!("lol")
} // terminating semi-colon optional when not returning an expression.

The resulting expression of an if branch can be assigned to a variable with the let keyword.

rust
// Assign resulting expression to `the_answer` variable.
let the_answer = if 42 > 69 {
    "the answer" // Considered a tail-expression so semi-colon not required.
} else {
    "lol"
}; // terminating semi-colon is required when returning an expression.

Considerations

  • The condition MUST evaluate to a boolean
  • Semi-colons at the end of the branches are not required as they are considered tail-expressions.
  • When an if block returns a value:
    • A terminating semi-colon on the if block is required.
    • All branches must return the same type.
# rust