CodeBlanks Logo Icon CodeBlanks

go run and go build

Learn to run with go run and compile with go build.

go run and go build

go run hello.go compiles your source in the background and runs it immediately, producing a temporary binary. It is ideal for quick trials.

go build instead produces a permanent binary. You can run the produced file directly with ./hello and copy it to a machine without Go installed.

Both commands compile; the difference is the output. run is fast, build is distributable.

go run vs go build

Knowing the difference helps you work efficiently:

  • go run: fast dev loop, leaves no file
  • go build: produces a distributable binary, used in production
  • go install: installs the binary under GOBIN

Production always runs a binary obtained with go build (or a CI tool).

Practice Build information

A binary produced by go build knows the target it was built for. Print whether runtime.GOOS and runtime.GOARCH are non-empty with fmt.Println(runtime.GOOS != "", runtime.GOARCH != "").

Starter code

main.go
package main

import (
    "fmt"
    "runtime"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "runtime"
)

func main() {
    fmt.Println(runtime.GOOS != "", runtime.GOARCH != "")
}

Expected output

true true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does go build produce?

  • A Docker image
  • An executable binary Correct answer
  • A ZIP file
  • A web server

Explanation: go build produces an executable binary.

2 The go run command

Question
To compile and run hello.go, type ____ hello.go.
Answer
To compile and run hello.go, type go run hello.go.

Explanation: go run compiles and runs the source file.

3 Match the commands

Term Meaning
go run Compiles and runs
go build Produces a binary
go install Installs to GOBIN
go test Runs tests

All lessons in Beginner