Skip to content
Tutorials Center
My learning

Topics

Lesson 141 of 147 ยท Practice and Review

Go Cheat Sheet

A one-page Go cheat sheet: syntax, types, control flow, slices, maps, structs, interfaces, generics, errors, goroutines, go commands and fmt verbs.

This page is a compact reference for Go 1.27: the syntax and the standard library features you use every day, in one place. It is not a tutorial. Each section links to the lesson that explains the topic in depth, and the trickiest items have a small program you can run and change. Code blocks without a Run button are read-only snippets, mostly fragments that you place inside a function or a file.

Bookmark it, and use the search box (Ctrl+K) for anything that is not here. If you want to see these features working together, try the 50 classic programs, the practice exercises or one of the projects.

Program structure

Getting Started, Syntax, Packages

Go
package main // every file starts with its package; "main" builds a program

import (
	"fmt"
	"os"
)

func main() { // the entry point: no arguments, no result
	fmt.Println("hello")
	if len(os.Args) > 1 {
		os.Exit(1) // exits at once: deferred calls do NOT run
	}
}
  • A name that starts with a capital letter is exported (visible to other packages). Everything else is private to its package.
  • Statements end at the line end (the compiler inserts semicolons). An opening { must stay on the line of its if, for or func.
  • Unused variables and unused imports are compile errors. Use _ to ignore a value: _, err := f().
  • gofmt formats code with tabs. Comments: // line and /* block */. A comment right above a declaration is its doc comment.

Variables and constants

Variables, Constants and iota

Go
var count int              // zero value: 0
var name, age = "Ada", 36  // types inferred
total := 0                 // short declaration; only inside functions
a, b := 1, 2
a, b = b, a                // swap

const Pi = 3.14159         // untyped constant
const (
	Sunday = iota // 0
	Monday        // 1
	Tuesday       // 2
)
const (
	_  = iota             // skip 0
	KB = 1 << (10 * iota) // 1024
	MB                    // 1048576
)
Type Zero value
numbers (int, float64, ...) 0
bool false
string "" (empty string)
pointer, slice, map, channel, function, interface nil
struct, array every field or element at its zero value

Basic types and conversion

Basic Types, Numbers, Type Conversion

Group Types
Boolean bool
Integers int, int8, int16, int32, int64; uint, uint8 ... uint64, uintptr
Aliases byte = uint8, rune = int32 (a Unicode code point), any = interface{}
Floats, complex float32, float64; complex64, complex128
Text string (immutable bytes, usually UTF-8)
Go
f := float64(i)               // conversions are always explicit
n, err := strconv.Atoi("42")  // string -> int
s := strconv.Itoa(42)         // int -> string
s = string(rune(65))          // "A" (string(65) is a vet warning)
bs := []byte("hi")            // string <-> bytes
rs := []rune("hรฉllo")         // string <-> runes
x := int8(200)                // constant overflow: compile error

Operators

Operators

Precedence Operators
5 (highest) * / % << >> & &^
4 + - | ^
3 == != < <= > >=
2 &&
1 (lowest) ||

Unary: + - ! ^ * & <-. Assignment forms: = := += -= *= /= %= &= |= ^= <<= >>= &^=. i++ and i-- are statements, not expressions. There is no ternary operator and no implicit conversion between numeric types. Integer division truncates toward zero; % keeps the sign of the left operand.

Control flow

if, switch, for, range, labels

Go
if v, err := f(); err != nil { // init statement; v and err live in the whole if/else
	return err
} else if v > 10 {
	// ...
}

switch day { // no fall-through; cases may be lists
case "sat", "sun":
	// weekend
case "fri":
	fallthrough // explicit
default:
}

switch { // expressionless switch replaces an if/else chain
case n < 0:
case n == 0:
}

for i := 0; i < 3; i++ {}      // classic
for n < 100 {}                 // while
for {}                         // forever
for i := range 3 {}            // 0, 1, 2 (Go 1.22)
for i, v := range slice {}     // index and value
for k, v := range m {}         // random order!
for i, r := range "hรฉllo" {}   // byte index, rune value
for v := range ch {}           // until the channel is closed
for v := range seq {}          // iterator function (Go 1.23)

outer:
for _, row := range grid {
	for _, c := range row {
		if c == 0 {
			continue outer // or: break outer
		}
	}
}

Since Go 1.22 every iteration has its own copy of the loop variable, so closures and goroutines started in a loop capture what you expect.

Functions

Functions, Multiple Results, Variadic, Closures, defer

Go
func add(a, b int) int { return a + b }

func divmod(a, b int) (q, r int, err error) { // named results
	if b == 0 {
		err = errors.New("divide by zero")
		return // "naked" return: use only in short functions
	}
	return a / b, a % b, nil
}

func sum(nums ...int) int { /* nums is a []int */ return 0 }
total := sum(1, 2, 3)
total = sum(values...) // pass a slice

double := func(x int) int { return x * 2 } // function literal
func() { fmt.Println("now") }()            // call it at once

defer file.Close()          // runs when the surrounding function returns (LIFO)
defer func() { recover() }() // arguments of a deferred call are evaluated immediately

Functions are values: they can be stored, passed and returned. Arguments are always copied. Slices, maps and channels are small headers that point to shared data, so the copy still reaches the same elements.

Arrays, slices and maps

Arrays, Slices, Slice Internals, Maps, slices and maps packages

Go
var arr [3]int                 // array: fixed size, a value type; [3]int != [4]int
s := []int{1, 2, 3}            // slice: pointer + len + cap
s = append(s, 4, 5)            // may allocate a new array: always keep the result
t := s[1:3]                    // shares memory with s; len 2, cap cap(s)-1
u := s[1:3:3]                  // full slice expression: cap limited to 2
buf := make([]int, 3, 10)      // len 3, cap 10
n := copy(dst, src)            // copies min(len(dst), len(src)) elements
clear(s)                       // zero every element (len unchanged)
all := append([]int(nil), s...) // a clone

m := map[string]int{"a": 1}    // reading a nil map is fine, writing panics
m["b"] = 2
v, ok := m["x"]                // ok is false when the key is missing
delete(m, "a")                 // no error if absent
clear(m)                       // remove all entries
Function What it does
slices.Sort(s), slices.SortFunc(s, cmp) sort in place (cmp.Compare for the comparison)
slices.Contains, slices.Index, slices.IndexFunc search
slices.BinarySearch(s, x) search a sorted slice, returns (pos, found)
slices.Reverse, slices.Max, slices.Min reverse, extremes
slices.Insert, slices.Delete, slices.Compact structural changes (return the new slice)
slices.Equal, slices.Clone compare, copy
maps.Keys(m), maps.Values(m) iterators over keys / values
slices.Sorted(maps.Keys(m)) the sorted keys, the way to loop over a map in order
slices.Collect(seq) turn an iterator into a slice
maps.Clone, maps.Copy, maps.DeleteFunc map helpers

Map keys must be comparable (no slices, maps or functions). Map iteration order is random on purpose. Maps and slices are not safe for concurrent writes.

Go Slices share memory, maps need sorting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Strings

Strings, Bytes and Runes, strings, strconv and unicode

Go
s := "hรฉllo, ไธ–็•Œ"
len(s)                     // bytes, not characters
utf8.RuneCountInString(s)  // characters (runes)
s[1]                       // a byte (here the first byte of รฉ)
s[:5]                      // a substring (byte offsets, may cut a rune)
raw := `C:\path\no escapes, may span lines`
Task Code
Join / split strings.Join(parts, ", "), strings.Split(s, ","), strings.Fields(s)
Split once before, after, found := strings.Cut(s, "=")
Test strings.Contains, HasPrefix, HasSuffix, EqualFold
Search strings.Index, LastIndex, Count
Change ToUpper, ToLower, TrimSpace, Trim, TrimPrefix, Replace, ReplaceAll, Repeat
Iterate lines / pieces strings.Lines(s), strings.SplitSeq(s, ",") (Go 1.24, iterators)
Build var sb strings.Builder; sb.WriteString("x"); sb.String()
Numbers strconv.Atoi, ParseFloat, ParseBool, FormatInt, Quote

Strings are immutable; building with += in a loop copies every time, so use strings.Builder.

Pointers

Pointers, Pointers and Functions, new and make

Go
x := 10
p := &x           // p is *int, the address of x
*p = 20           // write through the pointer; x is now 20
var q *int        // nil; dereferencing it panics
r := new(int)     // pointer to a new zero int
pt := &Point{1, 2} // pointer to a struct literal; pt.X works without (*pt).X

There is no pointer arithmetic. Returning the address of a local variable is fine: the compiler moves it to the heap (escape analysis).

Structs, methods and embedding

Structs, Methods, Pointer Receivers, Embedding, Struct Tags

Go
type Point struct {
	X, Y int
}

func (p Point) Dist() float64 { return math.Hypot(float64(p.X), float64(p.Y)) } // value receiver
func (p *Point) Move(dx, dy int) { p.X += dx; p.Y += dy }                       // pointer receiver

type Circle struct {
	Point              // embedded: Circle gets X, Y, Dist and Move
	Radius float64 `json:"radius,omitempty"` // struct tag
}

p := Point{X: 1, Y: 2} // named fields: preferred
c := Circle{Point: p, Radius: 3}
c.Move(1, 1)           // promoted method
type Celsius float64   // defined type: new type, own methods
type Temp = float64    // alias: same type, another name

Use a pointer receiver when the method changes the receiver, when the struct is large, or when other methods already use pointers. Do not mix receiver kinds on one type without a reason.

Interfaces

Interfaces, Type Assertions, Interface Internals, Common Interfaces

Go
type Shape interface {
	Area() float64
}

var s Shape = Circle{Radius: 1}    // satisfied implicitly: no "implements"
if c, ok := s.(Circle); ok { _ = c } // type assertion with ok (no panic)
switch v := s.(type) {              // type switch
case Circle:
	_ = v.Radius
case nil:
default:
}
var anything any = 42              // any holds every type
Method set Contains
T methods with a value receiver
*T methods with a value and pointer receiver

An interface value is a (type, value) pair. It is nil only when both are nil: a nil *MyErr stored in an error makes the error non-nil.

The interfaces to know: error (Error() string), fmt.Stringer (String() string), io.Reader, io.Writer, sort.Interface, json.Marshaler, http.Handler, context.Context. Accept interfaces, return concrete types.

Generics

Generics, Constraints, Generic Types

Go
func Map[T, U any](s []T, f func(T) U) []U {
	out := make([]U, 0, len(s))
	for _, v := range s {
		out = append(out, f(v))
	}
	return out
}

type Number interface {
	~int | ~int64 | ~float64 // ~ includes defined types with that underlying type
}

func Sum[T Number](xs []T) (total T) {
	for _, x := range xs {
		total += x
	}
	return
}

type Stack[T any] struct{ items []T }
func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }

// constraints from the standard library: any, comparable, cmp.Ordered
Map([]int{1, 2}, strconv.Itoa) // type arguments are usually inferred

Methods cannot have their own type parameters. Reach for generics for algorithms and containers; use an interface when behavior differs per type.

Iterators (Go 1.23)

Iterators

Go
func Count(n int) iter.Seq[int] { // iter.Seq[V] = func(yield func(V) bool)
	return func(yield func(int) bool) {
		for i := range n {
			if !yield(i) {
				return // the loop body did break
			}
		}
	}
}

for v := range Count(3) {} // 0 1 2
// iter.Seq2[K, V] yields pairs: for k, v := range seq2 {}
Go Generics and iterators together

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Errors, panic and recover

Errors as Values, Wrapping, Custom Errors, panic and recover

Go
var ErrNotFound = errors.New("not found")        // sentinel error

type ParseError struct{ Line int }               // custom error type
func (e *ParseError) Error() string { return fmt.Sprintf("line %d", e.Line) }

if err != nil {
	return fmt.Errorf("load config: %w", err)     // wrap with %w
}
errors.Is(err, ErrNotFound)                      // matches anywhere in the chain
var pe *ParseError
errors.As(err, &pe)                              // finds a *ParseError, sets pe
errors.Join(err1, err2)                          // several errors in one

defer func() {
	if r := recover(); r != nil { // only works inside a deferred function
		err = fmt.Errorf("recovered: %v", r)
	}
}()

Errors are ordinary values: return them, check them right away, add context when passing them up, and handle each error exactly once (either log it or return it). Use panic for programmer mistakes and impossible states, not for expected failures.

Go Wrapping and inspecting errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Concurrency

Goroutines, Channels, select, sync, Atomics, context, Patterns

Go
go work()                       // start a goroutine
ch := make(chan int)            // unbuffered: send and receive meet
buf := make(chan string, 8)     // buffered
ch <- 1; v := <-ch              // send, receive
v, ok := <-ch                   // ok is false when closed and drained
close(ch)                       // only the sender closes
for v := range ch {}            // receive until closed

select {                        // wait on several operations
case v := <-ch1:
case ch2 <- 5:
case <-time.After(time.Second): // timeout
case <-ctx.Done():
default:                        // do not wait
}

var wg sync.WaitGroup
wg.Go(func() { work() })        // Go 1.25: Add(1) + go + Done
wg.Wait()

var mu sync.Mutex
mu.Lock(); defer mu.Unlock()
var once sync.Once
var n atomic.Int64; n.Add(1)

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
Operation nil channel closed channel
send blocks forever panics
receive blocks forever zero value, ok == false
close panics panics

Rules of thumb: a goroutine needs a way to stop; the sender closes; never copy a Mutex; share by communicating when you can; run tests with go test -race. If all goroutines are blocked, the runtime reports fatal error: all goroutines are asleep - deadlock!.

Go Worker pool with results in order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Formatting with fmt

Printing with fmt, fmt in Depth

Verb Meaning Example (value) Output
%v default format []int{1,2} [1 2]
%+v structs with field names Point{1,2} {X:1 Y:2}
%#v Go syntax "hi" "hi"
%T the type 3.5 float64
%d integer 42 42
%5d, %-5d, %05d width, left-aligned, zero-padded 42 42, 42 , 00042
%x, %X, %o, %b hex, HEX, octal, binary 255 ff, FF, 377, 11111111
%c, %q, %U rune, quoted rune, code point 'A' A, 'A', U+0041
%f, %.2f, %8.3f float 3.14159 3.141590, 3.14, 3.142
%e, %g exponent, compact 1234.5678 1.234568e+03, 1234.5678
%s, %q, %x string, quoted, hex bytes "go" go, "go", 676f
%t bool true true
%p pointer address &x 0xc000012345 (varies)
%% a literal percent sign %

Sprintf returns a string, Fprintf(w, ...) writes to an io.Writer, Errorf builds an error, Sscanf and Scan read values. Argument problems such as %d with a string show up as %!d(string=hi), and go vet finds them before you run.

Go The verbs in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The standard library at a glance

Standard Library lessons

Package Use it for
fmt, log, log/slog formatting, simple and structured logging
strings, strconv, unicode, bytes text and bytes
os, io, bufio, path/filepath files, streams, paths
encoding/json, encoding/csv, encoding/xml data formats
regexp, text/template, html/template patterns and templates
time clocks, durations, formatting (layout 2006-01-02 15:04:05)
math, math/rand/v2, math/big, math/bits numbers
sort, slices, maps, cmp, iter collections
sync, sync/atomic, context concurrency
net, net/http, net/url, net/http/httptest networking and web
errors, flag, testing, reflect, embed errors, CLI flags, tests, reflection, embedded files
crypto/sha256, crypto/rand, encoding/hex, encoding/base64 hashing, randomness, encodings
database/sql databases (plus a driver from a module)

Testing and the go command

Testing, Table-Driven Tests, Benchmarks and Fuzzing, Tooling, Modules

Go
// add_test.go
func TestAdd(t *testing.T) {
	tests := []struct {
		name string
		a, b int
		want int
	}{{"zero", 0, 0, 0}, {"pair", 2, 3, 5}}
	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			if got := Add(tc.a, tc.b); got != tc.want {
				t.Errorf("Add(%d, %d) = %d, want %d", tc.a, tc.b, got, tc.want)
			}
		})
	}
}

func BenchmarkAdd(b *testing.B) {
	for b.Loop() { // Go 1.24
		Add(2, 3)
	}
}
Command What it does
go run . compile and run the package in the current folder
go build / go install build a binary / build and install it
go test ./... run every test (-v, -run Name, -count=1, -race, -cover, -bench ., -fuzz Name)
go vet ./... find suspicious code
gofmt -w . or go fmt ./... format the code
go mod init example.com/app start a module
go mod tidy add missing and remove unused dependencies
go get pkg@version add or upgrade a dependency
go doc strings.Cut read documentation in the terminal
go env, go version environment and toolchain
go generate ./... run //go:generate commands
go work init multi-module workspace

Cross-compiling needs only environment variables: GOOS=linux GOARCH=arm64 go build.

Quick reminders

  • if err != nil right after the call. Handle each error once.
  • Check the ok form of map reads and type assertions when "missing" is a real possibility.
  • Always use the result of append. After s2 := s[:2], writes through s2 can change s.
  • Do not take a map value's address, do not write to a nil map, and do not copy a sync.Mutex.
  • Loop variables are per-iteration since Go 1.22, but a goroutine still needs a way to stop and a WaitGroup to wait for.
  • defer runs in last-in-first-out order when the function returns, not when the block ends.
  • Prefer any over interface{}, strings.Builder over +=, time.Duration constants over bare numbers, errors.Is over == on wrapped errors.
  • Read the compiler: its messages name the exact line and column. Run go vet before you run the tests.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. After a := []int{1, 2, 3, 4}, b := a[1:3] and b = append(b, 99), what does fmt.Println(a) print?

    b has length 2 and capacity 3, so append writes into the shared array at index 3 of a, replacing 4 with 99. Use a full slice expression a[1:3:3] or copy to avoid the aliasing.
  2. 2. Which statement about a receive from a closed channel is true?

    Once a channel is closed and drained, every receive returns the element type's zero value at once, and the two-value form reports ok == false. Sending on a closed channel panics.
  3. 3. Which method set contains both value-receiver and pointer-receiver methods?

    *T can call all methods. A value of type T has only the value-receiver methods in its method set, which matters when you assign it to an interface.
  4. 4. What is the right way to loop over a map in sorted key order (Go 1.23+)?

    maps.Keys returns an iterator, slices.Sorted collects and sorts it. Map iteration order itself is intentionally random.
  5. 5. What does fmt.Printf("%5d|%-5d|%05d", 7, 7, 7) print?

    %5d right-aligns in five columns, %-5d left-aligns, and %05d pads with zeros.

Summary

  • The blocks above cover the syntax you use daily: declarations, control flow, functions, slices and maps, structs, interfaces, generics and iterators.
  • Errors are values; wrap with %w and inspect with errors.Is and errors.As.
  • Concurrency is goroutines plus channels, sync and context; know the closed-channel and nil-channel rules.
  • fmt verbs and the go command table answer most "how do I print or run this" questions.
  • Keep the exercises and interview questions nearby to turn the reference into skill.

Next: Go Programs: 50 Classic Examples