Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

package

go

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?

like image 282
Mahdi Avatar asked Sep 02 '25 18:09

Mahdi


1 Answers

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.

like image 70
Caleb Avatar answered Sep 04 '25 10:09

Caleb