Phase 0 · Module 2 of 6
The go command: run, build, test, fmt and vet
The go command: run, build, test, fmt, vet · 10 min read
Go ships one tool, go, that does what other languages need five tools for: building, running, testing, formatting, checking and managing dependencies. Learning it on day one is what makes Go projects feel the same everywhere.
Start a module
$ mkdir hello && cd hello
$ go mod init example.com/helloA module is a versioned unit of Go code. go.mod records its name (usually where it will live, like github.com/you/hello), the Go version and, later, its dependencies.
// main.go
package main
import "fmt"
// Greeting returns a friendly greeting for name.
func Greeting(name string) string {
if name == "" {
name = "world"
}
return fmt.Sprintf("Hello, %s!", name)
}
func main() {
fmt.Println(Greeting("Lagos"))
}Run and build
$ go run .
Hello, Lagos!
$ go build -o hello . && ./hello
Hello, Lagos!go run compiles to a temporary file and runs it. go build produces a single static binary you can copy to another machine with the same OS and CPU, with no runtime to install. Set GOOS and GOARCH to cross-compile, for example GOOS=linux GOARCH=arm64 go build.
Test
// main_test.go
package main
import "testing"
func TestGreeting(t *testing.T) {
tests := []struct{ name, want string }{
{"Lagos", "Hello, Lagos!"},
{"", "Hello, world!"},
}
for _, tt := range tests {
if got := Greeting(tt.name); got != tt.want {
t.Errorf("Greeting(%q) = %q, want %q", tt.name, got, tt.want)
}
}
}$ go test ./...
ok example.com/hello 0.002sTests live next to the code in _test.go files, and the table of inputs and expected outputs above is the most common Go testing style. You'll write a lot of these.
Format and check
$ gofmt -l . # lists files that aren't formatted (none, here)
$ go vet ./... # finds likely bugs, like printf verbs that don't match their argumentsGo has one official format, so code reviews never argue about style. Most editors run gofmt every time you save.
Try it
- Add a test case for a name with spaces. Then make Greeting trim spaces, and watch the test go from failing to passing.
- Change Sprintf's %s to %d and run go vet. What does it tell you?
In the full course you build on this through interfaces and generics, concurrency, web APIs and databases, and a case study in depending on a real open-source library, the Firecracker Go SDK, before deploying a production service.