Вопросы для подготовки к собеседованию по Go на русском и английском

Как готовиться?
  1. Читаем на русском, затем на английском

Типы данных

Что такое Golang?
What is Golang?
Golang — это компилируемый многопоточный язык программирования, разработанный в Google в 2007–2009 годах Робертом Гризмером, Робом Пайком и Кеном Томпсоном для создания высокопроизводительных систем. Он сочетает простоту синтаксиса (как у Python) с производительностью C/C++, поддерживает конкурентность через горутины и применяется в серверных приложениях, облаках и DevOps


Golang is a compiled multithreaded programming language developed at Google in 2007-2009 by Robert Griesmer, Rob Pike and Ken Thompson to create high—performance systems. It combines the simplicity of the syntax (like Python) with the performance of C/C++, supports competitiveness through goroutines, and is used in server applications, clouds, and DevOps.

Как проверить версию Go?
How do I check the version of Go?
Проверка версии Go выполняется командой go version в терминале, которая выводит установленную версию, например, "go version go1.23.1 linux/amd64".

The Go version check is performed by the go version command in the terminal, which outputs the installed version, for example, "go version go1.23.1 linux/amd64".

Что такое GOPATH?
What is GOPATH?
GOPATH — это переменная окружения, указывающая директории для рабочих пространств: исходного кода (src), пакетов (pkg) и бинарников (bin); актуальна для проектов без модулей.

GOPATH is an environment variable that specifies directories for workspaces: source code (src), packages (pkg), and binaries (bin); relevant for projects without modules.


Что такое GOROOT?
What is GOROOT?
GOROOT — переменная, указывающая корневую директорию установки Go (бинарники, исходники stdlib); обычно задается автоматически и не требует ручной настройки.

GOROOT is a variable that specifies the root directory of the Go installation (binaries, stdlib sources); it is usually set automatically and does not require manual configuration.


Какие есть типы данные в Go?
What types of data are there in Go?
Типы данных в Go включают целые (int, uint и их вариации), с плавающей точкой (float32, float64), bool, string, byte (alias uint8), rune (alias int32), а также составные: массивы, срезы, мапы, каналы, структуры, указатели, функции, интерфейсы.

Data types in Go include integers (int, uint and their variations), floating-point (float32, float64), bool, string, byte (alias uint8), rune (alias int32), as well as composite ones: arrays, slices, maps, channels, structures, pointers, functions, interfaces.

Чем отличаются int, int8, int16, int32, int64?
What is the difference between int, int8, int16, int32, int64?
Они отличаются размером и диапазоном: int8 (8 бит, -128..127), int16 (16 бит, -32768..32767), int32 (32 бита), int64 (64 бита); все со знаком

They differ in size and range: int8 (8 bits, -128..127), int16 (16 bits, -32768..32767), int32 (32 bits), int64 (64 bits); all signed
От чего зависит размер типа int?
What determines the size of the int type?
Размер int зависит от архитектуры: 32 бита на 32-битных системах, 64 бита на 64-битных.

The size of an int depends on the architecture: 32 bits on 32-bit systems, 64 bits on 64-bit systems.
Что произойдёт при переполнении uint?
What happens when the uint overflows?
Переполнение uint приводит к обертыванию (wraparound): максимум+1 становится 0

Uint overflow leads to wrapping (wraparound): the maximum of +1 becomes 0
Какие проблемы возникают при приведении int64 к int на 32-битной системе?
What problems arise when converting int64 to int on a 32-bit system?
Приведение int64 к int на 32-битной системе обрезает старшие биты, вызывая потерю данных для |x| > 2^31-1

Uint overflow leads to wrapping (wraparound): the maximum of +1 becomes 0
Какие типы чисел с плавающей точкой есть в Go?
What types of floating point numbers are there in Go? (🔊)
Типы float — float32 (32 бита) и float64 (64 бита, по умолчанию).

Float types are float32 (32 bits) and float64 (64 bits, by default).
Почему нельзя сравнивать float значения через ==?
Why can't float values be compared using ==?
Сравнение float == ненадёжно из-за неточности представления (округления, машинный эпсилон).

Float comparison with equality operator (==) is unreliable due to inaccuracy of representation (rounding, machine epsilon).
Как корректно сравнивать float значения?
How can float values be compared correctly?
Правильно — сравнивать с допуском: math.Abs(a-b) ≤ epsilon, где epsilon примерно 1e-9.

That's right, compare with the tolerance: math.Abs(a-b) ≤ epsilon, where epsilon is approximately 1e-9.
Почему нельзя использовать float для денежных расчётов?
Why can't float be used for financial calculations?
Float не для денег — неточность binary floating-point приводит к ошибкам вроде 0.1+0.2 != 0.3; используйте decimal или int (копейки).

Float is not for money — the inaccuracy of binary floating-point leads to errors like 0.1+0.2 != 0.3; use decimal or int (pennies).
Что такое строка в Go и в какой кодировке она хранится?
What is a string in Go and in what encoding is it stored?
Строка в Go — неизменяемая последовательность байт в UTF-8.

A string in Go is an immutable sequence of bytes in UTF-8.
В чём разница между len(s) и количеством символов в строке?
What is the difference between len(s) and the number of characters in a string?
len(s) vs символы — len возвращает байты, а не руны (символы); для кириллицы (2+ байта) len > utf8.RuneCountInString(s).

len(s) vs characters — len returns bytes, not runes (characters); for Cyrillic (2+ bytes) len > utf8.RuneCountInString(s).
Что такое rune (руна)?
What is rune?
Rune — int32 для Unicode code point (символ); []rune(s) декодирует UTF-8

Rune — int32 for Unicode code point (character); []rune(s) decodes UTF-8
Что такое zero value в Go?
What is zero value in Go?
Zero value — значение по умолчанию для инициализированных переменных.

Zero value is the default value for initialized variables.
Какие zero value (нулевые значения) у int, float, bool, string?
What is the zero value - int, float, bool, string?
Нулевые значения: int — 0, float — 0.0, bool — false, string — "".

Zero values: Int is zero, float is zero point zero, boolean is false, string is empty double quotes
Почему строки в Go неизменяемы?
Why are strings immutable in Go?
Строки неизменяемы, чтобы обеспечить безопасность потоков и неизменность в структурах без копирования

Strings are immutable to ensure thread safety and immutability in structures without copying.
Как получить корректно первый символ строки, если там содержится кириллица или иероглифы?
How do I get the first character of a string correctly if it contains Cyrillic or hieroglyphs?
Нужно преобразовать строку в срез рун и взять индекс 0
fmt.Printf("%c\n", []rune("Коля")[0])
или пройтись по строке циклом for range и выйти после первой итерации
word2 := "你好"
for _, r := range word2 {
fmt.Printf("%c\n", r)
break
}

You need to convert the string to a rune slice and take the element at index0 or iterate through the string with a for range loop and exit after the first iteration.

Сколько памяти занимает тип bool в Go и почему именно столько?
How much memory does the bool type take up in Go and why exactly that much?
bool занимает 1 байт (не 1 бит) для выравнивания памяти в структурах (padding)

bool takes 1 byte (not 1 bit) for memory alignment in structures (padding)

Что выведет код?
What is the output of the code?
Будет ошибка компилляции "cannot assign to s[0]", потому что строки неизменяемы.

There will be a compilation error "cannot assign to s[0]" because strings are immutable.

Какие есть проблемы? Как решить? (см. код)
What are the problems? How to solve them?
Есть три проблемы:
1. строки в Go неизменяемы, поэтому на каждой итерации создаётся новая строка, поэтому память расходуется неэффективно. Решение - использовать strings.Builder
2. число с точкой выглядит как float, для счетчика нужен int. Решение - убрать точку или использовать _(нижнее подчеркивание)
3. преобразование числа в строку через fmt.Sprintf("%d", i) медленнее, чем прямые методы (strconv.Itoa). Решение - использовать strconv.Itoa

финальный код

There are three problems:
1. Strings in Go are immutable, so a new string is created at each iteration, so memory is used inefficiently. The solution is to use strings.Builder
2. A number with a dot looks like a float, but an int is needed for the counter. The solution is to remove the dot or use _(underline)
3. Converting a number to a string using fmt.Sprintf("%d", i) is slower than direct methods (strconv.Itoa). The solution is to use strconv.Itoa

Что выведет код и почему?
What is the output of the code?
Код выведет
Длина через Len: 8
Длина через RuneCountInString: 5
Потому что в Go строка — это последовательность байт в UTF‑8, и len(str) считает байты, а не символы, в кириллице одна буква зачастую представлена двумя байтами. utf8.RuneCountInString считает руны (Unicode‑символы) и даёт их реальное количество

The code will output
Length via Len: 8
Length via RuneCountInString: 5

Because in Go, a string is a sequence of bytes in UTF—8, and len(str) counts bytes rather than characters, in Cyrillic, one letter is often represented by two bytes. utf8.RuneCountInString counts runes (Unicode characters) and gives their real number

Какие есть проблемы? Как решить? (см. код)
What are the problems? How to solve them?
Проблема в том, что цикл for выведет обходит строку по байтово, а эмодзи занимает несколько байтов. Корректнее использовать range.

финальный код

The problem is that the for loop outputs a byte-by-byte traversal of the string, while the emoji takes up several bytes. It is more correct to use range.

Типы данных: map

вопросы на собеседовании
Что такое map в Go и как устроен внутри?
What is a map in Go and how does it work inside?
Map — встроенная хеш-таблица, хранящая пары ключ-значение. Внутри реализована с помощью массива бакетов и хеш-функции.

Map is an embedded hash table that stores key-value pairs. It is implemented internally using an array of buckets and a hash function.

Какие типы можно использовать в качестве ключей?
What types can be used as keys?
Comparable-типы: числа, строки, указатели, структуры с comparable-полями.

Comparable types: numbers, strings, pointers, structures with comparable fields.

Почему нельзя использовать слайсы, функции или другие map в качестве ключей?
Why can't you use slices, functions, or other maps as keys?
Эти типы несравнимы (== не определён), а map требует операции сравнения для проверки уникальности ключей.

These types are not comparable (equality check is undefined), but a map requires comparison operation to ensure the uniqueness of keys.

Потокобезопасна ли map?
Is the map thread-safe?
Нет. Для безопасного конкурентного доступа используются Mutex или sync.Map.

No. Mutex or sync.Map are used for secure competitive access.

Что произойдёт, если несколько горутин одновременно запишут в map без синхронизации?
What will happen if several goroutines write to a map simultaneously without synchronization?
Рантайм детектирует гонку и вызовет panic «fatal error: concurrent map writes»

The runtime detects the race condition and will trigger a panic with the message «fatal error: concurrent map writes».

Как проверить наличие ключа?
How do I check the availability of the key?
Через второй возвращаемый параметр: value, ok := m[key]

Through the second returned parameter: value, ok := m[key]