fresh
fresh

Reputation: 411

Is the final comma in Rust struct definitions necessary?

Consider the following code:

struct User {
    user: String,
    email: String,
}

The compiler doesn't complain about it. The trailing comma after the email field struck me as odd, so I tried this:

struct User {
    user: String,
    email: String // no comma
}

The compiler still doesn't complain. Is there a difference or are the two scenarios completely equivalent?

Upvotes: 14

Views: 2062

Answers (3)

mnemotronic
mnemotronic

Reputation: 1026

Adding a trailing comma to make it easier to add a field in the future goes against the XP "YAGNI" You Ain't Gonna Need It principal. Planning for some future enhancement is a waste of time because by the time "the future" arrives the requirements for that enhancement will have changed from what I, in my infinitely wise foresight, thought they would be way back when. On the other hand I can see the comma being useful to make "diff" output less "noisy".

According to people on this rust-lang.org thread, the trailing comma on the last field makes automatic code generation easier since it doesn't have to deal with the "is this the last field?" question. Also something about macro generation that I don't understand at this point in my oxidation education. The comma also makes it easier to rearrange the order of fields in the struct, but again, planning for the future should wait for the future.

Upvotes: -2

Sébastien Renauld
Sébastien Renauld

Reputation: 19672

The last comma is purely optional in struct definitions. This is pure convenience; it allows you to leave that trailing comma in, so you do not have to go back and modify a line if you add an additional field, delete a field or change their order.

It also, coincidentally, makes code generation from macros easier, as your codegen macro no longer has to care about keeping track of whether you are on the last generated field.

The one time when you'll see a trailing comma being mandatory is in macros like the diesel table! macro, and the reason is down to the macro invocation structure chosen by the diesel developers.

Upvotes: 21

edwardw
edwardw

Reputation: 14002

Have to say that you are an acute observer. They are equivalent according to rust reference:

StructFields :

StructField (, StructField)* ,?

It is that way for convenience reason: be able to add or remove lines without touching previous ones.

Here's a counter-example. In languages that don't have such convenience, people may choose to format the code in unusual ways to achieve virtually the same, such as:

data Person = Person
    { firstName :: String
    , lastName  :: String
    , age       :: Int
    } 

I like an optional trailing comma more.

Upvotes: 4

Related Questions