为什么在 go lang 中对关键字进行严格的代码格式

why strict code format on keywords in go lang

正如每个开始使用 Go 的新程序员一样,您首先想到的是严格的代码格式。 意思是:

//Valid
func foo(){
}

//Invalid
func foo()
{
}

同样适用于 if-else,else 应该在 if 结束的同一行,例如:

//Valid
if{
}else{
}

//Invalid
if{
}
else{
}

我们得到以下错误:

syntax error: unexpected else, expecting }

我已经检查了规范 spec,但找不到原因。

我得到的唯一解释是强制性

任何人都可以向我们解释为什么这是强制性的,这有什么原因吗?如果有的话。

更新
我想我已经提到过 "I know lang say so",问题是为什么? 为什么要花这么大的时间让它成为编译时错误,如果我们不这样做会带来什么问题?

Go 插入一个;在以某些标记(包括 })结尾的行的末尾。 由于 if {...} else {...} 是单个语句,您不能在第一个右花括号(即 } 之后在中间放置分号,因此要求将 } else { 放在一行上强制性的。

我希望它能回答你的问题。

语言就是这样设计的,原因在常见问题解答中有所概述。

https://golang.org/doc/faq

为什么有大括号没有分号?为什么我不能把左大括号放在下一行?

o uses brace brackets for statement grouping, a syntax familiar to programmers who have worked with any language in the C family. Semicolons, however, are for parsers, not for people, and we wanted to eliminate them as much as possible. To achieve this goal, Go borrows a trick from BCPL: the semicolons that separate statements are in the formal grammar but are injected automatically, without lookahead, by the lexer at the end of any line that could be the end of a statement. This works very well in practice but has the effect that it forces a brace style. For instance, the opening brace of a function cannot appear on a line by itself.

Some have argued that the lexer should do lookahead to permit the brace to live on the next line. We disagree. Since Go code is meant to be formatted automatically by gofmt, some style must be chosen. That style may differ from what you've used in C or Java, but Go is a different language and gofmt's style is as good as any other. More important—much more important—the advantages of a single, programmatically mandated format for all Go programs greatly outweigh any perceived disadvantages of the particular style. Note too that Go's style means that an interactive implementation of Go can use the standard syntax one line at a time without special rules.