There many cases in Rust when a block of code can end with or without comma. For example:
enum WithoutComma
{
x,
y
}
or
enum WithComma
{
x,
y,
}
There are also other examples with match
, etc. It seems that both variants lead to the same result. The only case I know where adding or removing a comma changes behaviour is the 1-element tuple declaration (which isn't a block):
let just_int = (5);
let tuple = (5,);
Why can one use a comma or not at the end of a block? Why is there such dualism in thelanguage and what are the reasons for it?
As you say, the only time a trailing comma is required is the 1-tuple pattern, type and construction let (x,): (Type,) = (1,)
. Everywhere else, trailing commas are optional, have no effect, but are allowed for a few reasons:
it makes diffs nicer when extending a list of things, e.g. adding a variant to
enum Foo {
Bar
}
gives
enum Foo {
Bar,
Baz
}
which is changing two lines (i.e. tools like git
will display the Bar
line as modified, as well as the inserted line), even though only the second actually had anything interesting in the change. If Bar
started out with a trailing comma, then inserting Baz,
after it is fine, with only one line changed.
They're not required (other than the 1-tuple) because that would be fairly strange (IMO), e.g.
fn foo(x: u16,) -> (u8, u8,) {
(bar(x,), baz(x,),)
}
(I guess it would look less strange for enum
/struct
declarations, but still, it's nice to be able to omit it.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With