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

醉酒当歌 提交于 2019-11-30 21:48:58
huon

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!