当编译器可以推断出 'package' 关键字时,它的用途是什么?

What is purpose of 'package' keyword when it can be inferred by compiler?

目录 x 中的所有 Go 源文件都在顶部声明了包名称 x。我知道这不是强制性的,但否则会使事情变得不必要的复杂。那么为什么 go 编译器不从目录名中推断出包名呢?

这几乎存在于许多其他语言中,例如 Java 或 C#,在这些语言中您被迫声明可以在编译时轻松计算的内容。

理由是什么?

没有package你将无法区分主程序和库。

此外,根据language specification,该语言不要求包与目录相同:

An implementation may require that all source files for a package inhabit the same directory.

实际上有些包的名称与其导入路径不同:

If the PackageName is omitted, it defaults to the identifier specified in the package clause of the imported package.

考虑 github.com/google/go-gcm,它的文件中有 package gcm。使用此库的项目将具有:

import "github.com/google/go-gcm"

然后这样调用:

res, err := gcm.SendHttp(APIKey, notification)

这在 - 中尤为常见,因为您不能在标识符中使用它。