Golang: run all .go files within current directory

2019-02-01 00:59发布

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.

11条回答
小情绪 Triste *
2楼-- · 2019-02-01 01:34

You can run all .go files, excluding tests, using this bash construction:

go run $(ls -1 *.go | grep -v _test.go)
查看更多
萌系小妹纸
3楼-- · 2019-02-01 01:43

just use this

go run *.go 

it will work assuming u don't have any test files

查看更多
等我变得足够好
4楼-- · 2019-02-01 01:43

Here is my solution:

go run $(find . -name "*.go" -and -not -name "*_test.go" -maxdepth 1)

I use it with an alias to make it easy to run command line apps

alias gorun='go run $(find . -name "*.go" -and -not -name "*_test.go" -maxdepth 1)'

$ gorun param1 param2
查看更多
Bombasti
5楼-- · 2019-02-01 01:45

Unix related systems

go run *.go will be sufficient in most cases.

Continue to the below method if this causes errors.

Windows systems (and in other cases where go run *.go doesn't work)

Token expansion doesn't work in the windows command line and hence the above will not work and display an error. go run *.go may also not work in OSs in some cases due to current compiler limitations.

In these cases, use

go build && foo.exe

where foo.exe is the name of the .exe file produced. If perhaps you have no idea what the name of your executable is, first

go build and check the name of the .exe file produced. Afterwards, use the method that includes the file name.

These 2 methods will build and run all the .go files within your current directory with minimum fuss.

查看更多
冷血范
6楼-- · 2019-02-01 01:45

For peoples attempting to use go run combined with go generate a solution can be :

//go:generate sh -c "go run path/*.go"
查看更多
forever°为你锁心
7楼-- · 2019-02-01 01:48

The best way to do it is to run it like this:

go run !(*_test).go

It skips all your test files which is exactly what you need to avoid the error.

The other suggestion:

go build && ./<executable>

is a bit annoying. You have to delete the executable all the time to avoid being marked by git. You can put it in gitignore, of course, but I am lazy and this is an extra step.

查看更多
登录 后发表回答