I found some strange Rust code in dtolnay’s mind-bending Rust quiz. Apparently, this is a valid Rust program (playground):
fn main() {
if return { print!("1") } {}
}
According to the Rust docs:
The syntax of an if expression is a condition operand, followed by a consequent block, any number of else if conditions and blocks, and an optional trailing else block. The condition operands must have the boolean type.
To me it means that the return statement must somehow evaluate as a boolean, otherwise the code wouldn’t compile. But that explanation seems outlandish, and I suspect there must be something else going on.
So why does if return compile at all?
>Solution :
You’re looking for the never type, which is the result of the return expression.
And while it compiles, it does generate a warning:
warning: unreachable block in `if` or `while` expression
|
2 | if return { print!("1") } {}
| ---------------------- ^^ unreachable block in `if` or `while` expression
| |
| any code following this expression is unreachable