Pub struct Foo(); pub struct Foo {}

It appears if we write pub struct Foo(), the ';' is mandatory.
It appears if we write pub struct Foo{}, we must not have a following ';'

This has tripped me up quite a few times.

Can someone explain what is going on with the parsing rules here?

1 Like

This is a piece of the legacy of C.

Broadly speaking, in most languages with C-ish syntax — braces for blocks, and so on — you will see two kinds of items/statements: those which end with a semicolon, and those which end with a set of braces with contents. There's not necessarily any syntactic necessity for the semicolon just, in each thing-in-a-list (whether it be items at the top level or statements in a function) you can expect that there will be either a semicolon after/between them, or a brace pair at the end. Usually not both, though it is usually legal to have extra semicolons in a statement context.

You can think of it as a little bit of conventional redundancy, making code easier to read even to people who don't know the language. (Syntactic redundancy also helps compilers give good error messages by recovering from errors; the compiler can assume that if it encounters a ; not inside {} then the programmer probably meant to end the item declaration, even if the syntax of it wasn't quite right.)

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.