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

后端 未结 1 402
一向
一向 2021-01-05 15:42

There many cases in Rust when a block of code can end with or without comma. For example:

enum WithoutComma 
{
    x,
    y
}

or

         


        
相关标签:
1条回答
  • 2021-01-05 16:21

    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.)

    0 讨论(0)
提交回复
热议问题