为什么以及何时在块末尾使用逗号? [英] Why and when should a comma be used at the end of a block?

查看:60
本文介绍了为什么以及何时在块末尾使用逗号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Rust中,很多情况下代码块可以以逗号结尾或不以逗号结尾.例如:

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

enum WithoutComma 
{
    x,
    y
}

enum WithComma
{
    x,
    y,
}

还有其他带有 match 的示例,依此类推.似乎这两种变体都导致相同的结果.我唯一知道在其中添加或删除逗号会改变行为的情况是1元素元组声明(不是块):

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?

推荐答案

正如您所说,唯一需要尾随逗号的是1元组模式,类型和构造 let(x,):(类型,)=(1,).在其他任何地方,尾部逗号都是可选的,没有任何作用,但是出于以下几个原因而被允许使用

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:

  • 它使宏更容易:无需小心,不要在项目序列的最后插入逗号.
  • 它在扩展事物列表时使diffs更好,例如向

  • 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
}

给予

enum Foo {
    Bar,
    Baz
}

更改两行的

(即,像 git 这样的工具将显示已修改的 Bar 行以及插入的行),即使实际上只有第二行变化中任何有趣的东西.如果 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.

不需要它们(除了1元组),因为这很奇怪(IMO),例如

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,),)
}

(我想对于 enum / struct 声明来说看起来并不奇怪,但是仍然可以忽略它.)

(I guess it would look less strange for enum/struct declarations, but still, it's nice to be able to omit it.)

这篇关于为什么以及何时在块末尾使用逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆