为什么函数调用中的尾随逗号不是语法错误? [英] Why is a trailing comma in a function call not a syntax error?

查看:27
本文介绍了为什么函数调用中的尾随逗号不是语法错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这段代码会失败,因为逗号充当参数分隔符.没有第二个参数,foo 只接受一个参数.

I would expect this code to fail because the comma acts as a parameter separator. There is no second parameter and foo only accepts one parameter.

fn foo(_a: u8) {}

fn main() {
    foo(3, );
}

推荐答案

大多数语言都接受逗号分隔列表(如参数列表或元组或数组文字)中的尾随逗号.如果您将列表分成多行,这会很有帮助,例如

Most languages accept trailing commas in comma-separated lists like argument lists or tuple or array literals. This is helpful if you split up a list across multiple lines, e.g.

let a = [
    0,
    1,
    2,
    3,
];

由于所有行都以逗号终止,您可以轻松地在编辑器中重新排列行,并且差异在版本控制中看起来更清晰,尤其是在列表末尾添加更多条目时.这似乎不是允许尾随逗号的充分理由,但由于允许尾随逗号永远不会有什么坏处,因此作为一个基本原理就足够了.

Since all lines are terminated by a comma, you can easily reorder the lines in your editor, and diffs will look cleaner in version control, in particular when adding further entries to the end of the list. This may not seem like a strong reason to allow the trailing comma, but since allowing the traling comma never hurts, it is good enough as a rationale.

请注意,Rust 中的宏调用并不总是允许尾随逗号.

Note that macro invocations in Rust don't always allow the trailing comma.

随着时间的推移,其他语言对尾随逗号变得更加宽容.JavaScript 始终允许在数组文字中使用尾随逗号.他们允许 EcmaScript 5 中的对象文字和 EcmaScript 2017 中的函数参数列表使用它,而标准 JSON 仍然不允许尾随逗号.Python 直到最近才允许在 *args**kwargs 之后使用尾随逗号,但现在它们也被允许了.

Other languages have a history of becoming more permissive for the trailing comma over time. JavaScript always allowed a trailing comma in array literals. They allowed it for object literals in EcmaScript 5, and for function parameter lists in EcmaScript 2017, while standard JSON still does not allow trailing commas. Python did not allow a trailing comma after *args and **kwargs until recently, but now they are allowed as well.

这篇关于为什么函数调用中的尾随逗号不是语法错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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