ProgramGuru

Running Go Programs

Start with Running Go Programs

Use go run when you want to compile and execute a program during development. Go builds a temporary executable and runs it for you.

What you’ll learn

  • Run a Go file and a package.
  • Explain the behavior of go run.
  • Know when an explicit filename differs from a package build.

Understand the idea

In a directory containing a go.mod file and main.go, go run . runs the package in the current directory. For a simple standalone file, go run main.go also works. The dot means the current package, not the file literally named ..

A directory can contain several Go files belonging to the same package. Running the package includes those files; running one explicitly named file includes only the named source files.

Tools, syntax and practical notes

Commands to try

go mod init example.com/steps
go run main.go
go run .

Initialize the module once, after opening your project directory. Do not reinitialize it on every run.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func main() {
	for step := 1; step <= 3; step++ {
		fmt.Println("Step", step)
	}
}

Output

Step 1
Step 2
Step 3

Trace what the program does

The runner compiles the current program and executes main(). The loop prints three lines, then the process finishes. Changing the source and running the command again creates a fresh execution.

Avoid common mistakes

  • go run is not a persistent web server or file watcher; it starts the program anew each time.
  • go run main.go does not automatically include sibling Go source files.

Try it yourself

Run the example once with go run main.go and once with go run . from a module directory. Compare results.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What does the dot mean in go run .?
Choose one answer. You can try again.

Answer and explanation

The current directory’s package

Correct. The runner compiles the current program and executes main().

What you should remember

You have practiced Running Go Programs in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Building Go Programs →