Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I "go run" a project with multiple files in the main package?

Tags:

package

go

People also ask

Can a Go package have multiple files?

As Wombologist mentioned, you can split different files under the same package without problem, assuming they share the same package definition.

Can we define two Go programs with a main method within a package?

Yes, thats totally fine. For go build or go run you then provide the path to the main file you want to compile.

How do I run a Go package?

Add the Go install directory to your system's shell path. That way, you'll be able to run your program's executable without specifying where the executable is. Once you've updated the shell path, run the go install command to compile and install the package. Run your application by simply typing its name.


Update 26th July 2019 (for go >=1.11)

go run .

Will work on windows as well.

Original answer (for non windows environments)

The code actually works. The problem was that instead of running go run main.go I should run:

go run *.go

Update August 2018, with Go 1.11, a section "Run" states:

The go run command now allows a single import path, a directory name or a pattern matching a single package.
This allows go run pkg or go run dir, most importantly go run .


Original answer Jan. 2015

As mentioned in "How to compile Go program consisting of multiple files?", go run expects a list of files, since it "compiles and runs the main package comprising the named Go source files".
So you certainly can split your main package in several files with go run.

That differs from go build/go install which expect package names (and not go filenames).
A simple go build would produce an executable named after the parent folder.

Note that, as illustrated by this thread, a go run *.go wouldn't work in a Windows CMD session, since the shell doesn't do wildcard expansion.


In my opinion, the best answer to this question is hidden in the comments to the top answer.

Just run this:

go run .

This will run all the files in main package, but will not give an error message like

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

Kudos to @BarthesSimpson


As mentioned, you can say go run *.go but for Windows you can just list the script files (since *.go won't work) - go run main.go other.go third.go


The first method to do so will be to run

go run *.go

The another method is to generate an exe file

go build

Then run that .exe file

./filename.exe