ReferenceREF# go# reference

Go — cheatsheet

syntax, commands and idioms on a single page

Команды go

Команда Что делает
go mod init goflix создать модуль — файл go.mod
go run . скомпилировать во временный файл и запустить
go build собрать исполняемый файл
go fmt ./... отформатировать код
go vet ./... найти подозрительные места
go test ./... запустить тесты
go test -race ./..., go run -race . найти гонки данных
go get модуль@версия добавить или обновить зависимость
go mod tidy убрать лишние и докачать нужные зависимости
GOOS=linux GOARCH=amd64 go build собрать под другую ОС
go build -gcflags=-m показать решения escape analysis

→ 02 — Первая программа

Форматированный вывод

go
fmt.Print("без перевода строки")
fmt.Println("пробелы между аргументами", 1, true) // и перевод строки в конце
fmt.Printf("%s (%d), рейтинг %.1f\n", "Дюна", 2021, 8.1)
card := fmt.Sprintf("%s-%d", "FILM", 1) // вернуть строку, а не напечатать
Плейсхолдер Что печатает
%v значение в формате по умолчанию
%+v структуру с именами полей
%T тип значения
%d целое число
%f, %.2f дробное число, 2 знака после точки
%s, %q строку; строку в кавычках
%c символ по коду руны
%t bool
%% знак процента
%5d, %-10s ширина поля, выравнивание влево

→ 02 — Первая программа → Вывод через fmt

Переменные и константы

go
var rating float64 = 8.6 // полная форма
var title = "Дюна"       // тип выводится из значения
year := 2021             // короткая форма, только внутри функций
a, b = b, a              // обмен без временной переменной
_, rest := split(95)     // ненужное значение — в _

const maxRating = 10.0
const (
    PlanFree  = iota // 0
    PlanBasic        // 1
)

→ 03 — Переменные и константы

Типы и нулевые значения

Тип Нулевое значение
int, int8…int64, uint8 (byte), float64, rune 0
string ""
bool false
*T, []T, map[K]V, chan T, функция, интерфейс nil
структура, массив каждое поле или элемент — нулевое значение
go
f := float64(n)              // преобразование только явное
i := int(f)                  // дробная часть отбрасывается
s := strconv.Itoa(n)         // число → строка, а не string(n)
n, err := strconv.Atoi("42") // строка → число, с ошибкой
runes := []rune("Фильм")     // 5 символов; len("Фильм") == 10 байт

Деньги — целыми копейками в int64, не во float64. → 04 — Типы данных и преобразования

Управляющие конструкции

go
if d := discount(years); d > 0 { // переменная видна только в if/else
    apply(d)
} else {
    skip()
}

for i := 0; i < n; i++ {} // классический
for ok {}                 // как while
for {}                    // бесконечный — выход через break или return
for i, v := range items {} // индекс и значение
for i := range 10 {}       // числа 0..9, Go 1.22+

switch code {
case 1, 2: // несколько значений; break не нужен
    handle()
default:
    other()
}

switch { // без выражения — для диапазонов
case score >= 9:
    best()
}

switch v := x.(type) { // type switch
case int:
    useInt(v)
}

outer:
for _, row := range rows {
    for _, cell := range row {
        if cell == target {
            break outer // выход из обоих циклов
        }
    }
}

→ 06 — Условия if-else, 07 — Циклы for, 08 — Switch-case

Функции

go
func split(minutes int) (int, int) { return minutes / 60, minutes % 60 }

func sum(nums ...int) int { // вариативная: внутри nums — это []int
    total := 0
    for _, n := range nums {
        total += n
    }
    return total
}

// вызов: sum(1, 2, 3) или sum(durations...)

var calc func(int, int) int = add // функция как значение

func() { fmt.Println("вызвана сразу") }() // анонимная функция, IIFE

func counter() func() int { // замыкание: n живёт между вызовами
    n := 0
    return func() int {
        n++
        return n
    }
}

slices.SortFunc(movies, func(a, b Movie) int { return cmp.Compare(a.Year, b.Year) }) // callback

Аргументы передаются по значению — функция получает копию. → 05 — Функции, 12 — Продвинутые функции

Слайсы и мапы

go
s := []int{1, 2, 3}          // len 3, cap 3
s = make([]int, 0, 10)       // len 0, cap 10 — место заранее
s = append(s, 4, 5)          // результат append — всегда обратно в s
s = append(s, other...)      // влить другой слайс
part := s[1:3]               // окно над тем же массивом!
clone := slices.Clone(s)     // независимая копия
s = slices.Delete(s, i, i+1) // удалить элемент i

m := map[string]int{"Дюна": 1}
v, ok := m["Матрица"]               // comma-ok: ok == false, если ключа нет
delete(m, "Дюна")                   // безопасно даже без ключа
keys := slices.Sorted(maps.Keys(m)) // стабильный порядок обхода
set := map[string]struct{}{}        // множество
nil-слайс nil-мапа
len 0 0
чтение range — ноль итераций нулевое значение
запись append работает panic
JSON null null

→ 09 — Массивы и слайсы, 10 — Мапы

Указатели

go
p := &x      // адрес переменной
*p = 10      // записать по адресу — меняется x
p.Title      // поле структуры через указатель — Go разыменует сам
p = new(int) // указатель на нулевое значение
if p != nil { use(*p) } // nil разыменовывать нельзя

→ 11 — Указатели

Ошибки

go
if err != nil {
    return fmt.Errorf("загрузка фильма %d: %w", id, err) // контекст + причина
}

var ErrNotFound = errors.New("not found") // sentinel-ошибка уровня пакета
errors.Is(err, ErrNotFound)               // проверка по значению через цепочку

var vErr *ValidationError
if errors.As(err, &vErr) { use(vErr.Field) } // проверка по типу

err = errors.Join(err1, err2) // несколько ошибок сразу

f, err := os.Open(path)
if err != nil {
    return err
}
defer f.Close() // выполнится при выходе; несколько defer — LIFO

defer func() { // перехват паники — только внутри defer
    if r := recover(); r != nil {
        err = fmt.Errorf("паника: %v", r) // через именованный результат
    }
}()

→ 13 — Обработка ошибок, 14 — defer, panic, recover

Структуры и интерфейсы

go
type Movie struct {
    Title string `json:"title"`
    Year  int    `json:"year,omitempty"`
}

// Info — получатель по значению: работает с копией.
func (m Movie) Info() string { return m.Title }

// Rename — получатель по указателю: меняет оригинал.
func (m *Movie) Rename(t string) { m.Title = t }

func NewMovie(title string) *Movie { return &Movie{Title: title} } // конструктор

type Admin struct {
    User         // встраивание: поля и методы User доступны напрямую
    Level string
}

type Describer interface{ Info() string } // реализуется неявно
var _ Describer = Movie{}                 // проверка реализации при компиляции

s, ok := x.(string) // безопасный type assertion

func Contains[T comparable](items []T, x T) bool { return slices.Contains(items, x) } // дженерик

Интерфейс равен nil, только если пусты и тип, и значение. → 15 — Структуры, 16 — Интерфейсы

Конкурентность

go
var wg sync.WaitGroup
wg.Add(1)
go func() {
    defer wg.Done()
    work()
}()
wg.Wait()
wg.Go(work) // в современном Go: Add, go и Done одной строкой

ch := make(chan string)    // небуферизованный: встреча отправителя и получателя
buf := make(chan int, 3)   // буферизованный: очередь на 3 значения
ch <- "Дюна"               // отправить
v := <-ch                  // получить
close(ch)                  // закрывает только отправитель
for v := range ch {}       // читать до закрытия
v, ok := <-ch              // ok == false — закрыт и пуст

select {
case v := <-ch:
    use(v)
case <-time.After(time.Second): // таймаут
    timeout()
default: // без ожидания
}

mu.Lock()
defer mu.Unlock()

ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
<-ctx.Done() // закрывается при отмене; ctx.Err() — причина
Операция nil-канал открытый канал закрытый канал
ch <- v блокировка навсегда ждёт получателя или места в буфере panic
<-ch блокировка навсегда ждёт данные нулевое значение, ok == false
close(ch) panic закрывает panic

→ 17 — Конкурентность — горутины и каналы

HTTP и базы данных

go
mux := http.NewServeMux()
mux.HandleFunc("GET /api/v1/users/{id}", h.GetUser) // метод и параметр пути, Go 1.22+

// внутри обработчика func(w http.ResponseWriter, r *http.Request):
id := r.PathValue("id")                     // параметр пути
limit := r.URL.Query().Get("limit")         // query-параметр
token := r.Header.Get("Authorization")      // заголовок — не логировать!
err := json.NewDecoder(r.Body).Decode(&req) // JSON-тело в структуру

w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated) // статус — до тела
json.NewEncoder(w).Encode(resp)

type Middleware func(http.Handler) http.Handler // первый в цепочке — внешний

srv := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
srv.Shutdown(ctx) // graceful shutdown

pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL")) // секрет — из окружения
err = pool.QueryRow(ctx, "SELECT name FROM users WHERE id = $1", id).Scan(&name)
rows, err := pool.Query(ctx, query, args...)
defer rows.Close() // вернуть соединение в пул
tx, err := pool.Begin(ctx)
defer tx.Rollback(ctx) // после Commit ничего не делает
err = tx.Commit(ctx)
errors.Is(err, pgx.ErrNoRows) // строки нет → доменная ErrNotFound

Значения в SQL — только плейсхолдерами $1, $2, никакой конкатенации. → 18 — Backend — HTTP-сервер, 19 — Работа с базами данных

go commands

Command What it does
go mod init goflix create a module — the go.mod file
go run . compile to a temporary file and run
go build build an executable
go fmt ./... format the code
go vet ./... find suspicious spots
go test ./... run the tests
go test -race ./..., go run -race . find data races
go get module@version add or update a dependency
go mod tidy remove unneeded and fetch missing dependencies
GOOS=linux GOARCH=amd64 go build build for another OS
go build -gcflags=-m show escape analysis decisions

→ 02 — Your first program

Formatted output

go
fmt.Print("no newline")
fmt.Println("spaces between arguments", 1, true) // plus a newline at the end
fmt.Printf("%s (%d), rating %.1f\n", "Dune", 2021, 8.1)
card := fmt.Sprintf("%s-%d", "FILM", 1) // return a string instead of printing
Placeholder What it prints
%v the value in its default format
%+v a struct with field names
%T the value's type
%d an integer
%f, %.2f a float, 2 digits after the point
%s, %q a string; a quoted string
%c the character for a rune code
%t bool
%% a percent sign
%5d, %-10s field width, left alignment

→ 02 — Your first program → Output with fmt

Variables and constants

go
var rating float64 = 8.6 // the full form
var title = "Dune"       // the type is inferred from the value
year := 2021             // the short form, inside functions only
a, b = b, a              // swap without a temporary
_, rest := split(95)     // an unneeded value goes into _

const maxRating = 10.0
const (
    PlanFree  = iota // 0
    PlanBasic        // 1
)

→ 03 — Variables and constants

Types and zero values

Type Zero value
int, int8…int64, uint8 (byte), float64, rune 0
string ""
bool false
*T, []T, map[K]V, chan T, function, interface nil
struct, array every field or element — its zero value
go
f := float64(n)              // conversions are explicit only
i := int(f)                  // the fractional part is dropped
s := strconv.Itoa(n)         // number → string, not string(n)
n, err := strconv.Atoi("42") // string → number, with an error
runes := []rune("héllo")     // 5 characters; len("héllo") == 6 bytes

Money — integer kopecks in int64, never float64. → 04 — Data types and conversions

Control flow

go
if d := discount(years); d > 0 { // the variable is visible only in if/else
    apply(d)
} else {
    skip()
}

for i := 0; i < n; i++ {}  // the classic form
for ok {}                  // works like while
for {}                     // infinite — exit with break or return
for i, v := range items {} // index and value
for i := range 10 {}       // numbers 0..9, Go 1.22+

switch code {
case 1, 2: // several values; no break needed
    handle()
default:
    other()
}

switch { // no expression — for ranges
case score >= 9:
    best()
}

switch v := x.(type) { // type switch
case int:
    useInt(v)
}

outer:
for _, row := range rows {
    for _, cell := range row {
        if cell == target {
            break outer // exit both loops
        }
    }
}

→ 06 — if-else, 07 — for loops, 08 — Switch-case

Functions

go
func split(minutes int) (int, int) { return minutes / 60, minutes % 60 }

func sum(nums ...int) int { // variadic: inside, nums is a []int
    total := 0
    for _, n := range nums {
        total += n
    }
    return total
}

// call: sum(1, 2, 3) or sum(durations...)

var calc func(int, int) int = add // a function as a value

func() { fmt.Println("called at once") }() // an anonymous function, IIFE

func counter() func() int { // a closure: n lives across calls
    n := 0
    return func() int {
        n++
        return n
    }
}

slices.SortFunc(movies, func(a, b Movie) int { return cmp.Compare(a.Year, b.Year) }) // callback

Arguments are passed by value — the function gets a copy. → 05 — Functions, 12 — Advanced functions

Slices and maps

go
s := []int{1, 2, 3}          // len 3, cap 3
s = make([]int, 0, 10)       // len 0, cap 10 — space reserved up front
s = append(s, 4, 5)          // the result of append always goes back into s
s = append(s, other...)      // pour in another slice
part := s[1:3]               // a window over the same array!
clone := slices.Clone(s)     // an independent copy
s = slices.Delete(s, i, i+1) // remove element i

m := map[string]int{"Dune": 1}
v, ok := m["The Matrix"]           // comma-ok: ok == false when the key is missing
delete(m, "Dune")                  // safe even without the key
keys := slices.Sorted(maps.Keys(m)) // stable iteration order
set := map[string]struct{}{}       // a set
nil slice nil map
len 0 0
read range — zero iterations the zero value
write append works panic
JSON null null

→ 09 — Arrays and slices, 10 — Maps

Pointers

go
p := &x      // the variable's address
*p = 10      // write through the address — x changes
p.Title      // a struct field through a pointer — Go dereferences it
p = new(int) // a pointer to a zero value
if p != nil { use(*p) } // nil must not be dereferenced

→ 11 — Pointers

Errors

go
if err != nil {
    return fmt.Errorf("load movie %d: %w", id, err) // context + cause
}

var ErrNotFound = errors.New("not found") // a package-level sentinel error
errors.Is(err, ErrNotFound)               // a value check through the chain

var vErr *ValidationError
if errors.As(err, &vErr) { use(vErr.Field) } // a type check

err = errors.Join(err1, err2) // several errors at once

f, err := os.Open(path)
if err != nil {
    return err
}
defer f.Close() // runs on exit; several defers run LIFO

defer func() { // catching a panic — only inside defer
    if r := recover(); r != nil {
        err = fmt.Errorf("panic: %v", r) // through a named result
    }
}()

→ 13 — Error handling, 14 — defer, panic, recover

Structs and interfaces

go
type Movie struct {
    Title string `json:"title"`
    Year  int    `json:"year,omitempty"`
}

// Info — a value receiver: works on a copy.
func (m Movie) Info() string { return m.Title }

// Rename — a pointer receiver: changes the original.
func (m *Movie) Rename(t string) { m.Title = t }

func NewMovie(title string) *Movie { return &Movie{Title: title} } // a constructor

type Admin struct {
    User         // embedding: User's fields and methods are available directly
    Level string
}

type Describer interface{ Info() string } // implemented implicitly
var _ Describer = Movie{}                 // a compile-time implementation check

s, ok := x.(string) // a safe type assertion

func Contains[T comparable](items []T, x T) bool { return slices.Contains(items, x) } // a generic

An interface equals nil only when both the type and the value are empty. → 15 — Structs, 16 — Interfaces

Concurrency

go
var wg sync.WaitGroup
wg.Add(1)
go func() {
    defer wg.Done()
    work()
}()
wg.Wait()
wg.Go(work) // Add, go, and Done in one line

ch := make(chan string)    // unbuffered: the sender and receiver meet
buf := make(chan int, 3)   // buffered: a queue of 3 values
ch <- "Dune"               // send
v := <-ch                  // receive
close(ch)                  // only the sender closes
for v := range ch {}       // read until closed
v, ok := <-ch              // ok == false — closed and empty

select {
case v := <-ch:
    use(v)
case <-time.After(time.Second): // a timeout
    timeout()
default: // without waiting
}

mu.Lock()
defer mu.Unlock()

ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
<-ctx.Done() // closes on cancellation; ctx.Err() — the reason
Operation nil channel open channel closed channel
ch <- v blocks forever waits for a receiver or buffer space panic
<-ch blocks forever waits for data zero value, ok == false
close(ch) panic closes it panic

→ 17 — Concurrency — goroutines and channels

HTTP and databases

go
mux := http.NewServeMux()
mux.HandleFunc("GET /api/v1/users/{id}", h.GetUser) // method and path parameter, Go 1.22+

// inside the handler func(w http.ResponseWriter, r *http.Request):
id := r.PathValue("id")                     // a path parameter
limit := r.URL.Query().Get("limit")         // a query parameter
token := r.Header.Get("Authorization")      // a header — never log it!
err := json.NewDecoder(r.Body).Decode(&req) // the JSON body into a struct

w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated) // the status — before the body
json.NewEncoder(w).Encode(resp)

type Middleware func(http.Handler) http.Handler // the first in the chain is the outermost

srv := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
srv.Shutdown(ctx) // graceful shutdown

pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL")) // the secret — from the environment
err = pool.QueryRow(ctx, "SELECT name FROM users WHERE id = $1", id).Scan(&name)
rows, err := pool.Query(ctx, query, args...)
defer rows.Close() // return the connection to the pool
tx, err := pool.Begin(ctx)
defer tx.Rollback(ctx) // a no-op after Commit
err = tx.Commit(ctx)
errors.Is(err, pgx.ErrNoRows) // no row → the domain ErrNotFound

Values in SQL — placeholders $1, $2 only, no concatenation ever. → 18 — Backend — HTTP server, 19 — Working with databases

// related topics and cheatsheets