Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go file names starting with underscore character

Tags:

go

I wanted a specific file to appear at the top of my file list in my editor, so I prefixed it with _. This is how it looks:

mypkg
  _func.go
  a.go
  b.go

I know about Go's file naming conventions using _test, _unix etc, however, since _func does not match a specific architecture or is a test case, why doesn't it count as source file?

When I import this package, functions defined in this file are not available.

like image 870
Era Avatar asked Feb 12 '13 14:02

Era


2 Answers

Apparently, the underscore weights the same as the dot prefix at the beginning of files and is plainly ignored by the go build command. This however is not a decision of the go tool but of the go/build package in the standard library. You can see the responsible line here.

My guess is that temporary files are prefixed with underscores so that they are ignored by the build tool chain.

Edit: This comment documents the behavior. I cite:

// Import returns details about the Go package named by the import path,
// interpreting local import paths relative to the srcDir directory.
// If the path is a local import path naming a package that can be imported
// using a standard import path, the returned package will set p.ImportPath
// to that path.
//
// In the directory containing the package, .go, .c, .h, and .s files are
// considered part of the package except for:
//
//      - .go files in package documentation
//      - files starting with _ or . (likely editor temporary files)
//      - files with build constraints not satisfied by the context
//
// If an error occurs, Import returns a non-nil error and a non-nil
// *Package containing partial information.
//

And you can find this in user friendly form in the package docs of package go/build.

like image 160
nemo Avatar answered Sep 24 '22 15:09

nemo


I think I recall that _whatever is treated by the go tool in a similar fashion how dotfiles (.whatever) are hidden in the shell. Unfortunately, I cannot find any reference to where it is documented.

So, if my memory servers me correctly, you will have to rename the source file as it is not compatible with the Go build system in the case where you mean to have such _file.go considered a part of some package.

The intent for this behavior is probably to allow for easy creating temporary and non-conflicting files for tools like CGO etc.

like image 33
zzzz Avatar answered Sep 21 '22 15:09

zzzz