英文:
Why is there a comma in this Golang struct creation?
问题
我有一个结构体:
type nameSorter struct {
names []Name
by func(s1, s2 *Name) bool
}
它在这个方法中被使用。那个逗号是什么意思?如果我移除它,就会出现语法错误。
func (by By) Sort(names []Name) {
sorter := &nameSorter{
names: names,
by: by, //为什么这里必须有一个逗号?
}
sort.Sort(sorter)
}
此外,下面的代码运行得很好,而且似乎更清晰。
func (by By) Sort(names []Name) {
sorter := &nameSorter{names, by}
sort.Sort(sorter)
}
为了更好地理解,这段代码是用于对一个自定义类型进行排序的一系列声明的一部分,该类型的结构如下:
By(lastNameSort).Sort(Names)
英文:
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)
答案1
得分: 17
这是 Go 语言的工作方式,Go 对于像逗号和括号这样的东西非常严格。
这个概念的好处是,当添加或删除一行时,不会影响其他行。假设最后一个逗号可以省略,如果你想在它后面添加一个字段,你必须把逗号加回来。
参考这篇文章:https://dave.cheney.net/2014/10/04/that-trailing-comma。
英文:
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.
答案2
得分: 5
从https://golang.org/doc/effective_go.html#semicolons:
词法分析器在扫描过程中使用一个简单的规则自动插入分号,因此输入文本大部分是没有分号的。
换句话说,程序员不需要使用分号,但是Go在编译之前仍然会在内部使用它们。
分号会插入在以下情况之后:
换行符之前的最后一个标识符(包括int和float64等单词)、基本字面量(如数字或字符串常量)或者以下标记之一:
break continue fallthrough return ++ -- ) }
因此,如果没有逗号,词法分析器会插入一个分号并导致语法错误:
&nameSorter{
names: names,
by: by; // 在标识符之后插入分号,由于未关闭的大括号导致语法错误
}
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论