Using Go Run to Play Around with Go

Go comes with a run comand that allows you to quickly compile and run a program from practically anywhere. This is great if you want just want to play around with a feature or test a quick proof of concept without having to create the proper directory structure and build it there.

Let’s say you wanted to test reading command line arguments in an application. I’d normally start with a Hello World program just to make sure we’re setup. Make a directory anywhere, then create a file called main.go with the following contents:

package main

import (
	"fmt"
)

func main() {
	fmt.Println("Hello World")
}

Now try running it:

$ go run main.go
Hello World
$

Hopefully you get the same output. Now we can start messing around and get our command line args passed in.

The os package actually provides the command line arguments in a variable called Args so let’s just iterate over that:

package main

import (
	"fmt"
	"os"
)

func main() {
	args := os.Args

	for _, arg := range args {
		fmt.Println(arg)
	}
}

If you run it as before, you’ll see something like this:

$ go run main.go
/tmp/go-build445573655/b001/exe/main
$

What’s that? The first argument is actually always the application that was run. In this case, because we’re using go run, the program is compiled in a temporary location, as shown, and executed. So that is the output we expect. But let’s try passing in some other arguments, just to make sure:

$ go run main.go "These are" some arguments
/tmp/go-build674218610/b001/exe/main
These are
some
arguments
$

Looks good! Now integrate it in to your main program.

As a quick aside, you can also run go build to build you’re program, but things can get complicated when you start importing packages, at which point you should get a proper directory structure going. But give it a try:

$ go build main.go
$ ls
main  main.go
$

You’ll see a binary main was created. Try running that with some args and notice the value of the first line:

$ ./main "These are" some arguments
./main
These are
some
arguments
$

As you can see the binary being executed is the local one, otherwise though the behaviour is the same.

Leave a Reply

Your email address will not be published. Required fields are marked *