ReferenceQ&A# go# interview

Go — interview questions

questions with collapsible answers for self-check

Как пользоваться

  • Раз в неделю бери 10 случайных вопросов из разных разделов — это чередование, оно укрепляет память лучше, чем повтор подряд.
  • Отвечай вслух, как на собеседовании: термин → как устроено → пример из кода.
  • Не смог ответить — открой главу по ссылке и добавь вопрос в Go с нуля.
  • Задачи «что выведет» реши на бумаге, потом запусти код.

Основы языка

вопросПочему выбирают Go и где его используют?

Компилируемый, быстрый, с встроенной конкурентностью и простым синтаксисом; собирается в один бинарник. Используют для бэкендов и API, микросервисов, инфраструктуры (Kubernetes, Docker, Prometheus), сетевых сервисов и облаков. → 01 — Что такое Go и зачем его учить

вопросЧем := отличается от var? Где := использовать нельзя?

:= объявляет переменную и выводит тип, var можно использовать с явным типом и без значения. := работает только внутри функций, на уровне пакета — только var. Повторный := без новых переменных слева — ошибка. → 03 — Переменные и константы → Три способа объявить переменную

самопроверкаЧто такое zero value? Назови для основных типов.

Значение, которое Go даёт переменной без инициализации, — мусора не бывает. Числа — 0, строка — "", bool — false, указатели, слайсы, мапы, каналы, функции и интерфейсы — nil, структура — нулевые значения всех полей. → 04 — Типы данных и преобразования → Нулевые значения

вопросПочему len("Привет") равно 12? Что такое rune?

Строка — байты в UTF-8, len считает байты, а кириллическая буква занимает 2 байта. rune — код символа Unicode, псевдоним int32; символы считает utf8.RuneCountInString, а range по строке идёт по рунам. → 04 — Типы данных и преобразования → rune — один символ

вопросПочему нельзя сложить int и float64?

Go строго типизирован и не конвертирует типы неявно. Нужно явное преобразование: float64(n) * f. При int(f) дробная часть отбрасывается. → 04 — Типы данных и преобразования → Преобразование типов

вопросЧто такое shadowing и чем он опасен?

Объявление через := во вложенном блоке переменной с тем же именем, что снаружи. Появляется новая переменная, внешняя не меняется. Типичный баг — с err внутри if. → 05 — Функции → Shadowing — затенение

вопросКак в Go передаются аргументы в функцию?

Всегда по значению — функция получает копию. Для слайсов, мап и каналов копируется маленький заголовок со ссылкой на общие данные, поэтому изменения элементов видны снаружи. Чтобы изменить саму переменную, передают указатель. → 05 — Функции → Передача по значению

вопросКак сделать функцию или поле видимыми из другого пакета?

Назвать с заглавной буквы — имя экспортируется. Со строчной — приватно для пакета. → 05 — Функции → Экспорт — заглавная буква

вопросНужен ли break в switch? Что делает fallthrough?

break не нужен: выполняется одна ветка, провала нет. fallthrough безусловно выполняет тело следующего case, не проверяя его условие. → 08 — Switch-case

Слайсы и мапы

вопросЧем слайс отличается от массива?

Массив — фиксированный размер, который входит в тип ([3]int ≠ [5]int); при присваивании и передаче копируется целиком. Слайс — заголовок (указатель на массив, len, cap) поверх массива, размер динамический, копируется только заголовок. → 09 — Массивы и слайсы → Почему массивы почти не используют

вопросЧто внутри слайса и сколько он занимает?

Три поля: указатель на первый элемент окна в массиве, длина и ёмкость — 24 байта на 64-битной системе. Сам массив живёт отдельно. → 09 — Массивы и слайсы → Что под капотом

вопросКак работает append и почему пишут s = append(s, x)?

Если ёмкости хватает — пишет в тот же массив и увеличивает длину. Если нет — выделяет новый массив побольше (до 256 элементов вдвое, дальше медленнее), копирует данные и возвращает слайс на новый массив. Без присваивания переменная останется со старым заголовком. → 09 — Массивы и слайсы → append — добавление элементов

вопросЧем nil-слайс отличается от пустого?

У nil-слайса нет массива, он равен nil; у пустого массив есть. Оба имеют длину 0, с обоими работают range и append. В JSON: null против []. → 09 — Массивы и слайсы → nil-слайс

вопросКак получится утечка памяти при нарезке и как её избежать?

Маленький слайс от огромного массива держит весь массив, и GC его не соберёт. Нужно скопировать нужную часть: copy в новый слайс или slices.Clone. → 09 — Массивы и слайсы → Утечка памяти при нарезке

вопросЧто будет при записи в nil-мапу? А при чтении?

Запись — panic: assignment to entry in nil map. Чтение — нулевое значение без паники. → 10 — Мапы → Ловушка nil-мапы

вопросКак отличить отсутствие ключа от нулевого значения?

comma-ok: v, ok := m[k] — ok == false, если ключа нет. → 10 — Мапы → Чтение, запись и удаление

вопросКакие типы могут быть ключом мапы?

Только сравнимые: числа, строки, bool, указатели, каналы, интерфейсы, массивы и структуры из сравнимых полей. Слайсы, мапы и функции — нет. → 10 — Мапы → Какие типы могут быть ключом

вопросКак устроена мапа в Go?

До Go 1.24: массив бакетов по 8 пар, tophash — старшие 8 бит хеша на слот для быстрого отсева, при переполнении — цепочка overflow-бакетов, рост вдвое с постепенной эвакуацией. С Go 1.24 — Swiss Tables: группы по 8 слотов с 64-битным контрольным словом, хеш делится на h1 (57 бит, выбор группы) и h2 (7 бит, в контрольном слове), h2 сравнивается со всеми слотами группы разом, коллизии — открытой адресацией, мапа делится на таблицы до 1024 записей. → 10 — Мапы → Как устроена мапа

вопросПочему порядок обхода мапы случайный?

Go специально рандомизирует его, чтобы код не полагался на порядок. Для стабильного порядка сортируют ключи: slices.Sorted(maps.Keys(m)). → 10 — Мапы → Обход и порядок

вопросМожно ли писать в мапу из нескольких горутин?

Нет — fatal error: concurrent map writes, его не перехватить recover. Нужна защита sync.Mutex / sync.RWMutex или sync.Map. → 10 — Мапы → Мапа и горутины

Задача. Что выведет программа?

go
package main

import "fmt"

func grow(s []int) {
    s = append(s, 4)
    s[0] = 100
}

func main() {
    a := []int{1, 2, 3}
    grow(a)

    b := make([]int, 3, 10)
    copy(b, []int{1, 2, 3})
    grow(b)

    fmt.Println(a, b, b[:4])
}
самопроверкаОтвет
text
[1 2 3] [100 2 3] [100 2 3 4]

У a ёмкость 3: append внутри grow создал новый массив, и s[0] = 100 записалось уже туда — a не изменился. У b ёмкость 10: append записал 4 в общий массив, s[0] = 100 тоже попал в общий массив. Длина b осталась 3, но b[:4] показывает дописанный элемент.

Задача. Что выведет программа?

go
package main

import "fmt"

func main() {
    m := map[string]int{"a": 1}
    v := m["b"]
    _, ok := m["b"]
    m["c"]++
    fmt.Println(v, ok, len(m), m["c"])
}
самопроверкаОтвет
text
0 false 2 1

Отсутствующий ключ даёт нулевое значение, comma-ok — false. m["c"]++ читает 0 и записывает 1, поэтому в мапе стало два ключа.

Указатели и функции

вопросЧто такое указатель? Что делают & и *?

Адрес переменной в памяти. &x берёт адрес, *p читает или меняет значение по адресу. Нулевое значение указателя — nil, разыменовывать его нельзя. → 11 — Указатели → & и *

вопросКогда передавать значение по указателю?

Когда функция должна изменить оригинал, когда структура большая и копировать её дорого, когда нужно опциональное значение (nil — «не задано»). → 11 — Указатели → Итоги

вопросБезопасно ли вернуть указатель на локальную переменную? Что такое escape analysis?

Безопасно. Компилятор видит, что переменная «убегает» из функции, и размещает её в куче, а GC удалит её, когда ссылок не останется. Это и есть escape analysis; посмотреть решения — go build -gcflags=-m. → 11 — Указатели → Возврат указателя на локальную переменную

вопросНужно ли передавать слайс или мапу по указателю?

Обычно нет: внутри уже есть указатель на данные, изменения элементов видны снаружи. Исключение — append в функции: изменение длины не видно, поэтому слайс возвращают. → 11 — Указатели → Ссылочные типы

вопросЧто такое замыкание? Что изменилось с переменной цикла в Go 1.22?

Функция, захватывающая переменные окружения по ссылке. С Go 1.22 переменная цикла новая на каждой итерации, поэтому замыкания и горутины в цикле видят «своё» значение; раньше видели последнее. → 12 — Продвинутые функции → Замыкания

вопросЧто такое вариативная функция?

Функция с последним параметром ...T: принимает любое число аргументов, внутри это []T; готовый слайс передают как s.... Примеры — append, fmt.Println. → 12 — Продвинутые функции → Вариативные функции

Ошибки, defer и panic

вопросКак обрабатывают ошибки в Go и чем это отличается от исключений?

Ошибка — значение интерфейса error, которое функция возвращает последним. Вызывающий сразу проверяет if err != nil и решает, что делать; ничего не улетает по стеку само. → 13 — Обработка ошибок → Ошибка — это значение

вопросЧем %w отличается от %v в fmt.Errorf?

%w оборачивает ошибку и сохраняет связь с причиной — её найдут errors.Is и errors.As. %v вставляет только текст. → 13 — Обработка ошибок → Контекст: оборачивание через %w

вопросЧем errors.Is отличается от errors.As?

Is ищет в цепочке конкретное значение (sentinel-ошибку) и возвращает bool. As ищет ошибку определённого типа и записывает её в переданный указатель, давая доступ к полям. → 13 — Обработка ошибок → Свой тип ошибки и errors.As

вопросЧто такое sentinel-ошибка?

Заранее объявленное на уровне пакета значение ошибки, например var ErrNotFound = errors.New("not found"), которое распознают через errors.Is. Объявляют один раз, потому что два errors.New с одинаковым текстом — разные значения. → 13 — Обработка ошибок → Sentinel-ошибки

вопросВ каком порядке выполняются defer и когда вычисляются их аргументы?

В обратном порядке (LIFO) при выходе из функции — и при return, и при панике. Аргументы вычисляются сразу в момент defer; чтобы прочитать значение при выходе, используют замыкание. → 14 — defer, panic, recover → defer: отложенный вызов

вопросКак работает recover и поймает ли он панику из другой горутины?

Работает только внутри отложенной функции, останавливает панику и возвращает её значение; функция при этом завершается. Паника из другой горутины не перехватывается — защиту ставят внутри каждой горутины. → 14 — defer, panic, recover → recover

вопросКогда использовать panic, а когда ошибку?

Ошибку — для ожидаемых ситуаций: ввод, сеть, файлы, валидация. panic — для багов и нарушенных инвариантов, например отсутствия обязательного конфига на старте. Сомневаешься — ошибка. → 14 — defer, panic, recover → panic или ошибка

вопросЧто не так с defer внутри цикла?

Отложенные вызовы копятся до выхода из функции — файлы и соединения держатся открытыми. Тело итерации выносят в отдельную функцию. → 14 — defer, panic, recover → defer в цикле — ловушка

Задача. Что выведет программа?

go
package main

import "fmt"

func f() (result int) {
    defer func() { result++ }()
    return 10
}

func g() int {
    x := 10
    defer func() { x++ }()
    return x
}

func main() {
    fmt.Println(f(), g())
}
самопроверкаОтвет
text
11 10

В f результат именованный: return 10 записывает 10 в result, затем defer его увеличивает. В g результат безымянный: return x уже скопировал 10, а defer меняет локальную x, которая на результат не влияет.

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

вопросКак в Go реализовано ООП?

Классов нет: структуры с методами. Инкапсуляция — через регистр первой буквы. Наследования нет — композиция через встраивание. Полиморфизм — через интерфейсы с неявной реализацией. → 15 — Структуры → ООП в Go

вопросЧем получатель по значению отличается от получателя по указателю?

По значению метод работает с копией и не меняет оригинал. По указателю — меняет оригинал и не копирует структуру. Если хоть одному методу нужен указатель, обычно все методы делают с указателем. → 15 — Структуры → Методы

вопросВстраивание — это наследование?

Нет. Поля и методы встроенной структуры «поднимаются» наверх, но тип внешней структуры не становится типом встроенной и не подставляется вместо неё. Взаимозаменяемость дают интерфейсы. → 15 — Структуры → Встраивание — композиция вместо наследования

вопросСколько памяти занимает struct{} и где её используют?

0 байт. В множествах map[T]struct{} и сигнальных каналах chan struct{}. → 15 — Структуры → Пустая структура

вопросЧто такое интерфейс и что значит «неявная реализация»?

Набор сигнатур методов — контракт поведения. Тип реализует интерфейс автоматически, если у него есть все методы; implements не пишут, и тип может даже не знать об интерфейсе. → 16 — Интерфейсы → Интерфейс — контракт поведения

вопросПочему интерфейс с nil-указателем внутри не равен nil?

Интерфейс хранит пару «тип + значение» и равен nil, только если пусты оба. Положили (*T)(nil) — тип записан, значит интерфейс не пустой. Классический баг: функция с результатом error возвращает nil-переменную конкретного типа, и err != nil. → 16 — Интерфейсы → Ловушка nil-интерфейса

вопросКак достать конкретный тип из any?

Type assertion: v, ok := x.(T) — безопасно; v := x.(T) паникует при несовпадении. Для нескольких типов — type switch switch v := x.(type). → 16 — Интерфейсы → any — пустой интерфейс

вопросПочему значение T может не реализовать интерфейс, а *T реализует?

Метод с получателем-указателем входит в набор методов только *T. Положить в интерфейс значение T нельзя: method has pointer receiver. → 16 — Интерфейсы → Полиморфизм

вопросЧто такое дженерики и чем они отличаются от интерфейсов?

Функции и типы с параметрами типа (Go 1.18+): func Max[T cmp.Ordered](a, b T) T. Интерфейс — общее поведение разных типов, выбор во время выполнения; дженерик — один алгоритм для разных типов, подстановка при компиляции. Ограничения параметров типа задаются интерфейсами. → 16 — Интерфейсы → Дженерики

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

вопросЧем горутина отличается от потока ОС? Что такое модель GMP?

Горутина лёгкая: стек в пару килобайт растёт по мере надобности, переключает её планировщик Go, а не ядро. G — горутина, M — поток ОС, P — контекст планировщика с очередью горутин; число P задаёт GOMAXPROCS. Тысячи горутин работают на нескольких потоках (M:N). → 17 — Конкурентность — горутины и каналы → Горутины

вопросКак дождаться завершения горутин?

sync.WaitGroup: Add(1) до запуска, defer wg.Done() внутри горутины, Wait() в ожидающем коде; в современном Go — wg.Go(f). Или каналы. time.Sleep — не синхронизация. → 17 — Конкурентность — горутины и каналы → sync.WaitGroup

вопросЧем небуферизованный канал отличается от буферизованного?

В небуферизованном отправитель и получатель ждут друг друга — это точка синхронизации. В буферизованном отправка не блокируется, пока буфер не полон, а чтение — пока не пуст. → 17 — Конкурентность — горутины и каналы → Каналы

вопросЧто будет при отправке, чтении и закрытии nil-канала и закрытого канала?

nil-канал: отправка и чтение блокируются навсегда, close — паника. Закрытый: отправка — паника, чтение — оставшиеся значения, потом нулевое значение и ok == false, повторный close — паника. Закрывает канал только отправитель. → Go — шпаргалка → Конкурентность

вопросКак работает select?

Ждёт готовности одного из каналов и выполняет его case; если готовы несколько — выбирает случайный. Без default блокируется, с default — неблокирующая проверка. Таймаут — case <-time.After(d). → 17 — Конкурентность — горутины и каналы → select

вопросЧто такое data race и как его найти?

Одновременный доступ нескольких горутин к одной переменной, когда хотя бы один — запись, без синхронизации. Ищут флагом -race: go test -race ./.... Лечат мьютексом, атомиками или каналами. → 17 — Конкурентность — горутины и каналы → sync.Mutex

вопросMutex или каналы — когда что?

Каналы — для передачи данных и координации («разделяй память через общение»). Мьютекс — для защиты общего состояния: счётчика, кэша, мапы. → 17 — Конкурентность — горутины и каналы → sync.Mutex

вопросЧто такое deadlock и утечка горутин?

Deadlock — все горутины заблокированы, Go падает с all goroutines are asleep - deadlock!. Утечка — горутина навсегда зависла, например на отправке в канал, который никто не читает; лечится буфером, закрытием канала или отменой через context. → 17 — Конкурентность — горутины и каналы → select

вопросЗачем нужен worker pool?

Ограничить число одновременных операций: фиксированное число воркеров читает задачи из канала jobs, результаты пишет в results; после отправки задач jobs закрывают. → 17 — Конкурентность — горутины и каналы → Worker Pool

вопросЧто такое context и зачем вызывать cancel?

Механизм передачи отмены и дедлайнов: WithCancel, WithTimeout, WithDeadline; ctx.Done() закрывается при отмене, ctx.Err() объясняет причину. cancel освобождает ресурсы контекста — его вызывают всегда, обычно через defer. → 17 — Конкурентность — горутины и каналы → context — отмена и дедлайны

Задача. Что выведет программа?

go
package main

import "fmt"

func main() {
    ch := make(chan int, 3)
    for i := range 3 {
        ch <- i * i
    }
    close(ch)

    sum := 0
    for v := range ch {
        sum += v
    }
    v, ok := <-ch
    fmt.Println(sum, v, ok, len(ch))
}
самопроверкаОтвет
text
5 0 false 0

В канал легли 0, 1 и 4 — их сумма 5. После закрытия range дочитал буфер и завершился; дальнейшее чтение — нулевое значение и false, а буфер пуст.

Backend

вопросКак устроен HTTP-сервер на net/http?

Обработчик — func(w http.ResponseWriter, r *http.Request); маршруты регистрируют в http.ServeMux, с Go 1.22 — с методом и параметрами: "GET /users/{id}" и r.PathValue("id"). Сервер — http.Server с таймаутами. → 18 — Backend — HTTP-сервер → Эндпоинты, ServeMux и версии API

вопросЗачем делить сервис на handler, service и repository?

Разделение ответственности: транспорт, бизнес-логика, хранение. Слой меняют, не трогая остальные; зависимости передают через интерфейсы, что упрощает тесты. → 18 — Backend — HTTP-сервер → Слои приложения

вопросПочему WriteHeader вызывают до записи тела?

Первая запись тела неявно отправляет статус 200, и поздний WriteHeader уже ничего не изменит. → 18 — Backend — HTTP-сервер → Ответ: статус до тела

вопросЧто такое middleware и в каком порядке их ставить?

Функция func(http.Handler) http.Handler — слой вокруг обработчика для логов, request ID, recovery, CORS, авторизации. При цепочке «первый в списке — внешний»; Recovery ставят внешним, чтобы перехватывать паники и в других слоях. → 18 — Backend — HTTP-сервер → Middleware

вопросКак тестировать хендлеры без запуска сервера?

httptest.NewRequest — запрос, httptest.NewRecorder — подменный ответ, вызов ServeHTTP, проверка кода и тела; репозиторий подменяют заглушкой через интерфейс. Удобно оформлять табличным тестом. → 18 — Backend — HTTP-сервер → Тестирование хендлеров

вопросЧто такое graceful shutdown?

По сигналу SIGINT или SIGTERM сервер перестаёт принимать новые запросы и даёт текущим доработать в пределах таймаута: srv.Shutdown(ctx). Плюс таймауты ReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeout. → 18 — Backend — HTTP-сервер → Graceful shutdown и таймауты

вопросЗачем нужен пул соединений к базе?

Соединения дорогие и ограничены, а одно соединение выстроит запросы в очередь. Пул (pgxpool) переиспользует соединения; без rows.Close() они не возвращаются, и пул забивается. → 19 — Работа с базами данных → Пул соединений

вопросКак защититься от SQL-инъекций?

Только параметризованные запросы — плейсхолдеры $1, $2 или query builder; никакой конкатенации с пользовательским вводом. → 19 — Работа с базами данных → SQL-инъекции и плейсхолдеры

вопросКак сделать транзакцию в pgx?

tx, err := pool.Begin(ctx), сразу defer tx.Rollback(ctx), операции через tx, в конце tx.Commit(ctx). Откат после коммита ничего не делает. → 19 — Работа с базами данных → Транзакции

вопросЗачем переводить ошибки базы в доменные?

Чтобы бизнес-логика не зависела от драйвера: pgx.ErrNoRows → ErrNotFound, код 23505 → ErrAlreadyExists; хендлер переводит доменные ошибки в 404 и 409. → 19 — Работа с базами данных → Маппинг ошибок

вопросЧто такое миграции и как они применяются?

Версионированные изменения схемы с секциями up и down. Инструмент (goose, golang-migrate) хранит применённые версии в служебной таблице и при старте накатывает новые по порядку. → 19 — Работа с базами данных → Миграции

How to use this page

  • Once a week, take 10 random questions from different sections — the interleaving strengthens memory better than repetition in a row.
  • Answer out loud, as at an interview: the term → how it works → an example from code.
  • Could not answer — open the chapter by the link and add the question to Go from Scratch.
  • Solve the "what does this print" tasks on paper first, then run the code.

Language basics

questionWhy do people choose Go, and where is it used?

Compiled, fast, with built-in concurrency and simple syntax; builds into a single binary. Used for backends and APIs, microservices, infrastructure (Kubernetes, Docker, Prometheus), network services, and the cloud. → 01 — What is Go and why learn it

questionHow does := differ from var? Where can := not be used?

:= declares a variable and infers the type; var can be used with an explicit type and without a value. := works only inside functions; at the package level — only var. A repeated := with no new variables on the left is an error. → 03 — Variables and constants → Three ways to declare a variable

self-checkWhat is a zero value? Name them for the main types.

The value Go gives an uninitialized variable — there is no garbage. Numbers — 0, a string — "", bool — false, pointers, slices, maps, channels, functions, and interfaces — nil, a struct — the zero values of all its fields. → 04 — Data types and conversions → Zero values

questionWhy can len of a string be greater than its character count? What is a rune?

A string is UTF-8 bytes, len counts bytes, and a non-ASCII character takes 2 or more bytes. A rune is a Unicode code point, an alias for int32; characters are counted by utf8.RuneCountInString, and range over a string walks by runes. → 04 — Data types and conversions → rune: a single character

questionWhy can't you add an int and a float64?

Go is strictly typed and does not convert types implicitly. An explicit conversion is required: float64(n) * f. With int(f) the fractional part is dropped. → 04 — Data types and conversions → Type conversions

questionWhat is shadowing, and why is it dangerous?

Declaring, via := in a nested block, a variable with the same name as one outside. A new variable appears; the outer one stays unchanged. The typical bug is with err inside an if. → 05 — Functions → Shadowing

questionHow are arguments passed to functions in Go?

Always by value — the function gets a copy. For slices, maps, and channels the small header with a reference to shared data is copied, so element changes are visible outside. To change the variable itself, pass a pointer. → 05 — Functions → Pass by value

questionHow do you make a function or a field visible from another package?

Start the name with a capital letter — it is exported. Lowercase — private to the package. → 05 — Functions → Exporting: capitalization

questionIs break needed in a switch? What does fallthrough do?

break is not needed: one branch runs, there is no fallthrough. fallthrough unconditionally executes the body of the next case without checking its condition. → 08 — Switch-case

Slices and maps

questionHow does a slice differ from an array?

An array has a fixed size that is part of the type ([3]int ≠ [5]int); on assignment and passing it is copied whole. A slice is a header (a pointer to an array, len, cap) over an array; the size is dynamic, and only the header is copied. → 09 — Arrays and slices → Why arrays are almost never used

questionWhat is inside a slice, and how much does it take?

Three fields: a pointer to the first element of the window into the array, the length, and the capacity — 24 bytes on a 64-bit system. The array itself lives separately. → 09 — Arrays and slices → Under the hood

questionHow does append work, and why do people write s = append(s, x)?

If capacity suffices — it writes into the same array and grows the length. If not — it allocates a bigger array (doubling up to 256 elements, slower afterwards), copies the data, and returns a slice over the new array. Without the assignment, the variable keeps the old header. → 09 — Arrays and slices → append: adding elements

questionHow does a nil slice differ from an empty one?

A nil slice has no array and equals nil; an empty one has an array. Both have length 0; range and append work with both. In JSON: null versus []. → 09 — Arrays and slices → The nil slice

questionHow can slicing cause a memory leak, and how do you avoid it?

A small slice of a huge array keeps the whole array alive, and GC will not collect it. Copy the needed part: copy into a new slice or slices.Clone. → 09 — Arrays and slices → Memory leaks from slicing

questionWhat happens when writing to a nil map? And when reading?

Writing — panic: assignment to entry in nil map. Reading — the zero value, no panic. → 10 — Maps → The nil map trap

questionHow do you tell a missing key from a zero value?

comma-ok: v, ok := m[k] — ok == false when the key is absent. → 10 — Maps → Reading, writing, and deleting

questionWhich types can be map keys?

Only comparable ones: numbers, strings, bool, pointers, channels, interfaces, arrays, and structs of comparable fields. Slices, maps, and functions — no. → 10 — Maps → Which types can be keys

questionHow is a Go map built?

Before Go 1.24: an array of 8-pair buckets, tophash — the top 8 bits of the hash per slot for quick rejection, overflow bucket chains on overflow, doubling growth with gradual evacuation. Since Go 1.24 — Swiss Tables: groups of 8 slots with a 64-bit control word, the hash split into h1 (57 bits, group selection) and h2 (7 bits, in the control word), h2 compared against all slots of a group at once, collisions by open addressing, the map split into tables of up to 1024 entries. → 10 — Maps → How a map works

questionWhy is map iteration order random?

Go deliberately randomizes it so code does not rely on the order. For a stable order, sort the keys: slices.Sorted(maps.Keys(m)). → 10 — Maps → Iteration and order

questionCan you write to a map from several goroutines?

No — fatal error: concurrent map writes, which recover cannot catch. You need sync.Mutex / sync.RWMutex or sync.Map. → 10 — Maps → Maps and goroutines

Task. What does the program print?

go
package main

import "fmt"

func grow(s []int) {
    s = append(s, 4)
    s[0] = 100
}

func main() {
    a := []int{1, 2, 3}
    grow(a)

    b := make([]int, 3, 10)
    copy(b, []int{1, 2, 3})
    grow(b)

    fmt.Println(a, b, b[:4])
}
self-check
text
[1 2 3] [100 2 3] [100 2 3 4]

a has capacity 3: the append inside grow allocated a new array, and s[0] = 100 landed there — a did not change. b has capacity 10: append wrote 4 into the shared array, and s[0] = 100 hit the shared array too. b's length stayed 3, but b[:4] reveals the appended element.

Task. What does the program print?

go
package main

import "fmt"

func main() {
    m := map[string]int{"a": 1}
    v := m["b"]
    _, ok := m["b"]
    m["c"]++
    fmt.Println(v, ok, len(m), m["c"])
}
self-check
text
0 false 2 1

A missing key yields the zero value; comma-ok gives false. m["c"]++ reads 0 and writes 1, so the map now has two keys.

Pointers and functions

questionWhat is a pointer? What do & and * do?

A variable's address in memory. &x takes the address; *p reads or writes the value at the address. A pointer's zero value is nil, and it must not be dereferenced. → 11 — Pointers → & and *

questionWhen should you pass a value by pointer?

When the function must change the original, when the struct is big and copying is expensive, when you need an optional value (nil — "not set"). → 11 — Pointers → Summary

questionIs it safe to return a pointer to a local variable? What is escape analysis?

Safe. The compiler sees that the variable "escapes" the function and allocates it on the heap; GC frees it when no references remain. That is escape analysis; see the decisions with go build -gcflags=-m. → 11 — Pointers → Returning a pointer to a local variable

questionShould you pass a slice or a map by pointer?

Usually no: it already contains a pointer to the data, and element changes are visible outside. The exception is append inside a function: the length change is not visible, so the slice is returned. → 11 — Pointers → Reference types

questionWhat is a closure? What changed with the loop variable in Go 1.22?

A function that captures its surrounding variables by reference. Since Go 1.22 the loop variable is new on each iteration, so closures and goroutines in a loop see "their own" value; before, they saw the last one. → 12 — Advanced functions → Closures

questionWhat is a variadic function?

A function whose last parameter is ...T: it accepts any number of arguments, and inside it is a []T; a ready slice is passed as s.... Examples — append, fmt.Println. → 12 — Advanced functions → Variadic functions

Errors, defer, and panic

questionHow are errors handled in Go, and how does that differ from exceptions?

An error is an error interface value that the function returns last. The caller checks if err != nil right away and decides what to do; nothing unwinds the stack by itself. → 13 — Error handling → An error is a value

questionHow does %w differ from %v in fmt.Errorf?

%w wraps the error and keeps the link to the cause — errors.Is and errors.As will find it. %v only interpolates the text. → 13 — Error handling → Context: wrapping with %w

questionHow does errors.Is differ from errors.As?

Is looks for a concrete value (a sentinel error) in the chain and returns a bool. As looks for an error of a certain type and writes it into the passed pointer, giving access to fields. → 13 — Error handling → Custom error types and errors.As

questionWhat is a sentinel error?

A package-level error value declared in advance, e.g. var ErrNotFound = errors.New("not found"), recognized via errors.Is. Declared once, because two errors.New with the same text are different values. → 13 — Error handling → Sentinel errors

questionIn what order do defer calls run, and when are their arguments evaluated?

In reverse order (LIFO) on function exit — both on return and on panic. Arguments are evaluated at the moment of the defer itself; to read a value at exit, use a closure. → 14 — defer, panic, recover → defer: a deferred call

questionHow does recover work, and will it catch a panic from another goroutine?

It works only inside a deferred function; it stops the panic and returns its value, and the function then finishes. A panic from another goroutine is not caught — protection goes inside each goroutine. → 14 — defer, panic, recover → recover

questionWhen should you use panic, and when an error?

An error — for expected situations: input, network, files, validation. panic — for bugs and broken invariants, e.g. a missing required config at startup. In doubt — an error. → 14 — defer, panic, recover → panic or error

questionWhat is wrong with defer inside a loop?

Deferred calls pile up until the function exits — files and connections stay open. Move the iteration body into a separate function. → 14 — defer, panic, recover → defer in a loop — a trap

Task. What does the program print?

go
package main

import "fmt"

func f() (result int) {
    defer func() { result++ }()
    return 10
}

func g() int {
    x := 10
    defer func() { x++ }()
    return x
}

func main() {
    fmt.Println(f(), g())
}
self-check
text
11 10

In f the result is named: return 10 writes 10 into result, then the defer increments it. In g the result is unnamed: return x already copied 10, and the defer changes the local x, which does not affect the result.

Structs and interfaces

questionHow is OOP implemented in Go?

No classes: structs with methods. Encapsulation — through the case of the first letter. No inheritance — composition through embedding. Polymorphism — through interfaces with implicit implementation. → 15 — Structs → OOP in Go

questionHow does a value receiver differ from a pointer receiver?

By value, the method works on a copy and does not change the original. By pointer — it changes the original and does not copy the struct. If at least one method needs a pointer, usually all methods get pointers. → 15 — Structs → Methods

questionIs embedding inheritance?

No. The embedded struct's fields and methods are "lifted" upward, but the outer type does not become the embedded one and cannot be substituted for it. Interchangeability comes from interfaces. → 15 — Structs → Embedding: composition instead of inheritance

questionHow much memory does struct{} take, and where is it used?

0 bytes. In sets map[T]struct{} and signal channels chan struct{}. → 15 — Structs → Empty struct

questionWhat is an interface, and what does "implicit implementation" mean?

A set of method signatures — a behavior contract. A type implements the interface automatically if it has all the methods; nobody writes implements, and the type may not even know about the interface. → 16 — Interfaces → Interface: a behavior contract

questionWhy is an interface holding a nil pointer not equal to nil?

An interface stores a "type + value" pair and equals nil only when both are empty. Put in (*T)(nil) — the type is recorded, so the interface is not empty. The classic bug: a function with an error result returns a nil variable of a concrete type, and err != nil. → 16 — Interfaces → The nil interface trap

questionHow do you extract the concrete type from any?

A type assertion: v, ok := x.(T) — safe; v := x.(T) panics on a mismatch. For several types — a type switch switch v := x.(type). → 16 — Interfaces → any: the empty interface

questionWhy might a value T fail to implement an interface while *T does?

A method with a pointer receiver is only in the method set of *T. You cannot put the value T into the interface: method has pointer receiver. → 16 — Interfaces → Polymorphism

questionWhat are generics, and how do they differ from interfaces?

Functions and types with type parameters (Go 1.18+): func Max[T cmp.Ordered](a, b T) T. An interface — shared behavior of different types, chosen at runtime; a generic — one algorithm for different types, substituted at compile time. Type parameter constraints are defined by interfaces. → 16 — Interfaces → Generics

Concurrency

questionHow does a goroutine differ from an OS thread? What is the GMP model?

A goroutine is lightweight: a stack of a couple of kilobytes that grows as needed, switched by the Go scheduler, not the kernel. G — goroutine, M — OS thread, P — scheduler context with a queue of goroutines; the number of P is set by GOMAXPROCS. Thousands of goroutines run on a few threads (M:N). → 17 — Concurrency — goroutines and channels → Goroutines

questionHow do you wait for goroutines to finish?

sync.WaitGroup: Add(1) before the start, defer wg.Done() inside the goroutine, Wait() in the waiting code; or wg.Go(f). Or channels. time.Sleep is not synchronization. → 17 — Concurrency — goroutines and channels → sync.WaitGroup

questionHow does an unbuffered channel differ from a buffered one?

In an unbuffered one the sender and the receiver wait for each other — it is a synchronization point. In a buffered one the send does not block until the buffer is full, and the read — until it is empty. → 17 — Concurrency — goroutines and channels → Channels

questionWhat happens on send, receive, and close with a nil channel and a closed channel?

A nil channel: send and receive block forever, close panics. A closed one: send panics, receive drains the remaining values, then the zero value and ok == false; a repeated close panics. Only the sender closes a channel. → Go cheat sheet → Concurrency

questionHow does select work?

It waits for one of the channels to become ready and runs its case; if several are ready — it picks a random one. Without default it blocks; with default it is a non-blocking check. A timeout — case <-time.After(d). → 17 — Concurrency — goroutines and channels → select

questionWhat is a data race, and how do you find one?

Several goroutines accessing the same variable simultaneously, at least one being a write, without synchronization. Found with the -race flag: go test -race ./.... Treated with a mutex, atomics, or channels. → 17 — Concurrency — goroutines and channels → sync.Mutex

questionMutex or channels — when and which?

Channels — for passing data and coordination ("share memory by communicating"). A mutex — for protecting shared state: a counter, a cache, a map. → 17 — Concurrency — goroutines and channels → sync.Mutex

questionWhat are a deadlock and a goroutine leak?

A deadlock — every goroutine is blocked; Go dies with all goroutines are asleep - deadlock!. A leak — a goroutine stuck forever, e.g. sending into a channel nobody reads; fixed with a buffer, closing the channel, or cancellation via context. → 17 — Concurrency — goroutines and channels → select

questionWhy do you need a worker pool?

To limit the number of simultaneous operations: a fixed number of workers reads tasks from the jobs channel and writes results into results; after sending the tasks, jobs is closed. → 17 — Concurrency — goroutines and channels → Worker pool

questionWhat is context, and why call cancel?

A mechanism for carrying cancellation and deadlines: WithCancel, WithTimeout, WithDeadline; ctx.Done() closes on cancellation, ctx.Err() explains the reason. cancel releases the context's resources — always call it, usually via defer. → 17 — Concurrency — goroutines and channels → context: cancellation and deadlines

Task. What does the program print?

go
package main

import "fmt"

func main() {
    ch := make(chan int, 3)
    for i := range 3 {
        ch <- i * i
    }
    close(ch)

    sum := 0
    for v := range ch {
        sum += v
    }
    v, ok := <-ch
    fmt.Println(sum, v, ok, len(ch))
}
self-check
text
5 0 false 0

0, 1, and 4 went into the channel — their sum is 5. After the close, range drained the buffer and finished; any further read gives the zero value and false, and the buffer is empty.

Backend

questionHow is an HTTP server built on net/http?

The handler — func(w http.ResponseWriter, r *http.Request); routes are registered on http.ServeMux, since Go 1.22 with the method and parameters: "GET /users/{id}" and r.PathValue("id"). The server — http.Server with timeouts. → 18 — Backend — HTTP server → Endpoints, ServeMux, and API versions

questionWhy split a service into handler, service, and repository?

Separation of responsibility: transport, business logic, storage. A layer is changed without touching the rest; dependencies are passed through interfaces, which simplifies tests. → 18 — Backend — HTTP server → Application layers

questionWhy is WriteHeader called before writing the body?

The first body write implicitly sends status 200, and a late WriteHeader changes nothing. → 18 — Backend — HTTP server → Response: status before body

questionWhat is middleware, and in what order should it go?

A func(http.Handler) http.Handler — a layer around the handler for logs, request ID, recovery, CORS, authorization. In a chain, "the first in the list is the outermost"; Recovery goes outermost so it catches panics in the other layers too. → 18 — Backend — HTTP server → Middleware

questionHow do you test handlers without starting a server?

httptest.NewRequest — the request, httptest.NewRecorder — a fake response, call ServeHTTP, check the code and body; the repository is replaced with a stub through an interface. Convenient as a table-driven test. → 18 — Backend — HTTP server → Testing handlers

questionWhat is graceful shutdown?

On SIGINT or SIGTERM the server stops accepting new requests and lets in-flight ones finish within a timeout: srv.Shutdown(ctx). Plus the ReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeout timeouts. → 18 — Backend — HTTP server → Graceful shutdown and timeouts

questionWhy do you need a database connection pool?

Connections are expensive and limited, and a single connection serializes requests into a queue. The pool (pgxpool) reuses connections; without rows.Close() they are not returned and the pool clogs up. → 19 — Working with databases → Connection pool

questionHow do you protect against SQL injections?

Parameterized queries only — placeholders $1, $2 or a query builder; never concatenation with user input. → 19 — Working with databases → SQL injections and placeholders

questionHow do you make a transaction in pgx?

tx, err := pool.Begin(ctx), immediately defer tx.Rollback(ctx), operations through tx, and tx.Commit(ctx) at the end. A rollback after commit does nothing. → 19 — Working with databases → Transactions

questionWhy translate database errors into domain ones?

So business logic does not depend on the driver: pgx.ErrNoRows → ErrNotFound, code 23505 → ErrAlreadyExists; the handler maps domain errors to 404 and 409. → 19 — Working with databases → Error mapping

questionWhat are migrations, and how are they applied?

Versioned schema changes with up and down sections. The tool (goose, golang-migrate) keeps applied versions in a bookkeeping table and applies the new ones in order at startup. → 19 — Working with databases → Migrations

// related topics and cheatsheets