Why does loop's `break` return expression end in a semi-colon?

In the Rust Book, returning values from loops example, we place a semi-colon ; after break counter * 2.

According to function bodies contain statements and expressions:

If you add a semicolon to the end of an expression, you turn it into a statement, which will then not return a value.

Why is break counter * 2; different and able to return a value from a loop such that the loop is an expression?

The break expression assign a value to the loop, not to the break expression itself. Without a semicolon it might look like this:

let a = if counter == 10 {
    break counter * 2
} else {
    10
};

playground

In this case, the break expression has the never type ! since it never returns a value (the program jumps elsewhere), so the if compiles as the never type is convertible into another other type, including integers.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.