How to run all .go files within current directory through the command line (multi file package)

dk123 picture dk123 · May 16, 2014 · Viewed 60.4k times · Source

I'm a newcomer to Go. I extremely like the language, but I quickly realised that I needed to start dividing my files due to an increase in program size.

go run main.go (with main.go having been the file with my main() function)

didn't work and I hit a barrier for a while, because I had no clue how to get my program working.

Some quick searching lead me to the answer of

go run main.go other.go ..

where by typing all the files that my package main consists of, I could get the programming running. However, this is utterly cumbersome and frustrating to do each time.

I write the following self-answered question in order to prevent others like myself who may again hit this barrier.

Answer

Rob Napier picture Rob Napier · May 16, 2014

As Nate Finch notes:

Go run is ... really only meant to be used on very small programs, which generally only need a single file.

Even on unix, go run *.go is often not correct. In any project with unit tests (and every project should have unit tests), this will give the error:

go run: cannot run *_test.go files (something_test.go)

It will also ignore build restrictions, so _windows.go files will be compiled (or attempted to be compiled) on Unix, which is not what you want.

There has been a bit of discussion of making go run work like the rest of the go commands, and there's an open CL for it (5164). It's currently under consideration for Go 1.4. In the meantime, the recommended solution on all platforms is:

go build && ./<executable>