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条回答
我想做一个坏孩纸
2楼-- · 2019-02-01 01:48

For window the following works: Open cmd and go to the path where your folder exists. Then type the following command and press Enter.

go build

after this one executable will be created. Then in the command prompt call the executable. If your executable name is Project.exe then type the following and press Enter:

Project.exe
查看更多
在下西门庆
3楼-- · 2019-02-01 01:51

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>
查看更多
【Aperson】
4楼-- · 2019-02-01 01:54

If i understand your question right, you need import other code as libraries.

Little example

./testing/main.go:

package main

import "fmt"
import L "testing/lib"

func main() {
    fmt.Println("Hello from main()")
    L.Somefunc()
}

./testing/lib/somelib.go:

package lib

import "fmt"

func Somefunc() {
    fmt.Println("Hello from Somefunc()")
    return
}

To launch - go run main.go

查看更多
疯言疯语
5楼-- · 2019-02-01 01:54

On Windows I usually just add a little test.bat to all my project directories:

go build
.\{project_name}.exe
go clean

Works well enough. Replace {project_name} with the name of your executable, of course. And once the executable finishes, the batch script moves on to the clean up.

查看更多
一纸荒年 Trace。
6楼-- · 2019-02-01 01:54
登录 后发表回答