Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a .go-file as additional argument to `go run`

For quick hacking, I prefer to use go run prog.go ... instead of building the executable first. However, the program I am working on should take another go-file as an argument. As a consequence, go run and the compiled binary behave differently:

go run prog.go foo.go

will try to execute both go-files, whereas

go build prog.go && ./prog foo.go

will correctly take my file as input (the intended behaviour). Now I can pass additional args like this go run ... -- foo.go, but then because of the -- the position of the file differs in os.Args between the go run prog.go -- foo.go and the ./prog foo.go. Any easy solution? I'd like to avoid having full flag-processing. Should I just give up and stick to the compiled version?

like image 283
Volker Stolz Avatar asked May 07 '15 13:05

Volker Stolz


1 Answers

It's not possible. Here's the source for the command:

for i < len(args) && strings.HasSuffix(args[i], ".go") {
    i++
}
files, cmdArgs := args[:i], args[i:]

You can use go install instead of go build. That will put your executable in your $GOPATH/bin folder (I don't like having the binary in the same folder because sometimes I accidentally add it to git). But it's really not much different.

Another option you might want to consider is rerun. It will automatically recompile and run your code whenever you change a file:

rerun path/to/your/project foo.go
like image 107
Caleb Avatar answered Sep 20 '22 12:09

Caleb