Search code examples
gopackage-name

Golang: "package ast_test" underscore test


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?


Solution

  • 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)