Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a comma in this Golang struct creation?

Tags:

struct

go

I have a struct:

type nameSorter struct {
    names []Name
    by    func(s1, s2 *Name) bool

Which is used in this method. What is going on with that comma? If I remove it there is a syntax error.

func (by By) Sort(names []Name) {
        sorter := &nameSorter{
            names: names,
            by:    by, //why does there have to be a comma here?
        }
        sort.Sort(sorter)

Also, the code below works perfectly fine and seems to be more clear.

func (by By) Sort(names []Name) {
    sorter := &nameSorter{names, by}
    sort.Sort(sorter)

For more context this code is part of a series of declarations for sorting of a custom type that looks like this:

By(lastNameSort).Sort(Names)
like image 496
John Avatar asked Apr 07 '17 09:04

John


2 Answers

This is how go works, and go is strict with things like comma and parentheses.

The good thing about this notion is that when adding or deleting a line, it does not affect other line. Suppose the last comma can be omitted, if you want to add a field after it, you have to add the comma back.

See this post: https://dave.cheney.net/2014/10/04/that-trailing-comma.

like image 87
cizixs Avatar answered Dec 06 '22 17:12

cizixs


From https://golang.org/doc/effective_go.html#semicolons:

the lexer uses a simple rule to insert semicolons automatically as it scans, so the input text is mostly free of them

In other words, the programmer is unburdened from using semicolons, but Go still uses them under the hood, prior to compilation.

Semicolons are inserted after the:

last token before a newline is an identifier (which includes words like int and float64), a basic literal such as a number or string constant, or one of the tokens break continue fallthrough return ++ -- ) }

Thus, without a comma, the lexer would insert a semicolon and cause a syntax error:

   &nameSorter{
       names: names,
       by:    by; // semicolon inserted after identifier, syntax error due to unclosed braces
   }
like image 42
jordanpg Avatar answered Dec 06 '22 19:12

jordanpg