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
- A terminal. Everything in Go goes through the
gocommand. - 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:
| Fact | What it means for you |
|---|---|
| Go is compiled | go build turns your code into one executable file. The target machine does not need Go installed. |
| One tool does everything | Build, run, test, format, fetch dependencies: all are go subcommands. No separate package manager. |
| A folder is a package | All .go files in one folder share one package name. Import paths are folder paths. |
A go.mod file is a module | The folder that holds go.mod is the project root. It names the project and lists its dependencies. |
Install on macOS
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
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
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
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
Make a folder anywhere and save this file in it.
package mainsays this folder builds into a program, not a library.func main()is where the program starts.fmtis 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
- 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
go env prints every setting. Pass names to see only those.
| Variable | What it is | Default | Change it? |
|---|---|---|---|
GOROOT | The Go installation: compiler and standard library | Wherever Go was installed | No. Go finds it by itself. |
GOPATH | Your Go home: downloaded modules and installed tools | ~/go (%USERPROFILE%\go on Windows) | Rarely |
GOBIN | Where go install puts executables | GOPATH/bin | Sometimes |
GOMODCACHE | Downloaded dependency source, shared by all projects | GOPATH/pkg/mod | Rarely |
GOCACHE | Compiled build results, so rebuilds are fast | The OS cache folder | No |
GOOS, GOARCH | Target operating system and CPU | Your machine | Per build, to cross-compile |
GOPROXY | Where modules are downloaded from | proxy.golang.org, then the source host | Behind a company proxy |
GOPRIVATE | Module paths that must skip the public proxy | Empty | For 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
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.
| Folder | Before modules (GOPATH mode) | Today (module mode) |
|---|---|---|
~/go/src | All code lived here, yours and downloaded, at src/github.com/user/project | Not used. Your project can live in any folder. |
~/go/pkg | Compiled package archives (.a files) | pkg/mod holds downloaded dependency source, one folder per version, read-only |
~/go/bin | Executables from go install | The 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
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:
| Command | Executable goes to | Use it for |
|---|---|---|
go run | A temp folder, deleted afterwards | Trying code while developing |
go build | The current folder (or -o path) | Producing a file to ship |
go install | GOBIN | Tools you want to run by name |
How an import is found
Every import line is resolved in the same order. Knowing it makes the error messages obvious.
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
- 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 cango getit. For a throwaway project any name works, such asexample.com/bank. - The
goline 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
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, notbankAccountsoraccount_utils. - The comment directly above
packageand above each exported name is the documentation.go docreads it. - Go reports failure by returning an
errorvalue, not by raising an exception.%wwraps the original error so callers can still test for it.
Use the package from a command
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
Go has no public or private keywords. The first letter decides:
| Name | First letter | Visible from |
|---|---|---|
Account, Owner, New, Balance() | Capital | Any package that imports this one (exported) |
balance | Lower case | Only 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
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
The project now looks like this. It is the most common shape for a Go service.
cmd/<name>/main.gois 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.modandmain.goin 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
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 command | Purpose |
|---|---|
go.mod | Which modules and versions you need. You may edit it by hand. |
go.sum | Checksums of those downloads, so a changed or tampered copy is refused. Never edit it. Commit both files. |
go get pkg@v1.5.0 | Add, 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 tidy | Add missing requirements and remove unused ones. Run it before every commit. |
go list -m all | Show every module in the build, including dependencies of dependencies. |
go mod why pkg | Show 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
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.Errorfrecords a failure and continues;t.Fatalfstops the test.errors.IsfindsErrInsufficientFundseven thoughWithdrawwrapped it in a longer message. That is what%wwas for._test.gofiles 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
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
Set GOOS and GOARCH for one command and Go builds for that target. No extra toolchain is needed for pure Go code.
| Target | GOOS | GOARCH |
|---|---|---|
| Linux server, Intel or AMD | linux | amd64 |
| Linux on ARM (AWS Graviton, Raspberry Pi 64-bit) | linux | arm64 |
| Mac with Apple Silicon | darwin | arm64 |
| Mac with Intel | darwin | amd64 |
| Windows | windows | amd64 |
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
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
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
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 mode | Module mode (default since Go 1.16) | |
|---|---|---|
| Project location | Must be under GOPATH/src | Anywhere |
| Dependency versions | None: whatever is checked out in src | Exact versions in go.mod, verified by go.sum |
| Two projects, two versions of one library | Not possible without tricks | Normal |
| Reproducible build | No | Yes |
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
| Message | Cause | Fix |
|---|---|---|
go: go.mod file not found in current directory or any parent directory | You are not inside a module | cd into the project, or run go mod init |
no required module provides package X; to add it: go get X | The import is not in go.mod | Run the go get it prints, or go mod tidy |
package X is not in std | The import path lacks your module path, so Go looked in the standard library | Import github.com/hygull/bank/account, not account |
"os" imported and not used | An unused import is a compile error in Go | Delete it; editors with gopls do this on save |
declared and not used: total | So is an unused local variable | Use it, delete it, or assign to _ |
use of internal package ... not allowed | Importing another module's internal/ | Use that module's public packages |
import cycle not allowed | Package A imports B and B imports A | Move the shared part into a third package both import |
command not found: bank after go install | GOBIN is not on PATH | Add $(go env GOPATH)/bin to PATH (see GOBIN) |
Cheat sheet
| Task | Command |
|---|---|
| Which Go is this? | go version |
| Show settings | go env, go env GOPATH |
| Start a project | go mod init github.com/you/project |
| Run without keeping a binary | go run . or go run ./cmd/bank |
| Check everything compiles | go build ./... |
| Build a binary to ship | go build -o bin/ ./cmd/bank |
Install a binary into GOBIN | go install ./cmd/bank |
| Install someone else's tool | go install host/path/cmd/tool@latest |
| Add or upgrade a dependency | go get host/path@version |
Clean up go.mod | go mod tidy |
| Run tests | go test ./..., add -v for detail, -run Name for one test |
| Format and check | go fmt ./..., go vet ./... |
| Read docs | go doc fmt.Println |
| Build for Linux from a Mac | GOOS=linux GOARCH=amd64 go build ./cmd/bank |
| Free disk space | go clean -cache (build cache), go clean -modcache (downloads) |
Next: Go Basics, the language itself, starting with variables, types, control flow and functions.