Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "if return" compile in Rust?

Tags:

rust

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?

like image 225
aedm Avatar asked Jan 18 '26 18:01

aedm


2 Answers

It is for the same reason the following code compiles:

fn create_string() -> String {
    std::process::exit(0);
}

The body of the function above does never return a String value, however, since std::process::exit() is a divergent function (i.e., its return type is !), it results in valid code: The control flow will never reach the point where a String value has to be produced.

The same applies to panic!(). The following code, which replaces your return with panic!(), also compiles for the same reason:

fn main() {
    if panic!() { print!("1") } {}
}
like image 101
ネロク・ゴ Avatar answered Jan 21 '26 08:01

ネロク・ゴ


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
like image 36
maxy Avatar answered Jan 21 '26 09:01

maxy