具有方法/功能的Golang逗号[关闭]

Why are we allowed to put a comma at the end of a receiver in the method declaration, or in the parameter lists or the return lists. Like so:

func (ds *dasa,) yoooooolo (dsa dasa,) (dsaa dasa,) 

Why is this allowed? All those commas at the end?

Golang allows trailing commas after many declarations.

This was likely an explicit design choice by the designers of the language to be more permissive of irrelevant syntax errors; however, only they can explain their motivations.

func (f *Foo,) Bar(x, y int,) (int, error,) { //...
f.Bar(1, 2, 3,)
xs := []int{1, 2, 3,}

In fact, in some multiline literal declarations it requires trailing commas (presumably to simplify reordering of elements):

ys := []int{
  1,
  2, // <-- required comma.
}
m := map[string]int{
  "foo": 1,
  "bar": 2, // <-- required comma.
}

Note that the go fmt command automatically removes extraneous, optional trailing commas. You should always run that tool before building your code.

When you have a function with many arguments, you some times want to spread the function header over multiple lines like this:

func foo(
    int arg1,
    string arg2,
    []byte arg3,
    error arg4,
 ) {
    /* implementation goes here */
 }

The trailing comma allows for a more orthogonal way to write down this argument list.