Learnings

Go, part 1 of 5

Go Setup, GOPATH and Packages

Install Go on macOS, Linux or Windows, understand where it keeps things (GOROOT, GOPATH, GOBIN), and build a small bank module with packages, a dependency, a test and two commands. Every command and output on this page was run on Go 1.27.

Install

Part 1 of 4 · from nothing to a running program

Go ships as one download that contains the compiler, the standard library and the go command. There is nothing else to install.

What you need first

Install

  • A terminal. Everything in Go goes through the go command.
  • Git. Go downloads dependencies from Git hosts, and your module path is usually a repository URL.
  • Any text editor. VS Code with the Go extension is the common free choice.
  • One programming language you already know. This page explains the tooling, not variables and loops.

Four facts that explain most of what follows:

FactWhat it means for you
Go is compiledgo build turns your code into one executable file. The target machine does not need Go installed.
One tool does everythingBuild, run, test, format, fetch dependencies: all are go subcommands. No separate package manager.
A folder is a packageAll .go files in one folder share one package name. Import paths are folder paths.
A go.mod file is a moduleThe folder that holds go.mod is the project root. It names the project and lists its dependencies.

Install on macOS

Install

With Homebrew:

Without Homebrew: download the .pkg file from go.dev/dl (pick arm64 for Apple Silicon, amd64 for Intel) and double-click it. It installs to /usr/local/go and adds /usr/local/go/bin to your PATH. Open a new terminal window afterwards.

Install on Linux and Unix

Install

The official way is a tarball unpacked into /usr/local. Check go.dev/dl for the current version number and your CPU (amd64 or arm64).

The same steps work on FreeBSD and other Unix systems with the matching tarball.

Package managers: sudo apt install golang-go or sudo dnf install golang also work, but distributions often ship a version that is a year or more old. Prefer the tarball when you need a current release.

Install on Windows

Install

Download the .msi installer from go.dev/dl and run it. It installs to C:\Program Files\Go and sets PATH for you. Or use a package manager from PowerShell:

Close and reopen the terminal so it picks up the new PATH. On Windows the default GOPATH is %USERPROFILE%\go, and built programs get an .exe ending.

Check the install

Install

The last part is operating system/CPU. If you see command not found, the folder holding go is not on your PATH: open a new terminal, or re-check the PATH line from the install step.

To upgrade later, install the new version the same way. Homebrew users run brew upgrade go.

One Go per project: you rarely need a version manager. If a project's go.mod asks for a newer Go than the one installed, the go command downloads that toolchain by itself and uses it for that project (Go 1.21 and later).

First program

Install

Make a folder anywhere and save this file in it.

  • package main says this folder builds into a program, not a library.
  • func main() is where the program starts.
  • fmt is a standard library package for formatted printing.

That hello file is about 2.3 MB and contains everything it needs. Copy it to another machine with the same OS and CPU and it runs.

Editor setup

Install

  • VS Code: install the extension named "Go" (by the Go team). On first use it offers to install gopls, the language server that gives autocomplete, go-to-definition and errors as you type. Accept.
  • GoLand: works out of the box.
  • Vim, Neovim, others: point your LSP client at gopls.

Turn on "format on save". Go has one official code style, applied by gofmt, and everyone uses it. It indents with tabs.

Where Go keeps things

Part 2 of 4 · GOROOT, GOPATH, GOBIN and the caches

Three folders matter: where Go itself lives, where downloaded code and installed tools go, and your own project. Only the last one is yours to organise.

go env: the settings

Where Go keeps things

go env prints every setting. Pass names to see only those.

VariableWhat it isDefaultChange it?
GOROOTThe Go installation: compiler and standard libraryWherever Go was installedNo. Go finds it by itself.
GOPATHYour Go home: downloaded modules and installed tools~/go (%USERPROFILE%\go on Windows)Rarely
GOBINWhere go install puts executablesGOPATH/binSometimes
GOMODCACHEDownloaded dependency source, shared by all projectsGOPATH/pkg/modRarely
GOCACHECompiled build results, so rebuilds are fastThe OS cache folderNo
GOOS, GOARCHTarget operating system and CPUYour machinePer build, to cross-compile
GOPROXYWhere modules are downloaded fromproxy.golang.org, then the source hostBehind a company proxy
GOPRIVATEModule paths that must skip the public proxyEmptyFor private repositories

Change a setting permanently with go env -w. It is saved in Go's own config file, so it works the same in every shell. An environment variable of the same name wins over it.

Older versions: before recent releases, go env GOBIN printed an empty line when it was not set. Empty means the same thing: GOPATH/bin.

GOPATH: src, pkg and bin

Where Go keeps things

Old tutorials say a Go workspace has three folders: src, pkg and bin (there is no lib; pkg played that role). That was true until Go 1.11 introduced modules. The folders still exist, but their jobs changed.

FolderBefore modules (GOPATH mode)Today (module mode)
~/go/srcAll code lived here, yours and downloaded, at src/github.com/user/projectNot used. Your project can live in any folder.
~/go/pkgCompiled package archives (.a files)pkg/mod holds downloaded dependency source, one folder per version, read-only
~/go/binExecutables from go installThe same

So today GOPATH is a cache and a tool folder. You do not create it, you do not put projects in it, and most people never set it. Your code lives wherever you like, for example ~/projects/bank, and is marked as a project by its go.mod file.

Interview line: GOPATH mode had one global workspace and no dependency versions. Modules gave every project its own go.mod with exact versions, so two projects can use different versions of the same library.

GOBIN and go install

Where Go keeps things

go install compiles a program and copies the executable to GOBIN. It is how you install command line tools written in Go. Outside a project, give the package path and a version:

To run installed tools by name, the folder must be on your PATH. This is the one piece of manual setup Go needs. Add it to ~/.zshrc, ~/.bashrc or ~/.profile:

On Windows, add %USERPROFILE%\go\bin to the user Path in "Edit environment variables for your account".

To install somewhere else, set GOBIN for one command or for good:

CommandExecutable goes toUse it for
go runA temp folder, deleted afterwardsTrying code while developing
go buildThe current folder (or -o path)Producing a file to ship
go installGOBINTools you want to run by name

How an import is found

Where Go keeps things

Every import line is resolved in the same order. Knowing it makes the error messages obvious.

Three places only: the Go installation, your own module, and the module cache. Nothing is searched for by name across your disk.

Modules and packages

Part 3 of 4 · build a small bank project

A package is one folder of .go files. A module is a tree of packages with a go.mod at the root, versioned and released together. This part builds one module with four packages.

Create a module

Modules and packages

  • The module path (github.com/hygull/bank) is the prefix of every import inside this project. Use the repository URL if you will publish it, so others can go get it. For a throwaway project any name works, such as example.com/bank.
  • The go line is the minimum Go version the code needs.

Nothing is uploaded. The module path is only a name. The repository does not have to exist until someone else wants to download the module.

Create a package

Modules and packages

Make a folder, put a .go file in it, and start the file with package plus the folder name. That is all a package is.

Rules worth remembering:

  • Every file in the folder must declare the same package name. Split a package into as many files as you like; they see each other's names without importing.
  • Package names are short, lower case, one word: account, not bankAccounts or account_utils.
  • The comment directly above package and above each exported name is the documentation. go doc reads it.
  • Go reports failure by returning an error value, not by raising an exception. %w wraps the original error so callers can still test for it.

Use the package from a command

Modules and packages

A program is a package named main with a main function. It imports account by its full path: module path plus folder.

In code you refer to a package by its last path element: account.New. The ./ in go run ./cmd/bank means "the package in this folder", as opposed to a standard library name.

Exported and unexported names

Modules and packages

Go has no public or private keywords. The first letter decides:

NameFirst letterVisible from
Account, Owner, New, Balance()CapitalAny package that imports this one (exported)
balanceLower caseOnly files in the same package (unexported)

This applies to types, functions, methods, variables, constants and struct fields alike. Reading the unexported field from main fails to compile, and the compiler even suggests the fix:

Why it matters here: because balance is unexported, the only way to change it is through Deposit and Withdraw. No other package can set a negative balance by accident.

internal: packages only you can import

Modules and packages

Exported names are visible to the whole world once the module is published. A folder named internal limits that: packages under it can be imported only by code inside the parent of internal, here the bank module.

A second command inside the module may use it:

The same import from a different module is rejected by the compiler:

Rule of thumb: start every helper package under internal/. Moving it out later is easy; taking back something other people already import is not.

Project layout

Modules and packages

The project now looks like this. It is the most common shape for a Go service.

  • cmd/<name>/main.go is a convention, not a rule. The executable takes the folder's name.
  • There is no src/ folder. That was GOPATH; do not recreate it inside a module.
  • A tiny program can be just go.mod and main.go in one folder. Add folders when you have a second package, not before.
  • ./... means "this folder and everything below it": go build ./..., go test ./....

Add a dependency

Modules and packages

go get downloads a module into the module cache and records it in go.mod. Here: a library that generates unique ids, for receipt numbers.

Import it and call it in cmd/bank/main.go:

The receipt id is random, so yours will differ. go.mod now pins the exact version:

File or commandPurpose
go.modWhich modules and versions you need. You may edit it by hand.
go.sumChecksums of those downloads, so a changed or tampered copy is refused. Never edit it. Commit both files.
go get pkg@v1.5.0Add, upgrade or downgrade to a specific version. @latest for the newest.
go get -u ./...Upgrade all dependencies to their latest minor or patch versions.
go mod tidyAdd missing requirements and remove unused ones. Run it before every commit.
go list -m allShow every module in the build, including dependencies of dependencies.
go mod why pkgShow which of your packages pulls a dependency in.

No virtualenv, no node_modules: dependency source is stored once in ~/go/pkg/mod, one folder per version, and shared by every project. The project folder holds only go.mod and go.sum.

Add a test

Modules and packages

Tests live beside the code in files ending _test.go. A test is a function named TestXxx that takes *testing.T. The testing package is in the standard library.

  • t.Errorf records a failure and continues; t.Fatalf stops the test.
  • errors.Is finds ErrInsufficientFunds even though Withdraw wrapped it in a longer message. That is what %w was for.
  • _test.go files are never compiled into the real program.

Everyday commands

Part 4 of 4 · build, ship, check, and what to do when it fails

Build and install your commands

Everyday commands

After go install, and with ~/go/bin on your PATH, typing bank in any folder runs your program.

Add bin/ to .gitignore. Executables are build output, not source.

Cross-compile for another OS

Everyday commands

Set GOOS and GOARCH for one command and Go builds for that target. No extra toolchain is needed for pure Go code.

TargetGOOSGOARCH
Linux server, Intel or AMDlinuxamd64
Linux on ARM (AWS Graviton, Raspberry Pi 64-bit)linuxarm64
Mac with Apple Silicondarwinarm64
Mac with Inteldarwinamd64
Windowswindowsamd64

go tool dist list prints every supported pair. In PowerShell set the variables first: $env:GOOS="linux"; go build ./cmd/bank.

Why this matters for Docker: a statically linked Linux binary can be copied into an almost empty image. That is why Go service images are often a few megabytes.

Format, vet and read docs

Everyday commands

Both print nothing when there is nothing to fix. Run them, plus go test ./..., before every commit.

go doc shows documentation in the terminal, for the standard library and for your own packages:

Workspaces: two modules side by side

Everyday commands

Sometimes you edit a library and an app that uses it at the same time, and the library change is not published yet. A go.work file tells Go to use the local folders instead of downloading.

Keep it local: go.work describes your machine, so it is usually not committed. This is the modern meaning of "workspace" in Go; it is unrelated to the old GOPATH workspace.

GOPATH mode, for old code

Everyday commands

You will meet this in old projects, old answers and interview questions. In GOPATH mode there is no go.mod. All code sits under GOPATH/src, and an import path is simply the folder path below src.

It still works when you switch module mode off with GO111MODULE=off:

GOPATH modeModule mode (default since Go 1.16)
Project locationMust be under GOPATH/srcAnywhere
Dependency versionsNone: whatever is checked out in srcExact versions in go.mod, verified by go.sum
Two projects, two versions of one libraryNot possible without tricksNormal
Reproducible buildNoYes

Do not start new work this way. To modernise an old project, move it out of GOPATH/src if you like, then run go mod init <import path> and go mod tidy in its root.

Common errors

Everyday commands

MessageCauseFix
go: go.mod file not found in current directory or any parent directoryYou are not inside a modulecd into the project, or run go mod init
no required module provides package X; to add it: go get XThe import is not in go.modRun the go get it prints, or go mod tidy
package X is not in stdThe import path lacks your module path, so Go looked in the standard libraryImport github.com/hygull/bank/account, not account
"os" imported and not usedAn unused import is a compile error in GoDelete it; editors with gopls do this on save
declared and not used: totalSo is an unused local variableUse it, delete it, or assign to _
use of internal package ... not allowedImporting another module's internal/Use that module's public packages
import cycle not allowedPackage A imports B and B imports AMove the shared part into a third package both import
command not found: bank after go installGOBIN is not on PATHAdd $(go env GOPATH)/bin to PATH (see GOBIN)

Cheat sheet

Everyday commands

TaskCommand
Which Go is this?go version
Show settingsgo env, go env GOPATH
Start a projectgo mod init github.com/you/project
Run without keeping a binarygo run . or go run ./cmd/bank
Check everything compilesgo build ./...
Build a binary to shipgo build -o bin/ ./cmd/bank
Install a binary into GOBINgo install ./cmd/bank
Install someone else's toolgo install host/path/cmd/tool@latest
Add or upgrade a dependencygo get host/path@version
Clean up go.modgo mod tidy
Run testsgo test ./..., add -v for detail, -run Name for one test
Format and checkgo fmt ./..., go vet ./...
Read docsgo doc fmt.Println
Build for Linux from a MacGOOS=linux GOARCH=amd64 go build ./cmd/bank
Free disk spacego clean -cache (build cache), go clean -modcache (downloads)

Next: Go Basics, the language itself, starting with variables, types, control flow and functions.