Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why and when should a comma be used at the end of a block?

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?

like image 593
Arsenii Fomin Avatar asked Jan 27 '15 05:01

Arsenii Fomin


1 Answers

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 macros easier: no need to be careful to not insert a comma at the very end of a sequence of items.
  • 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.)

like image 150
huon Avatar answered Sep 18 '22 03:09

huon