Conditionals

Conditionals

if and else

if count > 0 {
    io::println("some")
} else if count == 0 {
    io::println("none")
} else {
    io::println("negative")
}

Braces are required and the condition is not parenthesized. The condition has to be a bool: there is no truthiness, so an optional or a number does not stand in for one.

if content.is_value() {
    // correct
}

if as an expression

An if can produce a value. When its result is used, the last statement of each branch is that branch's value:

let label = if count == 0 {
    "none"
} else {
    "some"
}

Two rules follow from how this is checked:

  • An else is required. Without one, a path exists that produces nothing, so the if stays a statement.
  • Every branch has to agree on a type. A branch that returns or exits instead of producing a value does not reach the merge, so an if whose branches mix the two is a statement rather than an expression.

The same if is a statement when its value is not used, so nothing has to be declared differently. Whether it is an expression depends on the position it appears in.