Passing a .go file as an optional argument to `go run`

For a quick hack, I prefer to use it go run prog.go ...instead of creating an executable file first. However, the program I'm working on should take another go file as an argument. As a result, the go runcompiled binary behaves differently:

go run prog.go foo.go

will try to execute both go files whereas

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

it will correctly take my file as input (assumed behavior). Now I can pass additional type arguments go run ... -- foo.go, but due to the --file position is different from os.Argsbetween go run prog.go -- foo.goand ./prog foo.go. Any simple solution? I would like to avoid full flag handling. Should I just give up and stick to the compiled version?

+4
source share
2 answers

It's impossible. Here is 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 installinstead go build. This will put your executable in your folder $GOPATH/bin(I don't like having a binary in the same folder, because sometimes I accidentally add it to git). But it really is not much different.

Another option you might want to consider is rerun. It will automatically recompile and run your code every time the file changes:

rerun path/to/your/project foo.go
+3
source

Looking at my problem again, I have to find out when I need some input files. If not, I can leave just by reading from Stdininstead of opening the file.

0
source

All Articles