Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a trailing comma in a function call not a syntax error?

Tags:

rust

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, );
}
like image 298
hellow Avatar asked Dec 07 '18 15:12

hellow


1 Answers

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.

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

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.

like image 176
Sven Marnach Avatar answered Oct 02 '22 19:10

Sven Marnach