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

标签 go goland

正如每个从 Go 1st 开始的新程序员所认为的那样,严格的代码格式。
方法:

//Valid
func foo(){
}

//Invalid
func foo()
{
}
if-else 也是如此else 应该在 if 结束的同一行中,例如:
//Valid
if{
}else{
}

//Invalid
if{
}
else{
}

我们得到以下错误:
syntax error: unexpected else, expecting }

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

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

谁能解释一下为什么这是强制性的,这有什么理由吗?如果有的话。

更新
我想我已经提到过“我知道朗这么说”,问题是为什么?
为什么要走这么长的路让它编译时错误,如果我们不这样做会带来什么问题?

最佳答案

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

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.

关于go - 为什么在 go lang 中对关键字进行严格的代码格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59839784/

相关文章:

database - SetMaxOpenConns 和 SetMaxIdleConns

go - 如何使用未导出结构体的函数

google-app-engine - http.DefaultTransport 和 http.DefaultClient 在 AppEngine 中不可用,但库使用它们

debugging - 戈格兰 : debugging has redundant parameter '--'

amazon-web-services - 安全地提供来自 S3 的内容

go - 使用 `encoding/json` 的默认值 golang 结构?

go - 是否可以使用GoLang调试预构建的go可执行文件?

debugging - GoGland 中的调试器配置

go - 如何在包内调用未导出的函数?

go - GoLand找不到引用: “Unresolved reference ' NewRGBA' ”