Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does "if return" compile in 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading