Volker Stolz
Volker Stolz

Reputation: 7402

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?

Upvotes: 5

Views: 2644

Answers (2)

Volker Stolz
Volker Stolz

Reputation: 7402

Looking at my problem again, I have to find out if I'm ever going to need several input files. If not, I might get away with just reading from Stdin instead of opening a file.

Upvotes: 0

Caleb
Caleb

Reputation: 9458

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

Upvotes: 6

Related Questions