1.2 How to use go tools(command): go run / build / test / fmt / vet
TL;DR
go run: Instantly run your Go code without creating a separate file. Perfect for quick tests.go build: Compile your code into a single, standalone program (an "executable") that you can run anywhere.go fmt: Automatically clean up and format your code so it's easy to read. No more arguments about style!go test: Run automated checks you've written to make sure your code works correctly.go vet: Let Go's built-in expert scan your code for subtle mistakes and suspicious patterns that might cause trouble later.
Why This Matters
In many programming languages, you need to find, install, and configure a bunch of separate tools just to get started. Go is different. It comes with a powerful, standardized toolkit right out of the box. Learning these five commands is like getting the keys to your workshop. It makes your workflow smooth, consistent, and fast, letting you focus on building cool stuff instead of fighting with your tools.
Concepts in Plain English
Every craft has its essential tools. For a Go developer, these commands are your hammer, screwdriver, and level. They do one thing and do it well.
Here are the key ideas, explained with simple analogies:
go runis like a "preview" button. When writing a document, you hit preview to see how it looks without actually printing it.go rundoes the same for your code—it runs it on the spot so you can see the result.go buildis like "exporting to PDF." You take your draft document and turn it into a final, polished PDF that anyone can open.go buildturns your source code into a single, final program that anyone can run.go fmtis like a magical bookshelf. You can toss books onto it haphazardly, and it automatically straightens them and sorts them perfectly. It just makes everything neat and tidy.go testis like a spell checker for your logic. You write down the "correct answers" in a separate file, andgo testruns your code to make sure it produces those answers every time.go vetis like a grammar checker. It reads your sentences (your code) and flags things that, while maybe not technically wrong, sound awkward or could be misunderstood. It helps you write clearer, safer code.
To keep things straight, here’s a little glossary:
| Term | Simple Definition | Where It Shows Up |
| Executable | A standalone program file that can be run directly. | The output of go build. |
| Terminal | The text-based command-line window where you type commands. | Where you run all go commands. |
| Source Code | The human-readable .go files you write. | The input for all go commands. |
| Package | A folder containing Go source files. | When you run a command like go build . on a folder. |
Quick Setup
Before we start, you just need two things: Go itself and a folder for our project.
- Install Go: Head over to the official Go website and download the installer for your operating system. The setup is quick and straightforward.
Create a File: Inside that folder, create a file named hello.go and paste this classic "Hello, World!" code into it.
// hello.go
package main
import "fmt"
func main() {
fmt.Println("Hello, builder!")
}
Create a Project Folder: Open your terminal and create a new folder for our experiment.
# Create a new directory and move into it
mkdir go-basics
cd go-basics
That's it! We're ready to go.
Do It Step by Step
Let's take each command for a spin.
1. See It Live with go run
Goal: Run our hello.go program to see its output immediately.
This is your go-to command for quick checks and experiments.
- Open your terminal in the
go-basicsfolder.
Check the output: You should see the message printed directly to your terminal.Plaintext
# Input: go run hello.go
# Output:
Hello, builder!
Run the command:
# Tell Go to run the hello.go file
go run hello.go
Pro tip: go run is fantastic for development, but you don't use it to deploy your final application. For that, you'll want to build it.2. Create a Program with go build
Goal: Compile our hello.go code into a single, runnable program file.
This creates a self-contained executable that you can share or run on a server. It's the "final draft" of your code.
- Stay in the same terminal window.
- Look for the new file: After you run the command, you won't see any text output. Instead, check the files in your folder. You'll find a new file.
- On macOS/Linux, it will be named
hello. - On Windows, it will be
hello.exe.
- On macOS/Linux, it will be named
Run your new program:
# On macOS or Linux
./hello
# On Windows
hello.exe
You'll see the same output as before: Hello, builder!. The difference is that now it's a real, standalone program.
Run the build command:
# Tell Go to build an executable from our file
go build hello.go
Here's how run and build compare:
| Command | What It Does | When to Use It | Main Benefit |
go run | Compiles and runs the code in one step, then deletes the temporary program. | When you're writing and testing code. | Fast feedback loop. |
go build | Compiles the code and saves the result as a permanent executable file. | When you're ready to share or deploy your app. | Creates a portable, optimized program. |
3. Tidy Up with go fmt
Goal: Automatically format messy code to match Go's official style.
Let's intentionally mess up our hello.go file to see go fmt work its magic.
Check the file: Open hello.go again. It will be perfectly formatted, as if by magic.
// Formatted hello.go file
package main
import "fmt"
func main() {
fmt.Println("Hello, builder!")
}
Run the format command: The . tells go fmt to format all .go files in the current folder.
# Format all Go files in the current directory (.)
go fmt .
Edit hello.go to look sloppy, like this
// Messy hello.go file
package main
import "fmt"
func main() {
fmt.Println( "Hello, builder!" )
}
Warning: There's no "undo" for go fmt. But since it just cleans up spacing and alignment, that's almost never a problem.4. Check Your Work with go test and go vet
These two commands help you find bugs, but they look for different kinds of problems.
go test: Runs formal tests that you write yourself.go vet: Scans for suspicious code that might be a mistake.
Let's see a quick example of go vet.
See the warning: go vet will analyze the code and report the problem it found.
# Output:
./check.go:8:14: fmt.Printf format %s reads arg #1, but call has 0 args
It's telling us exactly where the problem is and what's wrong. This is incredibly helpful for catching subtle bugs early!
Run go vet:
# Vet all Go files in the current directory (.)
go vet .
Create a new file called check.go with a common mistake: printing a variable without telling the print function what it is.
// check.go
package main
import "fmt"
func check() {
name := "builder"
// This is a mistake! We used %s but didn't provide the 'name' variable.
fmt.Printf("Hello, %s!")
}
Examples in Action
Let's put it all together. Imagine we're building a tiny tool that greets a user.
Example A: A Simple Greeter
Here's a simple program. You can save this as greeter.go.
// greeter.go
package main
import (
"fmt"
"os"
)
// The main function is the entry point of our program.
func main() {
// os.Args is a list of command-line arguments.
// os.Args[0] is the program name, so we check if there's at least one more.
if len(os.Args) > 1 {
name := os.Args[1] // Get the first argument
fmt.Printf("Hello, %s!\n", name)
} else {
fmt.Println("Hello, anonymous builder!")
}
}
You can run this in two ways:
- With
go run:go run greeter.go Alice→ Output:Hello, Alice! - With
go build:go build greeter.go(creates an executable namedgreeter)./greeter Bob→ Output:Hello, Bob!
This flow, from writing to running, is central to Go development.
flowchart LR
subgraph "Your Computer"
A[1. Write code in greeter.go] --> B{What's the goal?};
subgraph "Quick Test"
B --> C[2a. Run 'go run greeter.go Alice'];
C --> D[3. See 'Hello, Alice!' in Terminal];
end
subgraph "Final Program"
B --> E[2b. Run 'go build greeter.go'];
E --> F[3b. A 'greeter' file appears];
F --> G[4b. Run './greeter Bob'];
G --> H[5b. See 'Hello, Bob!' in Terminal]
end
end
ASCII Fallback: The diagram shows two paths. Path 1 (Quick Test) goes from code -> go run -> terminal output. Path 2 (Final Program) goes from code -> go build -> executable file -> run executable -> terminal output.
Common Pitfalls
Everyone stumbles a bit when learning. Here are a few common trip-ups:
- Running
go buildand expecting output. Remember,go buildis silent. Its only job is to create a file. You have to run that new file yourself to see any output. - Forgetting the
.in commands. Commands likego fmt .orgo test .need the.to know you mean "here, in this current folder." Forgetting it can sometimes lead to confusing errors. - Thinking
go vetfinds all bugs.go vetis a great safety net, but it's not a substitute for writing proper tests withgo test. It only catches a specific set of common-but-suspicious patterns.
FAQ
1. Is go build the same as "compiling"?
Yep, exactly. go build is the command that takes your human-readable source code and compiles it into machine code that a computer can run directly. go run does this too, but it throws away the result after running it.
2. What does the . mean in go fmt .?
In the command line, . is a shortcut for "the current directory you are in." So go fmt . means "format all the Go source files you can find right here."
3. Do I need to run these commands in a specific order?
Not really, but there's a natural workflow: You write some code, use go run to test it quickly, use go fmt to keep it clean, write some checks and use go test to confirm it works, and finally use go build when you're ready to create the final version. go vet is good to run periodically, like a health checkup.
4. Are these tools free?
Absolutely! All the tools we discussed (run, build, fmt, test, vet) are a core part of the Go programming language, which is open-source and completely free to use.
Recap & Next Steps
You've just learned the core workflow of a Go developer. These five commands are your bread and butter.
- You can run code instantly for quick feedback.
- You can build code into a final, portable program.
- You can format code automatically to keep it clean.
- You can test code to ensure it's correct.
- You can vet code to catch subtle mistakes.
Ready for more? A great next step is to look into go mod, the tool for managing dependencies (other people's code that your project uses). Happy building!