3

Is there a difference between panic!("blah"); and panic("blah")?

As I understand things, semicolons differentiate between statements and expressions1. Put differently, the lack of a semicolon shows that a value is expected as a result of the expression2.

This is pretty straight forward in most cases, but panic! causes the current thread to terminate. The program will never return from panic! and so the result of the expression is meaningless, right?

Will the expression panic!("blah") ever behave differently than the statement panic!("blah);?

Increasingly Idiotic
  • 5,700
  • 5
  • 35
  • 73

1 Answers1

9

In 99% of the cases, there's no meaningful difference. I'd just let rustfmt do whatever it wants to do and not think about it.

Is there any reason to put a semicolon after panic?

Yes. If you decide to stick a panic in the middle of some code for some quick-and-dirty debugging, if you don't add the semicolon you get a syntax error:

fn main() {
    // ... some code ...

    // We add a quick panic for some reason
    panic!("oops")

    // ... some code ...
    1;
}
error: expected one of `.`, `;`, `?`, `}`, or an operator, found `1`
 --> src/main.rs:8:5
  |
5 |     panic!("oops")
  |                   - expected one of `.`, `;`, `?`, `}`, or an operator here
...
8 |     1;
  |     ^ unexpected token

With the semicolon, you will be able to compile with some warnings about unreachable code.

There's also the implicit question:

Is there any reason to not put a semicolon after panic?

The one I can think of is when you are writing your own divergent function:

fn crash_override() -> ! {
    panic!("oops")
}

It's not needed, but it might appear more obvious to a reader that the never type is being "returned" from panic! in this case.

Is there a difference between panic!("blah"); and panic("blah")?

Yes, the former is a statement, the latter is an expression.

but panic! causes the current thread to terminate.

That's the default behavior, yes, but it's not the only one. When panic = abort is not enabled, you can catch panics if you need to.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • Thanks for the very comprehensive answer! Just for clarification, the [second answer](https://stackoverflow.com/a/27423473/9614249) on the question you linked is now outdated and incorrect, right? – Increasingly Idiotic May 30 '18 at 17:16
  • 1
    @IncreasinglyIdiotic yeah. I just edited it to note that. – Shepmaster May 30 '18 at 17:20