5

Source file from Golang's stdlib

File's base directory: ast

Package specified in the file: ast_test ???

Package specified in all other files inside the same directory: ast

From golang.org: src contains Go source files organized into packages (one package per directory) ... By convention, packages are given lower case, single-word names; there should be no need for underscores or mixedCaps ... Another convention is that the package name is the base name of its source directory

How is it possible to have multiple packages (here 2) in one folder?

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
xged
  • 1,207
  • 1
  • 14
  • 20

1 Answers1

7

You find another example in src/pkg/go/ast/commentmap_test.go, with the comment:

// To avoid a cyclic dependency with go/parser, this file is in a separate package.

I suppose it allows for an othogonal command like:

go test

That will test parser features while avoiding for that test to be part of the same parser features (since it has been put in a separate package)

From go command man page:

Test files that declare a package with the suffix "_test" will be compiled as a separate package, and then linked and run with the main test binary.


This thread asked the question:

Now that the go tool requires each directory to be one package and doesn't allow to have files with different package names inside the same folder, how is the package keyword useful? It seems like a unnecessary repetition.

Is it required by the compiler or is there any plan to remove it?

The answers hinted at the fact that you can have more than one package in a folder:

The package declaration declares the name of the package.
The language Go doesn't know what a file or a directory is and the import path itself doesn't effect the actual name of the package that is being imported. So the only way the compiler knows what to call the package is the package declaration.

The language doesn't require separate packages to be in separate directories; it is a requirement of the go tool.
Another hypothetical implementation may not have this requirement.

Even this go tool requirement can be bypassed thanks to the "// +build" build tags.

For example, read misc/cgo/gmp or misc/cgo/stdio (some files include // +build ignore)

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • If Go isn't aware of the import path, how Go knows which package is to be imported under the import path if multiple packages are allowed? – xged Jul 14 '14 at 09:41
  • @xged because a `go build` will ignore by default test classes. Hence their names. – VonC Jul 14 '14 at 09:42
  • That makes sense. I need to understand tests, then. You can also include this quote from golang.org in your answer: "Test files that declare a package with the suffix "_test" will be compiled as a separate package, and then linked and run with the main test binary." – xged Jul 14 '14 at 09:57