Level: BeginnerGo Programs

How to Run a Go Program: go run, go build and go install

Updated 15 min read
Run a Go Program featured image: terminal showing go run and go build

To run a Go program, you use one of three commands: go run, go build or go install. Each one compiles your code, but each gives you a different result. In this post, you will learn all three, plus how to pass arguments, read input, use exit codes and fix the errors beginners see most.

This is the second post in our Go programs series. If Go is not on your computer yet, start with the Go installation guide for Windows, macOS and Linux. At the end, you will find interview questions with small programs and their real output.

What Does It Mean to Run a Go Program?

Go is a compiled language. So, before your code can run, the compiler turns your .go files into a machine code file called a binary. Then your computer runs that binary.

Here is a simple way to picture it. Your source code is a recipe written in English. The compiler is a cook who turns the recipe into a finished dish. Running the program is serving that dish, and you can serve it again without cooking it twice.

The Parts of Every Go Program

Before you run a Go program, let’s look at a tiny one. Every runnable Go program needs the same three parts.

package main // this file is a program, not a library

import "fmt" // fmt is the standard package for printing

// main is the first function Go runs
func main() {
    fmt.Println("Hello from Go!") // Println prints the text and a new line
}
Hello from Go!
  • package main tells Go this code is a program, not a library.
  • import "fmt" loads the standard package for printing.
  • func main() is the entry point. The program starts here and stops when it returns.

Easy Example: Code Runs from Top to Bottom

When you run a Go program, the lines inside main run one by one, from top to bottom. This small program makes that order easy to see.

package main

import "fmt"

// main prints three steps in order
func main() {
    // := creates a new variable and gives it a value
    name := "Asha"

    fmt.Println("Step 1: the program starts")
    fmt.Println("Step 2: hello,", name)
    fmt.Println("Step 3: the program ends")
}
Step 1: the program starts
Step 2: hello, Asha
Step 3: the program ends

First, Go stores “Asha” in the variable name. Then it runs each Println line in the order you wrote them. When main reaches its last line, the program stops.

Set Up a Folder to Run a Go Program

Modern Go uses modules. A module is a folder with a go.mod file that names your project. You create it once per project with go mod init.

mkdir hello
cd hello
go mod init example.com/hello

After you add main.go, the folder looks like this. The go.mod file is small and Go writes it for you.

hello/
    go.mod
    main.go

You will learn more about modules in our Go modules and packages guide. For now, just remember that every project starts with go mod init.

Three Ways to Run a Go Program

All three commands compile your code. The difference is where the binary ends up, and whether Go runs it for you.

Run a Go program diagram showing go run, go build and go install flows
go run builds into a temporary folder and runs the program, go build saves a binary in your folder, and go install saves it in GOBIN.

Method 1: Run a Go Program with go run

go run compiles the code into a temporary folder, runs it, and then cleans up. It is the fastest way to run a Go program while you are learning. You can pass one file or the whole package.

go run main.go
go run .
Hello from Go!
Hello from Go!

Use go run . as your habit. The dot means “the package in this folder”, so Go includes every .go file in it.

Method 2: Build First, Then Run a Go Program

go build compiles the code and saves the binary in the current folder. The file is named after your module, so here it is hello on Linux and macOS, or hello.exe on Windows. Then you run the file yourself.

go build
./hello
Hello from Go!

On Windows, run .\hello.exe instead. You can also choose the file name with the -o flag, for example go build -o bin/app ..

Method 3: Install and Run a Go Program Anywhere

go install builds the binary and moves it to your GOBIN folder, which is usually $HOME/go/bin. If that folder is on your PATH, you can run the program from any folder by name.

go install
hello
Hello from Go!

This is how Go developers install command line tools. For example, go install golang.org/x/tools/cmd/goimports@latest installs a popular formatter.

go run vs go build vs go install

The table below compares the three ways to run a Go program side by side.

Featurego rungo buildgo install
Compiles codeYesYesYes
Runs the programYes, right awayNoNo
Keeps a binaryNo, temporary onlyYes, in current folderYes, in GOBIN
Best forLearning and quick testsShipping or testing a binaryInstalling tools
Speed on rerunsUses the build cacheUses the build cacheUses the build cache
Run a Go program comparison of go run, go build and go install
Pick go run while coding, go build to ship a file, and go install to use a tool everywhere.

In short, use go run while you code, go build when you need a file to ship, and go install when you want a command on your PATH.

Run a Go Program with Many Files

Real programs have more than one file. Let’s split our greeting into a second file, greet.go, in the same folder.

// greet.go
package main

// greet builds a friendly message for the given name
func greet(name string) string {
    return "Hello, " + name + "!" // + joins strings together
}
// main.go
package main

import "fmt"

// main calls greet, which lives in the other file
func main() {
    fmt.Println(greet("Asha"))
}

Now watch what happens with each command. The first one fails, and the second one works.

$ go run main.go
# command-line-arguments
./main.go:8:17: undefined: greet

$ go run .
Hello, Asha!

The reason is simple. go run main.go only compiles the one file you named, so Go never sees greet.go. On the other hand, go run . compiles the whole package, so both files are included.

Pass Arguments When You Run a Go Program

Many programs need input from the command line. Go stores these values in os.Args. The first item is always the program path, and your arguments come after it.

Easy Example: Greet a Name from the Command Line

Let’s start with one word. This program reads a name after the program name and greets it.

package main

import (
    "fmt"
    "os" // os gives access to the command line words
)

// main greets the name typed after the program name
func main() {
    // len(os.Args) counts the items; item 0 is the program path
    if len(os.Args) < 2 {
        fmt.Println("Please type a name after the program name.")
        return // stop main early
    }

    name := os.Args[1] // the first word you typed
    fmt.Println("Hello,", name)
}

Run it with one word after the dot.

go run . Asha
Hello, Asha

First, the program checks that you typed at least one word. If you did not, it prints a hint and stops. Otherwise, it reads os.Args[1] and prints the greeting.

Run a Go Program with Many Arguments

Now let’s print every word you pass, with its position.

package main

import (
    "fmt"
    "os"
)

// main prints how many items os.Args holds, then each argument
func main() {
    fmt.Println("Total items:", len(os.Args))

    // os.Args[1:] skips item 0, the program path
    // range gives the position (i) and the value (arg) of each item
    for i, arg := range os.Args[1:] {
        fmt.Printf("Arg %d: %s\n", i+1, arg) // %d prints a number, %s prints text
    }
}
go run . apple banana
Total items: 3
Arg 1: apple
Arg 2: banana

So the program sees three items, the path plus two words. The loop starts at the first real argument, and i+1 makes the count start at 1 instead of 0. For named options like -port=8080, use the flag package from our Go command line tools guide.

Read Input and Return Exit Codes

Programs often read from the keyboard and tell the system if they worked. This example reads a name and exits with code 1 when the name is empty.

package main

import (
    "bufio"   // bufio reads input in bigger pieces, such as a full line
    "fmt"
    "os"
    "strings" // strings has helpers for text
)

// main reads a name and exits with code 1 if it is empty
func main() {
    fmt.Print("Your name: ") // Print does not add a new line

    // Step 1: read one full line from the keyboard (os.Stdin)
    reader := bufio.NewReader(os.Stdin)
    line, _ := reader.ReadString('\n') // _ ignores the second value (the error)

    // Step 2: remove spaces and the new line at the end
    name := strings.TrimSpace(line)

    // Step 3: stop with a failure code when the name is empty
    if name == "" {
        fmt.Println("No name given")
        os.Exit(1) // a non-zero code means failure
    }
    fmt.Println("Welcome,", name)
}

We type “Ravi” and press Enter. You can also pipe it in with echo "Ravi" | go run ..

Ravi
Your name: Welcome, Ravi

When the input is empty, the program stops with code 1.

$ echo "" | go run .
Your name: No name given
exit status 1

Here, bufio.NewReader reads a full line, and strings.TrimSpace removes the new line at the end. Also, the line “exit status 1” comes from go run itself. When you run a built binary, you only see the code with echo $?.

Format and Check Code Before You Run It

Two more commands help you write clean code. go fmt fixes spacing and layout, and go vet finds bugs the compiler misses. Let’s give go vet something to catch.

package main

import "fmt"

// main has a bug: %d expects a number, but we pass text
func main() {
    fmt.Printf("Count: %d\n", "ten") // wrong type for %d
}
$ go vet .
# example.com/hello
# [example.com/hello]
./main.go:7:5: fmt.Printf format %d has arg "ten" of wrong type string

The code compiles, but it would print a wrong result. So run go fmt ./... and go vet ./... before every commit. Most editors run them on save for you.

Common Errors When You Run a Go Program

When you run a Go program for the first time, you may hit an error. The table below lists the errors beginners see most, with the fix for each one.

Error messageWhy it happensFix
go.mod file not foundNo module in this folderRun go mod init
undefined: greetYou ran one file onlyUse go run .
is not a main packagePackage is not mainChange to package main
declared and not usedUnused local variableUse it or delete it
“os” imported and not usedUnused importRemove the import
missing function body / no mainmain is missingAdd func main()

Common Mistakes

  • Running one file in a big package: use go run . so every file is included.
  • Forgetting the module: without go.mod, newer Go versions refuse to build. Run go mod init first.
  • Committing binaries: add your built files, such as hello or hello.exe, to .gitignore.
  • Expecting defer to run after os.Exit: os.Exit stops at once, so deferred calls are skipped.
  • Missing GOBIN on PATH: after go install, the command is “not found” until $HOME/go/bin is on PATH.

Best Practices

  • Use go run . while learning, because it always includes the whole package.
  • Use go build -o to give binaries clear names, such as bin/api.
  • Keep one main package per program. For many programs in one repo, use cmd/<name>/main.go folders.
  • Run go vet and tests before you ship, since they catch bugs the compiler accepts.
  • Return a non-zero exit code on failure, so scripts and CI tools can detect errors.

How to Run a Go Program: Interview Questions and Answers

These are the run and build questions interviewers ask most. Many include a short program, so you can run a Go program yourself and compare the output.

Questions on How to Run a Go Program

Q1. What happens when you type go run main.go?

Go compiles the file into a temporary folder, runs the binary, and then deletes it. The build cache keeps compiled packages, so the second run is faster.

Q2. What is the difference between go build and go install?

Both compile the code. go build leaves the binary in the current folder, while go install moves it to GOBIN or $GOPATH/bin. Use install for tools you want on your PATH.

Q3. Why does go run main.go fail with “undefined” when go run . works?

go run main.go only compiles the file you named. If a function lives in another file of the same package, Go cannot see it. go run . compiles all files in the package.

Q4. Can you run a Go program without a main function?

No. A runnable program needs package main with func main(). Without main, the build fails, and Go reports that the function main is undeclared.

Q5. Where does go build put the binary, and what is its name?

It puts it in the current folder. The name comes from the last part of the module path or folder name, such as hello. On Windows, Go adds .exe.

Q6. How do you build a binary with a custom name?

Use the -o flag, for example go build -o bin/server .. Go creates the bin folder if needed.

Program Output Questions

Q7. What does this program print?

package main

import (
    "fmt"
    "os"
)

// main shows that os.Exit skips deferred calls
func main() {
    defer fmt.Println("bye") // defer means "run this when main returns"
    fmt.Println("start")
    os.Exit(0) // stop the program now, so main never returns
}
start

It prints only “start”. os.Exit ends the program right away, so the deferred Println never runs. That is why you should return from main instead of calling os.Exit when you need cleanup.

Q8. In what order do init and main run?

package main

import "fmt"

// message is a package variable, so Go sets it before init and main
var message = makeMessage()

// makeMessage prints a line and returns the value for message
func makeMessage() string {
    fmt.Println("1. package variable")
    return "ready"
}

// init runs by itself after package variables and before main
func init() {
    fmt.Println("2. init")
}

// main runs last
func main() {
    fmt.Println("3. main:", message)
}
1. package variable
2. init
3. main: ready

Go first sets package variables, then runs every init function, and finally calls main. A file can even have more than one init.

Q9. What is os.Args[0]?

It is the path of the running program. With go run, it points to a binary in a temporary folder. Your own arguments start at os.Args[1].

Q10. What does this program print with go run . one two?

package main

import (
    "fmt"
    "os"
)

// main prints the number of items and the last item in os.Args
func main() {
    count := len(os.Args)     // program path + one + two = 3
    last := os.Args[count-1] // positions start at 0, so the last one is count-1
    fmt.Println(count, last)
}
3 two

There are three items: the program path, “one” and “two”. The last item is “two”.

Q11. Why does this program fail to compile?

package main

import (
    "fmt"
    "os"
)

func main() {
    count := 5
    fmt.Println("hi")
}
./main.go:5:5: "os" imported and not used
./main.go:9:5: declared and not used: count

Go does not allow unused imports or unused local variables. This rule keeps code clean, and the fix is to use them or delete them.

Build and Tool Questions

Q12. What do go fmt and go vet do?

go fmt rewrites code into the standard Go style. go vet looks for likely bugs, such as a wrong Printf verb or unreachable code. Neither one changes how correct code behaves.

Q13. How do you make a smaller binary?

Build with go build -ldflags="-s -w". These flags remove the symbol table and debug info, so the file gets smaller. The program still works the same way.

Q14. Why is a Go binary larger than a C hello world?

Go builds static binaries by default. The file includes the runtime, the garbage collector and every package you use. So it runs without any extra installs on the target machine.

Q15. How do you build a Windows .exe on Linux?

Set the target system before the build, for example GOOS=windows GOARCH=amd64 go build -o app.exe .. Go supports this cross compiling out of the box.

Advanced Build Questions

Q16. How do you run a program with the race detector?

Add the -race flag, as in go run -race .. Go then reports when two goroutines touch the same memory without a lock. It is slower, so use it in testing.

Q17. What does go build ./… mean?

The ./... pattern means “this folder and every folder below it”. So go build ./... checks that every package in the module compiles. Many teams run it in CI.

Q18. What is the build cache?

Go saves compiled packages in a cache folder, shown by go env GOCACHE. Next time, it only rebuilds what changed. You can clear it with go clean -cache.

Q19. How do you put many programs in one repository?

Give each program its own folder under cmd, such as cmd/api/main.go and cmd/worker/main.go. Then run one with go run ./cmd/api. Shared code goes in other packages.

Q20. What exit code does a Go program return?

It returns 0 when main finishes normally. A panic that is not recovered returns 2. You can set any code with os.Exit(n).

Q21. How can you see the build steps Go runs?

Use go build -x to print every command, or go build -v to print package names. These flags help when a build behaves strangely.

Practice Task

This task shows you how to run a Go program with real input. Write a program that takes two numbers from os.Args, adds them and prints the sum. If the user gives fewer than two numbers, print a message and exit with code 1. Hint: use strconv.Atoi to turn text into an int.

Official Resources

Quick Recap

  • To run a Go program quickly, use go run . inside your module folder.
  • go build saves a binary in the current folder, and go install puts it in GOBIN.
  • os.Args holds command line arguments, and os.Exit sets the exit code.
  • go fmt and go vet keep code clean and catch hidden bugs.
  • Unused imports and variables are compile errors in Go.

What’s Next?

You can now run any program on your own machine. Next, we look at browser tools in the best online Go compilers, so you can test code without any setup. For more basics practice, see our Go functions guide.