Bookmarks
ReferenceBackendVerified

Go

Go (Golang) — a compiled language for network services and command-line utilities. In this reference: types, interfaces, errors, modules, goroutines and channels, go test.

checked 5 Nov · next check 12 Nov · 49 min read

Sections
13
Reading
49 min
Current version
1.27.3
Written from
go.dev/doc

Check status of the reference

Verified 5 Nov · next check 12 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What Go is and how it works

Go (often called Golang) is a compiled programming language with static typing, a garbage collector and built-in concurrency. A program is compiled to machine code in advance and needs neither an interpreter nor a virtual machine to run.

Go was created for network servers and is at its strongest in cloud infrastructure: Docker and Kubernetes, for example, are written in it. Builds are meant to be fast: even a large program should compile in a few seconds. Goroutines are so cheap that hundreds of thousands of them run in a single process. If you are used to classes with inheritance and to exceptions, you will have to adjust: Go has no type hierarchies, and errors are returned as ordinary values.

The build model is simple. A package is a directory with .go files, and a module is a set of packages with a go.mod file. The go build command compiles packages and links them into a single executable file, statically by default. That file includes the runtime — a library present in every Go program: it schedules goroutines, manages their stacks and collects garbage. The finished file is copied to a machine with the same OS and processor architecture, while a different platform is set with the GOOS and GOARCH variables.

The build platform is set with the GOOS and GOARCH variables, for example GOOS=linux GOARCH=arm64.

The language and the standard library are covered by the Go 1 compatibility promise: a program that works now will keep building with new releases without changes to the source code. You still need to rebuild it, though — compatibility is guaranteed at the source level, not for binaries.

How it differs from Python and Java

FeatureGoPythonJava
How it runsthe compiler produces machine code in advancean interpreter runs the program without a separate buildthe compiler turns the code into bytecode, which the JVM runs
Typingstatic: types are checked by the compilervariables and arguments are not declaredstrictly static
Concurrencygoroutines and channels are built into the languagethreads; in a standard CPython build one thread executes the bytecode at any moment (GIL)threads
What you deployone executable filesource code and an interpreterbytecode and the JVM

Choose Go for network services and tools that need to build fast and deploy as a single file. Python is more convenient for scripts and experiments in the interpreter, Java — when the team and libraries already live on the JVM. Packaging a service into an image is covered in the Docker reference, gRPC services in the gRPC reference.

What to know in advance

  • Command line: directories, environment variables, PATH — the Linux reference.
  • Git: the module path usually matches the repository address — the Git reference.
  • HTTP basics for network services — the “HTTP and REST” reference.

Section sources

the section is written from these pages

Cheat sheet

Everyday commands and constructs; each one is covered in detail in its own section. Replace the names in the examples (example.com/hello, s, m, ch) with your own.

Commands

TaskCommand
Create a module in the current directorygo mod init example.com/hello
Run the program from the current directorygo run .
Build an executablego build -o bin/app .
Build for Linux on ARMGOOS=linux GOARCH=arm64 go build .
Run all the module’s testsgo test ./...
Add or change a dependency versiongo get example.com/pkg@v1.2.3
Tidy up go.mod and go.sumgo mod tidy
Find suspicious codego vet ./...
Update the code to modern idiomsgo fix ./...
Format all files in the directorygofmt -w .
Function documentation in the terminalgo doc strings.Cut

Declarations

TaskHow to write it
Variable with a zero valuevar n int
Variable with type inference (inside a function)name := "gopher"
Constantconst Timeout = 5 * time.Second
Numbered constantsconst ( Low = iota; Mid; High )
New type based on anothertype UserID int64
Structtype User struct { ID int64; Name string }
Function with a result and an errorfunc parse(s string) (int, error)

Slices and maps

TaskHow to write it
Slice of five zeross := make([]int, 5)
Empty slice with capacity in reserves := make([]int, 0, 100)
Slice literals := []string{"a", "b"}
Append elementss = append(s, 1, 2)
Length and capacitylen(s), cap(s)
Elements 1 and 2 (same underlying array)t := s[1:3]
Copy into a separate arrayc := make([]int, len(s)); copy(c, s)
Create a mapm := map[string]int{}
Check whether a key existsv, ok := m["go"]
Delete a keydelete(m, "go")

Control flow

TaskHow to write it
Condition with a short declarationif n, err := strconv.Atoi(s); err == nil { … }
Loop with a counterfor i := 0; i < 10; i++ { … }
“While” loopfor n > 0 { … }
Infinite loopfor { … }
Iterate over a slicefor i, v := range s { … }
Iterate over a map (the order is not specified)for k, v := range m { … }
Repeat 10 timesfor i := range 10 { … }
Switch without breakswitch x { case 1, 2: … default: … }
Run when the function exitsdefer f.Close()

Errors

TaskHow to write it
Check and return an errorif err != nil { return err }
Create an errorerrors.New("empty name")
Wrap with contextfmt.Errorf("read config: %w", err)
Find an error in the chainerrors.Is(err, fs.ErrNotExist)
Extract an error of the needed type (since Go 1.26)pe, ok := errors.AsType[*fs.PathError](err)
Join several errorserrors.Join(err1, err2)

Goroutines and channels

TaskHow to write it
Start a goroutinego worker(ch)
Unbuffered and buffered channelsmake(chan int), make(chan int, 10)
Send and receivech <- v, v := <-ch
Close and read to the endclose(ch), for v := range ch { … }
Wait for the first channel that is readyselect { case v := <-ch: … case <-done: … }
Wait for a group of goroutines (since Go 1.25)wg.Go(func() { … }), then wg.Wait()
Protect shared datamu.Lock(), defer mu.Unlock()

Section sources

the section is written from these pages

Installation and first run

The official way to install Go is an archive or installer from go.dev/dl: it contains the go command, the compiler and the standard library. Verify the result with go version, and start your first project with go mod init.

Linux

Download the archive for your architecture from go.dev/dl — for a regular server that is linux-amd64. Remove any previous installation and unpack the archive into /usr/local: you get a /usr/local/go directory.

bashin the directory with the archive
# the go1.27.* pattern matches any release of the branchsudo rm -rf /usr/local/gosudo tar -C /usr/local -xzf go1.27.*.linux-amd64.tar.gz

Add the /usr/local/go/bin directory to PATH, and also $HOME/go/bin — go install puts the programs it installs there. Append the lines to ~/.profile; they take effect in a new session or after source ~/.profile.

bashon the host
echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.profileecho 'export PATH=$PATH:$HOME/go/bin' >> ~/.profilesource ~/.profile

macOS and Windows

On macOS, open the .pkg package from the download page: it installs Go into /usr/local/go and adds /usr/local/go/bin to PATH itself. Go 1.27 requires macOS 13 Ventura or newer. On Windows, run the .msi installer — by default Go is installed into Program Files — and then open a fresh command line so that it picks up the new PATH.

Verification

bashin a new terminal
go version
textexample output
go version go1.27.0 linux/amd64

First project

Create a directory and a module. The module path (example.com/hello) is the import prefix for all its packages; if others are going to download the module, it is the repository address, for example github.com/user/hello.

bashin the terminal
mkdir hello && cd hellogo mod init example.com/hello
gomain.go
package main import "fmt" func main() {	fmt.Println("Hello, Go!")}
bashin the hello directory
go run .
textexample output
Hello, Go!
textproject tree
hello/├── go.mod└── main.go

The Go version in go.mod

The go line in go.mod is the minimum Go version for the module and the language version whose rules the compiler checks its code against. The toolchain line is the suggested toolchain: it takes effect only when the module is the main module and only if its version is newer than the version of Go installed by default. If either line is newer than the installed Go, the go command downloads the required toolchain itself and runs it. GOTOOLCHAIN=local forbids switching: the command then refuses to work with such a module.

Since Go 1.26, go mod init writes the version of the previous branch into go.mod: Go 1.27.x creates the line go 1.26.0. This keeps the module compatible with both supported branches. To use the new 1.27 features, such as generic methods, raise the version with go get go@1.27.0.

textgo.mod after go mod init
module example.com/hello go 1.26.0
bashin the module directory
go get go@1.27.0

Section sources

the section is written from these pages

Syntax and control flow

A Go file starts with a package line, followed by imports and declarations. There are few control constructs — if, for, switch, select and defer — and the language has just one loop: for.

gomain.go
package main import (	"fmt"	"os"	"strings") func main() {	name := "Go"	if len(os.Args) > 1 {		name = strings.Join(os.Args[1:], " ")	}	fmt.Println("Hello, " + name + "!")}

A name is visible to other packages (exported) when it begins with an uppercase letter: strings.Join is available from outside, while a function named join is visible only within its own package. The rule applies to package-level names, struct fields and methods; the words public and private do not exist in Go.

Declarations and zero values

var declares a variable with a type or with an initial value; inside functions the short declaration := is more common, with the type inferred from the value. A variable without a value gets the zero value of its type: 0, false, "", and for pointers, slices, maps, channels, functions and interfaces — nil.

go
// zero value: 0var count int // the string type is inferred from the valuevar name = "gopher" func run() {	// := works only inside functions	port := 8080	// at least one new variable on the left	host, port := "localhost", 9090	fmt.Println(count, name, host, port)}

Constants are declared with const. In a constant block the identifier iota equals the line number, starting from zero, and a line without an expression repeats the previous one along with its type. Here Debug equals 0, Info — 1, Warn — 2, Error — 3, and all of them have the type Level.

go
type Level int const (	Debug Level = iota	Info	Warn	Error)

if and for

There are no parentheses around the condition, and the braces are required. Before the if condition you can run a short statement: a variable declared there is visible only inside the if and its else.

go
if err := os.Remove(path); err != nil {	log.Printf("remove %s: %v", path, err)}

for replaces both the for and the while of other languages: it comes with three parts, with a single condition, or without a condition — an infinite loop until break or return.

go
for i := 0; i < 3; i++ {	fmt.Println(i)} n := 100for n > 1 {	n /= 2}

The range form iterates over an array, a slice, a string, a map, a channel, an integer (since Go 1.22) and an iterator function (since Go 1.23). Since Go 1.22, each iteration has its own loop variables, so a closure created in the loop sees the value of its own iteration.

go
for i, lang := range []string{"go", "rust"} {	fmt.Println(i, lang)} // i = 0, 1, 2for i := range 3 {	fmt.Println(i)}

An iterator function takes a yield function and calls it for each value; if yield returns false — the loop body has done break — the iterator must stop.

go
func countdown(n int) func(func(int) bool) {	return func(yield func(int) bool) {		for i := n; i > 0; i-- {			if !yield(i) {				return			}		}	}} func main() {	// prints 3, 2, 1	for i := range countdown(3) {		fmt.Println(i)	}}

switch and defer

switch executes the first matching branch and exits — break is not needed; to fall through to the next branch, write fallthrough. A case can list several values, and a switch without an expression replaces a chain of if-else statements.

go
switch runtime.GOOS {case "linux", "freebsd":	fmt.Println("unix-like")case "windows":	fmt.Println("windows")default:	fmt.Println("other")} switch {case code >= 500:	return "server error"case code >= 400:	return "client error"}

defer postpones a call until the function exits — via return, the end of the body or a panic. The arguments of a deferred call are evaluated at once, while the calls themselves run in reverse order: the last deferred is the first executed.

go
func readConfig(path string) ([]byte, error) {	f, err := os.Open(path)	if err != nil {		return nil, err	}	// the file is closed on any exit from the function	defer f.Close()	return io.ReadAll(f)}
go
// prints 2 1 0 when the function exitsfor i := range 3 {	defer fmt.Print(i, " ")}

Formatting: gofmt

Go has a single code style for everyone: gofmt sets indentation with tabs and aligns columns, and all standard library code is formatted with it. go fmt runs gofmt for packages; run it before every commit, and settle a contentious case the way gofmt would format it.

bashin the module directory
# format every package of the modulego fmt ./...

Section sources

the section is written from these pages

Types, slices, maps and structs

Go types fall into basic ones — numbers, strings, bool — and composite: arrays, slices, maps, structs, pointers, functions, interfaces and channels. Most often you work with slices and maps: a slice is a window onto an array, a map is a “key → value” table.

Basic types and conversions

TypeWhat it holds
booltrue or false
int, uintan integer, 32 or 64 bits — depends on the platform
int8 … int64, uint8 … uint64fixed-size integers
float32, float64IEEE 754 floating-point numbers
stringan immutable sequence of bytes, usually UTF-8 text
byte, runealiases of uint8 and int32: a byte and a Unicode code point

There is no implicit conversion between numeric types: int and int64 are distinct types even when their size matches. When mixing types, convert explicitly — T(x). len of a string returns the number of bytes, not characters.

gomain.go
package main import "fmt" func main() {	n := 10	// int and float64 do not mix without a conversion	avg := float64(n) / 3	s := "привет"	// 12 bytes, but 6 characters	fmt.Println(len(s), len([]rune(s)))	fmt.Printf("%.2f\n", avg)}

Arrays and slices

An array [4]int has a fixed length, and that length is part of its type; assigning an array copies all of its elements. A slice []int is a descriptor over an array: a pointer to the first element, the length len and the capacity cap — how many elements fit up to the end of the array.

Several slices may look at the same array, and a write through one slice is visible through the others. append adds to the same array while there is capacity to spare, and when there is not, it allocates a new array and copies the elements into it. That is why the result of append is always assigned back: s = append(s, x).

The state after b[0] = 99 and c := append(a, 1, 2, 3).
gomain.go
package main import "fmt" func main() {	arr := [6]int{10, 20, 30, 40, 50, 60}	a := arr[1:4]	b := a[1:3]	b[0] = 99	fmt.Println(a, len(a), cap(a))	fmt.Println(b, len(b), cap(b))	// there is not enough capacity: a new array, arr is unchanged	c := append(a, 1, 2, 3)	c[0] = 0	fmt.Println(arr, c)}
textexample output
[20 99 40] 3 5[99 40] 2 4[10 20 99 40 50 60] [0 99 40 1 2 3]

map

A map is an unordered “key → value” table. Any type for which == is defined can serve as the key: numbers, strings, pointers, structs and arrays of comparable elements — but not slices, maps or functions. Reading a missing key returns the zero value, so key presence is checked with a second variable, ok.

go
stock := map[string]int{"apple": 5}stock["pear"] = 3 if n, ok := stock["plum"]; !ok {	fmt.Println("out of stock:", n)}delete(stock, "apple")fmt.Println(len(stock))

Structs and embedding

A struct groups named fields. In a literal with field names (User{ID: 1}) the order is arbitrary, and omitted fields get their zero values. A field without a name is embedding: the fields and methods of the embedded type become available directly, as if they were its own.

go
type Timestamps struct {	CreatedAt time.Time} type User struct {	ID    int64  `json:"id"`	Name  string `json:"name"`	Email string `json:"email,omitempty"`	Timestamps} func newUser(name string) User {	u := User{ID: 1, Name: name}	// a field of the embedded struct is available directly	u.CreatedAt = time.Now()	return u}

A backquoted string after a field’s type is a tag. The compiler does not check it; libraries read it through reflection: encoding/json takes the JSON key name from json:"id".

Pointers and methods

A pointer *T holds the address of a value: &x takes the address, *p is the value at that address. Memory is reclaimed by the garbage collector, so returning the address of a local variable from a function is safe.

A method is a function with a receiver. A value receiver gets a copy, and the caller will not see changes made inside the method; a pointer receiver modifies the original value. Methods with a value receiver are callable on both values and pointers, those with a pointer receiver — only on pointers; on a variable the compiler will insert the & itself.

go
type Counter struct {	hits int} // pointer receiver: the method modifies the fieldfunc (c *Counter) Inc() {	c.hits++} // value receiver: the method only readsfunc (c Counter) Hits() int {	return c.hits} func main() {	var c Counter	c.Inc()	c.Inc()	fmt.Println(c.Hits())}

The slices and maps packages

Generic functions for slices and maps live in the standard library packages slices and maps. The sorting and min/max functions take elements with an ordering — the types of the cmp.Ordered constraint.

TaskFunction
Sort a sliceslices.Sort(s)
Sort with your own ruleslices.SortFunc(users, byAge)
Is an element presentslices.Contains(s, "go")
Index of an element, or −1slices.Index(s, "go")
Minimum and maximumslices.Min(s), slices.Max(s)
An independent copyslices.Clone(s)
Compare two slicesslices.Equal(a, b)
Delete elements from i to j-1s = slices.Delete(s, i, j)
Map keys in orderslices.Sorted(maps.Keys(m))
A copy of a mapmaps.Clone(m)
Compare two mapsmaps.Equal(m1, m2)

Section sources

the section is written from these pages

Interfaces and generics

An interface is a type that defines a set of methods; any type with those methods implements the interface automatically, with no implements keyword. Generics solve a different problem: one function or type works with many types, substituted in place of a type parameter.

The link between a type and an interface is established by the set of methods. A type File with Read and Write methods fits both io.Reader and io.Writer, even though neither interface is mentioned in its declaration. This is how one type implements several interfaces at once.

gomain.go
package main import (	"bytes"	"fmt"	"io"	"os") // Upper writes text to w in capital letterstype Upper struct {	w io.Writer} func (u Upper) Write(p []byte) (int, error) {	if _, err := u.w.Write(bytes.ToUpper(p)); err != nil {		return 0, err	}	return len(p), nil} func main() {	// Upper is an io.Writer: it has a Write method	var w io.Writer = Upper{w: os.Stdout}	fmt.Fprintln(w, "hello, gopher")}

Small interfaces of the standard library

InterfaceMethodWhere it is used
io.ReaderRead(p []byte) (n int, err error)files, network connections, HTTP request bodies
io.WriterWrite(p []byte) (n int, err error)files, os.Stdout, http.ResponseWriter
fmt.StringerString() stringhow fmt.Println and %v print a value
errorError() stringany error

Interfaces with one or two methods are common in Go: the fewer the methods, the more types fit. Larger interfaces are built from small ones by embedding: io.ReadWriter is io.Reader and io.Writer combined.

Type assertion: v.(T) and switch

The type assertion v.(T) extracts the concrete value from an interface. If v holds a different type, the single-value form panics, while the two-result form does not: ok is false and the value is the zero value. Several alternatives are handled with a switch x := v.(type) statement.

go
func describe(v any) string {	switch x := v.(type) {	case nil:		return "nil"	case int:		return "int " + strconv.Itoa(x)	case string:		return "string " + strconv.Quote(x)	case fmt.Stringer:		return "Stringer " + x.String()	default:		return fmt.Sprintf("other %T", x)	}}
go
if s, ok := v.(fmt.Stringer); ok {	fmt.Println(s.String())}

An interface value with nil inside is not equal to nil

An interface value stores a pair: a type and a value. It equals nil only when both parts are empty. If a nil pointer of type *ValidationError is returned through error, the type is already recorded, and the caller’s err != nil check fires even though there was no error.

gowrong
func validate(name string) error {	var err *ValidationError	if name == "" {		err = &ValidationError{Field: "name"}	}	// always not nil: the type inside is *ValidationError	return err}
gocorrect
func validate(name string) error {	if name == "" {		return &ValidationError{Field: "name"}	}	return nil}

Declare a function’s result as the type error and return nil explicitly.

Generics: type parameters

Type parameters are written in square brackets after the name of a function or type. Each has a type constraint — an interface that defines the permitted types. The built-in comparable admits types that support the == and != operators, while the union ~int | ~float64 admits the listed types and types based on them.

gomain.go
package main import "fmt" // Number is a constraint: integers and floating-point numberstype Number interface {	~int | ~int64 | ~float64} // Sum adds up the values of a map with any key typefunc Sum[K comparable, V Number](m map[K]V) V {	var total V	for _, v := range m {		total += v	}	return total} func main() {	prices := map[string]float64{"tea": 1.5, "cake": 3}	// K and V were inferred from the argument	fmt.Println(Sum(prices))}

Type arguments are usually omitted: the compiler infers them from the function arguments. They are written out explicitly when there is nothing to infer them from: Sum[string, int](nil).

Generic methods (since Go 1.27)

Since Go 1.27 a method can declare its own type parameters — previously they could only be taken from the receiver type. Like a generic function, such a method is instantiated before the call, usually implicitly through type inference. Interface methods cannot declare type parameters.

go
type List[E any] []E // Map is a generic method with its own parameter Ffunc (l List[E]) Map[F any](f func(E) F) List[F] {	out := make(List[F], 0, len(l))	for _, x := range l {		out = append(out, f(x))	}	return out} func main() {	stars := List[int]{1, 2, 3}.Map(func(n int) string {		return strings.Repeat("*", n)	})	// [* ** ***]	fmt.Println(stars)}

Section sources

the section is written from these pages

Errors and panic

In Go, an error is an ordinary value of type error that a function returns as its last result; the caller checks it immediately with if err != nil. The panic and recover mechanism is reserved for impossible states, not for everyday failures such as a missing file.

go
func readPort(path string) (int, error) {	data, err := os.ReadFile(path)	if err != nil {		return 0, fmt.Errorf("read port: %w", err)	}	s := strings.TrimSpace(string(data))	port, err := strconv.Atoi(s)	if err != nil {		return 0, fmt.Errorf("parse port %q: %w", s, err)	}	return port, nil}

The error type is an interface with a single method, Error() string. errors.New creates an error with a message, and fmt.Errorf with the verb %w wraps the original error and adds context. The result is a chain that reads well in a log: read port: open port.txt: no such file or directory.

Checking errors: errors.Is and errors.As

Comparing errors with == is unreliable: after wrapping, the original error sits somewhere inside the chain. errors.Is searches the chain for a specific value, while errors.As, and from Go 1.26 the type-safe errors.AsType, finds an error of a given type.

go
_, err := readPort("port.txt")if errors.Is(err, fs.ErrNotExist) {	fmt.Println("no file, using the default port")}if pe, ok := errors.AsType[*fs.PathError](err); ok {	fmt.Println("failed path:", pe.Path)}

errors.Join combines several errors into one, and errors.Is finds each of them. This makes it easy to return every validation error from a form at once, rather than only the first.

go
func validate(u User) error {	var errs []error	if u.Name == "" {		errs = append(errs, errors.New("name is empty"))	}	if u.Age < 0 {		errs = append(errs, errors.New("age is negative"))	}	// nil if no errors accumulated	return errors.Join(errs...)}

Sentinel errors and custom types

A sentinel error is a pre-created value that signals an expected outcome. The classic example is io.EOF: Read returns it when the data runs out, and that is not a failure. Sentinel errors in the standard library are named with the prefix Err: fs.ErrNotExist, io.ErrUnexpectedEOF.

go
var ErrNotFound = errors.New("user not found") type ValidationError struct {	Field string} func (e *ValidationError) Error() string {	return "invalid field " + e.Field}

A custom error type is worth defining when the caller needs details — the field, code or path, as with *fs.PathError and its Op and Path fields. Return such errors as the error type and extract the details with errors.AsType.

Don’t ignore err

Assigning the blank identifier _ in place of the error hides the failure: the program keeps going on a zero value and breaks later, far from the cause.

gowrong
port, _ := strconv.Atoi(os.Getenv("PORT"))
gocorrect
port, err := strconv.Atoi(os.Getenv("PORT"))if err != nil {	return fmt.Errorf("PORT: %w", err)}

In the first version, an empty or invalid PORT silently becomes port 0.

panic and recover

panic stops the current function and unwinds the goroutine’s stack, running deferred calls along the way. If the panic is still not handled at the top of the stack, the program exits and prints the panic value and the stack trace. Panics can also be implicit: run-time errors such as a slice index out of range or a call through a nil pointer.

A panic can be caught only in a deferred function: recover returns the panic value and returns the goroutine to normal operation. This is how a server keeps one failing handler from bringing down the whole process.

go
func safely(job func()) (err error) {	defer func() {		if r := recover(); r != nil {			err = fmt.Errorf("panic: %v", r)		}	}()	job()	return nil}

Section sources

the section is written from these pages

Modules and packages

A module is a set of packages that are released and versioned together; its root is marked by a go.mod file with the module path and its dependencies. A package is a directory of .go files, and a package’s import path is the module path plus the subdirectory: example.com/shop/internal/order.

textgo.mod
module example.com/shop go 1.27.0 require (    example.com/payments v1.4.2    example.com/retry v0.3.1 // indirect)
LineWhat it means
modulethe module path — the import prefix for its packages
gothe minimum Go version and the language version for the module’s code
toolchainthe recommended toolchain; used if it is newer than the installed Go
requireminimum versions of dependencies; // indirect marks a module whose packages the module’s own code does not import directly
replacesubstitute a module version with another one or with a local directory
retractretract your own published versions, for example ones with a bug

Next to it sits go.sum — cryptographic hashes of every dependency version that is needed. The go command checks downloaded files against it and reports a security error on a mismatch. Keep go.mod and go.sum in the repository; they are usually changed not by hand but with the go get and go mod tidy commands.

Dependencies: go get and go mod tidy

bashin the module directory
# add a dependency or change its versiongo get example.com/payments@v1.4.2# upgrade to the latest versiongo get example.com/payments@latest# remove a dependencygo get example.com/payments@none# reconcile go.mod and go.sum with the imports in the codego mod tidy

go get edits the require lines, and go mod tidy brings the files in line with the code: it adds the missing modules and go.sum entries and removes the ones no longer needed. Run go mod tidy after you add or remove imports.

Each dependency version is chosen by minimal version selection (MVS): from all the requirements in the module graph it takes the greatest of the minimum required versions. New dependency releases do not change the build by themselves, so a lock file is not needed. The resulting list of modules is shown by go list -m all.

Major versions: /v2 in the path

From v2 on, the module path carries a major version suffix: example.com/mod/v2. The packages of a new major version are incompatible with the old one, so they have a different import path, and both versions can live in one build. Versions v0 and v1 carry no suffix.

bashin the module directory
go get example.com/mod/v2@v2.1.0

Proxies, checksums and private modules

By default, modules are downloaded through the proxy.golang.org mirror, and their hashes are checked against the checksum database sum.golang.org: GOPROXY=https://proxy.golang.org,direct, GOSUMDB=sum.golang.org. For closed-source code, set GOPRIVATE: such modules are downloaded straight from the repository and are not checked against the public database.

bashin a terminal
go env -w GOPRIVATE=git.example.comgo env GOPROXY GOSUMDB GOPRIVATE

Module layout: cmd and internal

A package from an internal directory can be imported only by code in the subtree of that internal’s parent. This is how you hide what must not become a public API. Executable programs go in separate directories inside cmd, and the service logic goes in internal.

textmodule tree
shop/├── go.mod├── cmd/│   ├── api/│   │   └── main.go│   └── migrate/│       └── main.go└── internal/    ├── order/    │   └── order.go    └── storage/        └── storage.go

Each program is built separately: go build ./cmd/api. If packages from the module become useful to other projects, move them out into a module of their own.

Section sources

the section is written from these pages

Goroutines and channels

A goroutine is a function that runs concurrently with others in the same address space; the go statement starts one. Data is passed between goroutines through channels or protected with the sync package: don’t communicate by sharing memory; share memory by communicating.

Goroutines are cheap: each starts with a small stack that grows as needed, and the runtime schedules goroutines onto OS threads. When one blocks on I/O, the others keep running.

gomain.go
package main import (	"fmt"	"time") func main() {	done := make(chan string)	go func() {		time.Sleep(100 * time.Millisecond)		done <- "done"	}()	// main waits until the goroutine sends a value	fmt.Println(<-done)}

Channels

A channel carries values between goroutines. In an unbuffered channel, a send waits for a receiver, so the transfer also synchronises the goroutines; in a buffered channel, a send blocks only when the buffer is full. The sender closes the channel: close(ch) signals that no more values will arrive, and the for v := range ch loop then ends.

Operationnil channelOpen channelClosed channel
Send ch <- vblocks foreverwaits for a receiver or for room in the bufferpanic
Receive v, ok := <-chblocks foreverwaits for a valuethe rest of the buffer, then the zero value and ok == false right away
close(ch)paniccloses the channelpanic

select and timeouts

select waits on several channel operations at once and runs the first one that is ready; if several are ready, it chooses at random. A default branch makes select non-blocking, and a time.After channel or ctx.Done() bounds the wait.

go
select {case res := <-results:	fmt.Println(res)case <-time.After(2 * time.Second):	fmt.Println("timeout")case <-ctx.Done():	return ctx.Err()}

WaitGroup, Mutex and Once

sync.WaitGroup waits for a group of goroutines to finish. Since Go 1.25, the wg.Go(f) method runs f in a new goroutine and maintains the counter itself; in older code, wg.Add(1) and defer wg.Done() do the same.

sync.Mutex protects data that several goroutines access: between Lock and Unlock, only one goroutine works with it. sync.Once runs a function exactly once, no matter how many goroutines call it. Values of these types must not be copied after first use — pass them by pointer.

gomain.go
package main import (	"fmt"	"sync") type Counter struct {	mu   sync.Mutex	hits map[string]int} func (c *Counter) Inc(key string) {	c.mu.Lock()	defer c.mu.Unlock()	c.hits[key]++} func main() {	c := &Counter{hits: map[string]int{}}	var wg sync.WaitGroup	for range 100 {		wg.Go(func() {			c.Inc("home")		})	}	wg.Wait()	fmt.Println(c.hits["home"])}

context: cancellation and deadlines

context.Context carries a cancellation signal and a deadline down the call chain. The server creates a context for each request, and functions that wait on the network or disk take it as their first parameter, ctx. When the context is cancelled or the deadline has passed, the ctx.Done() channel closes, and ctx.Err() returns context.Canceled or context.DeadlineExceeded.

go
func fetch(ctx context.Context, url string) ([]byte, error) {	ctx, cancel := context.WithTimeout(ctx, 3*time.Second)	// cancel releases the timer on every exit path	defer cancel()	req, err := http.NewRequestWithContext(ctx,		http.MethodGet, url, nil)	if err != nil {		return nil, err	}	resp, err := http.DefaultClient.Do(req)	if err != nil {		return nil, err	}	defer resp.Body.Close()	return io.ReadAll(resp.Body)}

Data races and the -race detector

A data race means two goroutines access the same variable at the same time and at least one of the accesses is a write. The Go memory model requires that such access be ordered through channels or through sync and sync/atomic. A race-free program behaves as if the goroutines took turns on a single processor.

bashin the module directory
go test -race ./...go run -race .

The detector only finds races that actually happen during a run, so run your tests with it regularly and keep coverage good. Under the detector a program typically uses 5–10 times more memory and takes 2–20 times longer.

The worker pool pattern

A typical task is to process many jobs with a fixed number of goroutines. Jobs travel through a jobs channel and results through results. When all the workers have finished, a separate goroutine closes results, and the range loop in main ends.

  1. Create the jobs and results channels.
  2. Start the workers with wg.Go: each reads jobs in a range loop until the channel is closed.
  3. The sender puts jobs into jobs and closes it.
  4. A separate goroutine waits on wg.Wait() and closes results.
  5. main reads results in a range loop until it is closed.
gomain.go
package main import (	"fmt"	"sync") func main() {	jobs := make(chan int)	results := make(chan int)	var wg sync.WaitGroup	for range 3 {		wg.Go(func() {			for n := range jobs {				results <- n * n			}		})	}	go func() {		for n := 1; n <= 9; n++ {			jobs <- n		}		close(jobs)	}()	go func() {		wg.Wait()		close(results)	}()	sum := 0	for r := range results {		sum += r	}	// 285 — sum of squares of 1 to 9	fmt.Println(sum)}

Section sources

the section is written from these pages

Testing

Tests in Go are written in Go itself: the go test command runs TestXxx(t *testing.T) functions in *_test.go files. A separate framework isn’t needed — the testing package includes subtests, benchmarks, fuzzing and examples.

goreverse.go
package strutil // Reverse reverses a string rune by runefunc Reverse(s string) string {	r := []rune(s)	for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {		r[i], r[j] = r[j], r[i]	}	return string(r)}
goreverse_test.go
package strutil import "testing" func TestReverse(t *testing.T) {	got := Reverse("abc")	if got != "cba" {		t.Errorf("Reverse(%q) = %q, want %q", "abc", got, "cba")	}}

t.Errorf marks the test as failed and keeps it running; t.Fatal and t.Fatalf stop the current test. The test file can live in the same package, in which case it sees unexported names. A test in a package with the _test suffix sees the package the same way external code does.

Table-driven tests and t.Run

goreverse_test.go
func TestReverseTable(t *testing.T) {	tests := []struct {		name, in, want string	}{		{"ascii", "abc", "cba"},		{"cyrillic", "привет", "тевирп"},		{"empty", "", ""},	}	for _, tt := range tests {		t.Run(tt.name, func(t *testing.T) {			if got := Reverse(tt.in); got != tt.want {				t.Errorf("Reverse(%q) = %q, want %q",					tt.in, got, tt.want)			}		})	}}

Each row of the table is a subtest with its own name. A failing one shows up as TestReverseTable/cyrillic, and you can run just that one with the flag -run 'TestReverseTable/cyrillic'.

Running go test

bashin the module directory
go test ./...go test -v -run 'TestReverseTable/cyrillic' ./strutilgo test -cover ./...go test -race -count=1 ./...
FlagWhat it doesDefault
-run regexponly tests, examples and fuzz tests whose name matches the expressionall
-vverbose output, including t.Log from passing testsoff
-coverthe share of code covered by testsoff
-racetests run with the race detectoroff
-count nrun each test n times; -count=1 bypasses the cache1
-bench regexpbenchmarks whose name matchesnot run
-timeout dpanic if the test binary runs longer than d10m

In package list mode (go test ./...), successful results are cached: rerunning without changes prints (cached). Before the tests, go test runs a subset of the go vet checks and refuses to run the tests if they find a problem.

Benchmarks and fuzzing

goreverse_test.go
func BenchmarkReverse(b *testing.B) {	for b.Loop() {		Reverse("hello, gopher")	}}

Since Go 1.24, benchmarks are written with b.Loop(): only the loop body is measured, and setup before it stays out of the measurement. To run them, use go test -bench . -benchmem; the second flag adds memory allocation statistics.

goreverse_test.go
func FuzzReverse(f *testing.F) {	f.Add("hello")	f.Fuzz(func(t *testing.T, s string) {		if !utf8.ValidString(s) {			t.Skip("not UTF-8")		}		if got := Reverse(Reverse(s)); got != s {			t.Errorf("double reverse of %q = %q", s, got)		}	})}

A fuzz target FuzzXxx calls the function with randomly mutated inputs from the seed corpus (f.Add). Without the flag it only runs the corpus, like an ordinary test. With the -fuzz flag it looks for new inputs, and an input that makes the test fail is saved to testdata/fuzz/FuzzReverse — from then on that input is checked on every run.

bashin the module directory
go test -fuzz=FuzzReverse -fuzztime=30s ./strutil

Examples as documentation

An ExampleXxx function is both a test and an example in the package documentation: go test runs it and compares its output with the // Output: comment. Without such a comment the example is only compiled.

goexample_test.go
func ExampleReverse() {	fmt.Println(Reverse("gopher"))	// Output: rehpog}

httptest and synctest

PackageWhat it’s for
net/http/httptestNewRecorder records a handler’s response without the network; NewServer starts a test server on a local address, and since Go 1.27 NewTestServer — a server on a fake in-memory network that closes itself at the end of the test
testing/synctest (since Go 1.25)synctest.Test runs the test in an isolated “bubble” with a fake clock: time.Sleep completes instantly, and synctest.Wait waits until all goroutines in the bubble are blocked
gohandler_test.go
func TestHealth(t *testing.T) {	req := httptest.NewRequest(http.MethodGet, "/health", nil)	rec := httptest.NewRecorder()	healthHandler(rec, req)	if rec.Code != http.StatusOK {		t.Fatalf("status = %d, want 200", rec.Code)	}}

Section sources

the section is written from these pages

Standard library

For the typical jobs of a service — HTTP, JSON, logs, files and time — the Go standard library has ready-made packages. The table shows which package to start from; every example in this section builds without third-party modules.

TaskPackage
HTTP server and client, routes with a method and path parametersnet/http
JSONencoding/json/v2 (from Go 1.27); in code for Go 1.26 — encoding/json
Files, environment variables, program argumentsos; general I/O interfaces — io
Reading line by line and bufferingbufio
File paths by the rules of the current OSpath/filepath
Structured logslog/slog
Time, durations, timerstime
Strings and conversion to numbersstrings, strconv
Command-line flagsflag
UUIDuuid (from Go 1.27)

HTTP server with a GET /items/{id} route

From Go 1.22, a route pattern in http.ServeMux can carry a method and path parameters: GET /items/{id}. r.PathValue("id") returns the parameter value, and a pattern with GET also matches HEAD requests.

gomain.go
package main import (	"fmt"	"log/slog"	"net/http"	"os"	"time") func getItem(w http.ResponseWriter, r *http.Request) {	fmt.Fprintf(w, "item %s\n", r.PathValue("id"))} func main() {	mux := http.NewServeMux()	mux.HandleFunc("GET /items/{id}", getItem)	srv := &http.Server{		Addr:              ":8080",		Handler:           mux,		ReadHeaderTimeout: 5 * time.Second,	}	slog.Info("listening", "addr", srv.Addr)	if err := srv.ListenAndServe(); err != nil {		slog.Error("server stopped", "err", err)		os.Exit(1)	}}
bashin a second terminal
curl localhost:8080/items/42
textexample output
item 42

Give the server timeouts: if ReadTimeout and ReadHeaderTimeout are not set, there is no limit on reading a request, and a slow client can hold a connection for as long as it likes. ListenAndServe always returns an error; after Shutdown or Close it is http.ErrServerClosed.

Reading JSON into a struct

encoding/json/v2 (from Go 1.27) reads JSON straight from an io.Reader, for example a request body. By default it is stricter than the old package: it matches field names case-sensitively, rejects invalid UTF-8 and duplicate names. It skips unknown fields; to reject them, set the option json.RejectUnknownMembers(true).

gowith encoding/json/v2
type CreateItem struct {	Name  string `json:"name"`	Price int    `json:"price"`} func createItem(w http.ResponseWriter, r *http.Request) {	// at most 1 MiB of the request body	body := http.MaxBytesReader(w, r.Body, 1<<20)	var in CreateItem	err := json.UnmarshalRead(body, &in,		json.RejectUnknownMembers(true))	if err != nil {		http.Error(w, err.Error(), http.StatusBadRequest)		return	}	w.Header().Set("Content-Type", "application/json")	w.WriteHeader(http.StatusCreated)	if err := json.MarshalWrite(w, in); err != nil {		slog.Error("write response", "err", err)	}}

Structured logging with slog

log/slog writes the log as key–value pairs: slog.NewJSONHandler prints one JSON line per record, slog.NewTextHandler — key=value pairs. After slog.SetDefault, the slog.Info family of functions and the old log package all log through this logger.

go
opts := &slog.HandlerOptions{Level: slog.LevelDebug}logger := slog.New(slog.NewJSONHandler(os.Stdout, opts))slog.SetDefault(logger) slog.Info("order created", "id", 42, "total", 990)// With adds fields to every record of the loggerreqLog := logger.With("req", "f3a1")reqLog.Warn("slow query", "ms", 870)
textexample output
{"time":"...","level":"INFO","msg":"order created","id":42,"total":990}{"time":"...","level":"WARN","msg":"slow query","req":"f3a1","ms":870}

UUID

The uuid package (from Go 1.27) creates and parses UUIDs. uuid.New() returns a random version 4 UUID, and uuid.NewV7() a UUID with a timestamp. These sort in ascending order unless the system clock is set back, which makes them handy as database keys.

go
func example() error {	id := uuid.NewV7()	fmt.Println(id.String()) 	parsed, err := uuid.Parse(id.String())	if err != nil {		return err	}	// a UUID is an array of 16 bytes; they compare with ==	fmt.Println(parsed == id)	return nil}

Section sources

the section is written from these pages

Common errors and diagnostics

Start with go build ./... and go vet ./...: the compiler and vet catch most errors before the program runs. If the program crashes, read the first panic line and the stack below it — that is the file and line where it happened.

Order of checks

  1. go build ./... — syntax, types, unused imports and variables.
  2. go vet ./... — suspicious code that compiles but is almost certainly wrong.
  3. go test -race ./... — data races during test runs.
  4. On a panic — its value and stack: by default the stack of the current goroutine is printed, GOTRACEBACK=all adds the stacks of all user goroutines; the exit code is 2.
bashin the module directory
go build ./... && go vet ./...GOTRACEBACK=all go run .

Build fails on an unused variable or import

Cause: Go refuses to build a program with unused variables and imports — this is a compile-time error, not a warning. The Go compiler never issues warnings: only errors that stop the build.

bashin the module directory
go build ./...
  • Remove the unused code or start using the value.
  • While debugging, assign the value to the blank identifier: _ = debugData.
  • Let the editor with gopls or goimports manage imports — they add and remove them automatically.

The go command cannot find go.mod

Cause: go build, go test and other commands operate in the context of the main module — the go.mod file in the current directory or one of its parents. Without it, only standard library packages and .go files listed on the command line can be built.

bashin the project directory
# create the module or change into its directorygo mod init example.com/app

A go.sum entry is missing

Cause: the dependency appears in the code or in go.mod, but its hash is missing from go.sum — for example, after a manual edit of go.mod or a branch merge. Without the hash, the go command cannot verify the downloaded module.

bashin the module directory
go mod tidygit diff go.mod go.sum

Panic on nil access

Cause: dereferencing a nil pointer, accessing a field through it, calling a method on a nil interface and writing to a nil map are run-time errors — they panic. Most often the pointer is still nil because the function’s error was never checked.

go
// writing to a nil map panics; create it with make firstcounts := make(map[string]int)counts["go"]++
  • Find the first line from your own code in the stack — that is where the value was nil.
  • Check err before using a function’s result.
  • Create maps with make or a composite literal before the first write.

A goroutine blocks on a channel forever

Cause: a goroutine receives from a channel nobody writes to, or sends on a channel with no receiver, and the program hangs. On an unbuffered channel a send waits for a receiver, and operations on a nil channel — as well as a select with only nil channels and no default — block forever.

gowrong
ch := make(chan int)// the send waits for a receiver, and the only reader is this same mainch <- 1fmt.Println(<-ch)
gocorrect
ch := make(chan int, 1)ch <- 1fmt.Println(<-ch)
  • Every receive must have a sender, and a channel read via range must be closed by someone.
  • Bound the wait: select with ctx.Done() or time.After.

WARNING: DATA RACE

Cause: two goroutines access the same variable at the same time and at least one of them writes. The report is printed by the race detector: stacks of both accesses and the places where the goroutines were created. Concurrent writes to a plain map are doubly dangerous — unsynchronised access can crash the program.

bashin the module directory
go test -race ./...
  • Guard shared data with a sync.Mutex or pass it over a channel.
  • For a read-mostly cache, sync.Map is a good fit.
  • Run -race in CI regularly: the detector only sees races that actually happen during a run.

err != nil although the function returned a nil pointer

Cause: the function returned a typed nil pointer, such as *MyError, through the error interface. The interface value carries a type, so the interface itself is not equal to nil.

go
// prints the type stored in the interface and the comparison with nilfmt.Printf("%T %v\n", err, err == nil)
  • Return nil explicitly, not a variable of a concrete type holding a nil value.
  • Declare the function’s result as the error type, not *MyError.

Section sources

the section is written from these pages

Versions and what’s new

This reference describes Go 1.27. The latest release is 1.27.3, dated 19 October 2026. Major releases come out every six months, in February and August, and each is supported until two more have been released: currently 1.27 and 1.26.

BranchStatusLatest releaseSupported until
1.27supported, covered here1.27.3, 19 October 2026release of 1.29
1.26supported1.26.10, 19 October 2026release of 1.28
1.25no longer supported1.25.14, 19 August 202619 August 2026, release of 1.27.0

Fixes, including security fixes, arrive in minor releases 1.N.x. Upgrade freely within a branch: the Go 1 compatibility promise still holds, and almost all programs build and run as before.

What changed in 1.27

  • Interfaces and generics: generic methods — a method may declare its own type parameters, for example func (l List[E]) Map[F any](f func(E) F) List[F]. Interface methods do not declare type parameters, and a generic method cannot implement an interface method.
  • Standard library: the encoding/json/v2 package with the Marshal, Unmarshal, MarshalWrite and UnmarshalRead functions and strict defaults. The old encoding/json now works on top of the new implementation and remains supported, but its error messages may differ.
  • Standard library: the uuid package for creating and parsing UUIDs, and the strings.CutLast and bytes.CutLast functions.
  • Cheat sheet: go fix gains the new modernizers atomictypes, embedlit, slicesbackward and unsafefuncs; the waitgroup analyser is renamed to waitgroupgo
  • Testing: go test runs the stdversion check by default — it reports standard library functions newer than the version in the go line; httptest.NewTestServer and synctest.Sleep simplify tests with a fake network and fake time.
  • Goroutines and channels: the goroutine leak profile goroutineleak is no longer experimental — it is available in runtime/pprof and at /debug/pprof/goroutineleak in net/http/pprof
  • Errors and panics: go vet warns about fmt.Errorf("...: %w", p) where p is a pointer to a type that itself implements error: such wrapping breaks errors.Is checks.
  • Installation and first run: macOS 13 Ventura or later is required.

Deprecated and removed

  • The go command no longer supports Bazaar: modules are no longer downloaded directly from bzr servers.
  • The GODEBUG settings asynctimerchan, tlsunsafeekm, tlsrsakex, tls3des, tls10server, x509keypairleaf and gotypesalias have been removed. If such a setting is set to its old value in go.mod or in //go:debug, the go command fails with an error.
  • Channels from the time package are now always unbuffered, regardless of GODEBUG
  • tls.Config.Rand is deprecated: use testing/cryptotest.SetGlobalRandom for deterministic tests.
  • The old encoding/json implementation can still be brought back by building with GOEXPERIMENT=nojsonv2; this setting will be removed in one of the upcoming releases.

Security updates

Check your code and dependencies with govulncheck: it reports only the vulnerabilities that calls from your code actually reach.

bashin the module directory
go install golang.org/x/vuln/cmd/govulncheck@latestgovulncheck ./...
IdentifierWhat is affectedFixed in
CVE-2026-111943crypto/x509: Certificate.Verify accepted intermediate certificates that can no longer be trusted1.27.3, 1.26.10
CVE-2026-94439net/http: after a 2xx response to an HTTP/1 CONNECT the server kept reading requests from the connection — a request smuggling risk1.27.2, 1.26.9
CVE-2026-78667net/http: a Range header with many small ranges overloaded the CPU in FileServer, ServeContent and ServeFile1.27.2, 1.26.9
CVE-2026-94440mime/multipart, net/textproto: parsing a multipart form could bypass the memory limit1.27.2, 1.26.9
CVE-2026-97031crypto/tls: repeated references to external ECH extensions could exhaust server memory1.27.2, 1.26.9
CVE-2026-94447the go command: a forged golang.org/toolchain entry in go.sum, together with a malicious proxy, bypassed checksum verification1.27.2, 1.26.9
CVE-2026-97030, CVE-2026-94448html/template: incorrect escaping of yield and of expressions in JavaScript template literals1.27.2, 1.26.9
CVE-2026-97032net/http, HTTP/2: a client could crash the server by changing the header table size during responses1.26.9; 1.27 not affected
CVE-2026-78669net/http, HTTP/2: many streams and small SETTINGS frames overloaded the CPU1.26.9; 1.27 not affected
CVE-2026-56864the go command: a malicious GOSUMDB database could serve code that is missing from the transparency log1.27.0, 1.26.6

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 4 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Manual edit

    reason: manual edit
  4. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

18 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Go” topic
13 sections
Another reference · Backend

Python

Verified 31 Oct
All references · 61