4

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?

kostix
  • 51,517
  • 14
  • 93
  • 176
Mahdi
  • 1,871
  • 2
  • 24
  • 41
  • I'll answer for Java as was originally tagged: Say a file exists at `/home/mahdix/projects/foo/src/main/com/stackoverflow/foo/Something.java`. How would `javac` know the package is `com.stackoverflow.foo` and not, say, `projects.foo.src.main.com.stackoverflow.foo`? – nanofarad Aug 12 '16 at 21:42
  • I say, It can be in both of packages depending on how you define your CLASSPATH. Still it can be inferred by the compiler. – Mahdi Aug 12 '16 at 21:58

1 Answers1

10

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.

Caleb
  • 9,272
  • 38
  • 30