可以由编译器推断“ package”关键字的目的是什么? [重复]

This question already has an answer here:

All of the Go source files inside directory x have package name x declared on top. I know this is not mandatory but doing otherwise will make things unnecessarily complex. So why the go compiler does not infer the package name from directory name?

This exists in almost many other languages like Java or C# where you are forced to declare what can be easily calculated at compile time.

What is the rationale?

</div>

Without package you wouldn't be able to distinguish between main programs and libraries.

Furthermore, according to the language specification, the language does not require a package to be identical with a directory:

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

And in practice some packages have different names than their import paths:

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

Consider github.com/google/go-gcm which has package gcm in its files. Projects that use this library will have:

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

And then call things like this:

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

This is particularly common with - because you can't use it in an identifier.