Why does the "go run" command fail to find a second file in the main package?
I want to share some useful resources here for reference, which I learned from another similar deleted post. It looks like a simple command but yet you may not fully know it.
- If you're supplying a list of source files to
go run
, you are creating a single synthesized package, and build constraints are ignored. So instead of listing go files, it's better to use an import path or a file system path, e.g.go run .
. Check it withgo help packages
:
As a special case, if the package list is a list of .go files from a
single directory, the command is applied to a single synthesized
package made up of exactly those files, ignoring any build constraints
in those files and ignoring any other files in the directory.
- The executable target is named after the first source file. Check it in implementations for
go run
command here(on line 80 and 125) and here(on line 2506):
// GoFilesPackage creates a package for building a collection of Go files
// (typically named on the command line). The target is named p.a for
// package p or named after the first Go file for package main.
func GoFilesPackage(ctx context.Context, gofiles []string) *Package {
...
- To avoid potential problems during package initialization, you're encouraged to supply the list of go files in lexical file name order. Check it in the specs:
The declaration order of variables declared in multiple files is determined by the order in which the files are presented to the compiler: Variables declared in the first file are declared before any of the variables declared in the second file, and so on.
...
A package with no imports is initialized by assigning initial values to all its package-level variables followed by calling all init functions in the order they appear in the source, possibly in multiple files, as presented to the compiler.
...
To ensure reproducible initialization behavior, build systems are encouraged to present multiple files belonging to the same package in lexical file name order to a compiler.
- There are historical discussions about
go run
, check it here and here.
Try providing all relevant files to go run
$ go help run
usage: go run [build flags] [-exec xprog] gofiles... [arguments...]
Run compiles and runs the main package comprising the named Go source files.
A Go source file is defined to be a file ending in a literal ".go" suffix.