Part 2. Language BasicsLesson 04# go# basics# types

Data types and conversions

numbers, strings, runes, bool, a zero values table, explicit conversions

Цели главы

  • Знать базовые типы и когда какой выбирать.
  • Понимать, почему float не годится для денег.
  • Отличать string от rune и байты от символов.
  • Помнить нулевые значения всех типов.
  • Делать явные преобразования и понимать, что при этом теряется.

Строгая типизация

Каждая переменная в Go привязана к конкретному типу, и Go не смешивает типы молча: сложить строку и число или int с float64 не получится — код просто не скомпилируется. Это плюс: строгая типизация ловит ошибки на этапе компиляции, а не в продакшене.

Целые числа

int — основной тип для целых. На 64-битных системах он 64-битный, этого хватает для любых повседневных задач. Подчёркивания в числовых литералах игнорируются — они только для читаемости: 1_500_000.

Тип Диапазон
int8 от −128 до 127
int16 от −32 768 до 32 767
int32 примерно ±2,1 миллиарда
int64 примерно ±9,2 квинтиллиона (9·10¹⁸)
uint8 (он же byte) от 0 до 255

В 99% случаев хватает обычного int; типы с фиксированным размером нужны для протоколов, файлов и экономии памяти.

go
package main

import (
    "fmt"
    "math"
)

func main() {
    var zeroInt int
    views := 1_500_000
    fmt.Println(zeroInt, views)

    fmt.Println(math.MinInt8, math.MaxInt8)
    fmt.Println(math.MinInt16, math.MaxInt16)
    fmt.Println(math.MaxInt32, math.MaxInt64)

    var level int8 = 127
    level++ // переполнение в рантайме молча «заворачивается»
    fmt.Println(level)
}
stdout // вывод программы
0 1500000
-128 127
-32768 32767
2147483647 9223372036854775807
-128

Дробные числа

Для дробей есть float32 и float64. float64 точнее — около 15–17 значащих цифр — и используется по умолчанию; float32 хранит около 7 значащих цифр и нужен редко, ради экономии памяти. Короче: всегда бери float64.

go
package main

import "fmt"

func main() {
    var zeroFloat float64
    avg := 85.5
    fmt.Println(zeroFloat, avg)

    a, b := 0.1, 0.2
    fmt.Println(a + b)     // ошибка двоичного представления
    fmt.Println(0.1 + 0.2) // константы складываются точно ещё при компиляции

    priceKopecks := 99_900 // 999 рублей 00 копеек
    fmt.Printf("%d.%02d руб.\n", priceKopecks/100, priceKopecks%100)
}
stdout // вывод программы
0 85.5
0.30000000000000004
0.3
999.00 руб.

Строки

string — последовательность символов в двойных кавычках; нулевое значение — пустая строка. Строка в обратных кавычках (raw string) переносится как есть, со всеми переводами строк, а escape-последовательности вроде \n в ней не работают. Это удобно для многострочного текста, путей, JSON и SQL.

go
package main

import "fmt"

func main() {
    var zeroString string
    title := "Интерстеллар"
    fmt.Printf("[%s] [%s]\n", zeroString, title)

    synopsis := `Строка в обратных кавычках
переносится как есть,
а \n здесь — просто два символа`
    fmt.Println(synopsis)
}
stdout // вывод программы
[] [Интерстеллар]
Строка в обратных кавычках
переносится как есть,
а \n здесь — просто два символа

rune — один символ

rune — один символ в одинарных кавычках. На самом деле это число: код символа в Unicode (тип rune — псевдоним int32). Поэтому Println печатает число, а чтобы увидеть сам символ, нужен плейсхолдер %c.

go
package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    var letter rune = 'A'
    fmt.Println(letter)        // rune хранит код символа
    fmt.Printf("%c\n", letter) // %c печатает сам символ
    fmt.Println('Я', '⭐')

    word := "Фильм"
    fmt.Println(len(word), utf8.RuneCountInString(word))
}
stdout // вывод программы
65
A
1071 11088
10 5

bool

bool принимает только true или false; нулевое значение — false. Используется в условиях, фильтрах и флагах: isPremium, hasSubtitles.

Нулевые значения

Go гарантирует: объявленная без значения переменная содержит не мусор, а предсказуемое нулевое значение (zero value).

Тип Нулевое значение
int, int8…int64, uint, byte, rune, float32, float64 0
string "" — пустая строка
bool false
указатель *T, слайс []T, мапа map[K]V, канал chan T, функция, интерфейс nil
структура каждое поле — нулевое значение своего типа
массив [N]T каждый элемент — нулевое значение T
go
package main

import "fmt"

func main() {
    var (
        i  int
        f  float64
        s  string
        b  bool
        p  *int
        sl []int
        m  map[string]int
    )
    fmt.Printf("%v %v %q %v %v %v %v\n", i, f, s, b, p, sl, m)
    fmt.Println(p == nil, sl == nil, m == nil)
}
stdout // вывод программы
0 0 "" false <nil> [] map[]
true true true

Преобразование типов

Go не конвертирует типы автоматически: int и float64 нельзя перемножить напрямую.

go
episodes := 8
avgLength := 52.5
total := episodes * avgLength // invalid operation: episodes * avgLength (mismatched types int and float64)

Преобразование всегда явное и пишется как вызов: Тип(значение).

go
package main

import (
    "fmt"
    "strconv"
)

func main() {
    episodes := 8
    avgLength := 52.5

    total := float64(episodes) * avgLength // 8.0 * 52.5
    rough := episodes * int(avgLength)     // int(52.5) = 52 — дробная часть отброшена
    fmt.Println(total, rough)

    year := 2014
    fmt.Println(strconv.Itoa(year) + " год") // число → строка
    fmt.Println(string(rune(65)))            // из кода символа получаем символ

    n, err := strconv.Atoi("169") // строка → число, может вернуть ошибку
    fmt.Println(n+1, err)
}
stdout // вывод программы
420 416
2014 год
A
170 <nil>
  • Приводить «вверх» безопасно: float64(episodes) не теряет данных — получаем 420 минут.
  • Приводить «вниз» опасно: int(52.5) отбрасывает дробную часть, и вместо 420 выходит 416.
  • string(число) даёт не цифры, а символ с таким кодом. Число в строку переводят через strconv.Itoa или fmt.Sprint.

Практика

Домашнее задание: конвертеры для GoFlix

  1. Длительность фильма дана в секундах, например 8520. Переведи её в формат «X ч Y мин Z с» через деление / и остаток % и выведи через Printf.
  2. Размер файла фильма дан в байтах, например 4 831 838 208. Переведи в гигабайты через float64 и выведи с двумя знаками после точки.
решениеЭталонное решение
go
package main

import "fmt"

func main() {
    duration := 8520 // секунды
    hours := duration / 3600
    minutes := duration % 3600 / 60
    seconds := duration % 60
    fmt.Printf("Длительность: %d ч %d мин %d с\n", hours, minutes, seconds)

    size := 4_831_838_208 // байты
    gib := float64(size) / (1024 * 1024 * 1024)
    gb := float64(size) / 1e9
    fmt.Printf("Размер: %.2f ГиБ (%.2f ГБ)\n", gib, gb)
}
stdout // вывод программы
Длительность: 2 ч 22 мин 0 с
Размер: 4.50 ГиБ (4.83 ГБ)

Тренировка: предскажи вывод

go
package main

import "fmt"

func main() {
    fmt.Println(7/2, 7.0/2, 7%3, -7%3)
    f := 3.99
    fmt.Println(int(f))
}
самопроверкаОтвет
text
3 3.5 1 -1
3

Деление целых отбрасывает дробную часть; 7.0/2 — дробная константа, поэтому 3.5; знак остатка совпадает со знаком делимого. int(f) отбрасывает дробь без округления. А вот int(3.99) с константой не скомпилируется: cannot convert 3.99 (untyped float constant) to type int.

Проверь себя

вопросЧто значит «строгая типизация» и чем она полезна?

Каждая переменная привязана к типу, и типы не смешиваются без явного преобразования. Ошибки ловятся при компиляции, а не в продакшене.

вопросПочему деньги не хранят во float64 и как хранить правильно?

Дробные числа хранятся в двоичном виде с погрешностью: 0.1 + 0.2 даёт 0.30000000000000004. Деньги хранят в копейках или центах целым числом (int64).

вопросЧто такое rune и что напечатает fmt.Println('A')?

rune — код символа Unicode, псевдоним int32. Println('A') напечатает 65; символ печатают через %c.

вопросПочему len("Фильм") возвращает 10?

len считает байты, а строка хранится в UTF-8, где кириллическая буква занимает 2 байта. Символы считает utf8.RuneCountInString.

самопроверкаПеречисли нулевые значения для int, string, bool, слайса и мапы.

0, "", false, nil, nil.

вопросКак перевести int в строку и почему не через string(n)?

strconv.Itoa(n) или fmt.Sprint(n). string(n) вернёт символ с кодом n, а не цифры.


Ключевые выводы

  • 🧱 Go строго типизирован: типы не смешиваются, ошибки ловит компилятор.
  • 🔢 int — для целых, float64 — для дробей; деньги храни целыми копейками.
  • 🔤 string — байты в UTF-8, rune — код одного символа; len считает байты.
  • 0️⃣ У каждого типа есть нулевое значение: 0, "", false, nil.
  • 🔄 Преобразование только явное: float64(n), int(f); числа в строки — через strconv.

Chapter goals

  • Know the basic types and when to pick which.
  • Understand why float is wrong for money.
  • Tell string from rune, and bytes from characters.
  • Remember the zero values of all types.
  • Do explicit conversions and understand what gets lost along the way.

Strong typing

Every variable in Go is bound to a specific type, and Go never mixes types silently: you can't add a string to a number, or an int to a float64 — the code simply won't compile. That's a plus: strong typing catches errors at compile time, not in production.

Integers

int is the default type for integers. On 64-bit systems it's 64-bit, which is enough for any everyday task. Underscores in numeric literals are ignored — they exist purely for readability: 1_500_000.

Type Range
int8 from −128 to 127
int16 from −32 768 to 32 767
int32 roughly ±2.1 billion
int64 roughly ±9.2 quintillion (9·10¹⁸)
uint8 (aka byte) from 0 to 255

In 99% of cases plain int is enough; fixed-size types are needed for protocols, files, and saving memory.

go
package main

import (
    "fmt"
    "math"
)

func main() {
    var zeroInt int
    views := 1_500_000
    fmt.Println(zeroInt, views)

    fmt.Println(math.MinInt8, math.MaxInt8)
    fmt.Println(math.MinInt16, math.MaxInt16)
    fmt.Println(math.MaxInt32, math.MaxInt64)

    var level int8 = 127
    level++ // runtime overflow silently wraps around
    fmt.Println(level)
}
stdout // program output
0 1500000
-128 127
-32768 32767
2147483647 9223372036854775807
-128

Floating-point numbers

For fractions there are float32 and float64. float64 is more precise — about 15–17 significant digits — and is the default; float32 holds about 7 significant digits and is rarely needed, to save memory. Short version: always take float64.

go
package main

import "fmt"

func main() {
    var zeroFloat float64
    avg := 85.5
    fmt.Println(zeroFloat, avg)

    a, b := 0.1, 0.2
    fmt.Println(a + b)     // binary representation error
    fmt.Println(0.1 + 0.2) // constants are added exactly at compile time

    priceKopecks := 99_900 // 999 rubles, 00 kopecks
    fmt.Printf("%d.%02d RUB.\n", priceKopecks/100, priceKopecks%100)
}
stdout // program output
0 85.5
0.30000000000000004
0.3
999.00 RUB.

Strings

A string is a sequence of characters in double quotes; its zero value is the empty string. A string in backticks (a raw string) carries over as-is, with all the line breaks, and escape sequences like \n don't work inside it. Handy for multi-line text, paths, JSON, and SQL.

go
package main

import "fmt"

func main() {
    var zeroString string
    title := "Interstellar"
    fmt.Printf("[%s] [%s]\n", zeroString, title)

    synopsis := `A string in backticks
carries over as-is,
and \n here is just two characters`
    fmt.Println(synopsis)
}
stdout // program output
[] [Interstellar]
A string in backticks
carries over as-is,
and \n here is just two characters

rune: a single character

A rune is a single character in single quotes. It's actually a number: the character's Unicode code (the rune type is an alias for int32). That's why Println prints a number, and to see the character itself you need the %c placeholder.

go
package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    var letter rune = 'A'
    fmt.Println(letter)        // a rune holds the character's code
    fmt.Printf("%c\n", letter) // %c prints the character itself
    fmt.Println('Я', '⭐')

    word := "Фильм"
    fmt.Println(len(word), utf8.RuneCountInString(word))
}
stdout // program output
65
A
1071 11088
10 5

bool

bool takes only true or false; the zero value is false. Used in conditions, filters, and flags: isPremium, hasSubtitles.

Zero values

Go guarantees: a variable declared without a value holds not garbage, but a predictable zero value.

Type Zero value
int, int8…int64, uint, byte, rune, float32, float64 0
string "" — the empty string
bool false
pointer *T, slice []T, map map[K]V, channel chan T, function, interface nil
struct each field — the zero value of its type
array [N]T every element — the zero value of T
go
package main

import "fmt"

func main() {
    var (
        i  int
        f  float64
        s  string
        b  bool
        p  *int
        sl []int
        m  map[string]int
    )
    fmt.Printf("%v %v %q %v %v %v %v\n", i, f, s, b, p, sl, m)
    fmt.Println(p == nil, sl == nil, m == nil)
}
stdout // program output
0 0 "" false <nil> [] map[]
true true true

Type conversions

Go doesn't convert types automatically: int and float64 can't be multiplied directly.

go
episodes := 8
avgLength := 52.5
total := episodes * avgLength // invalid operation: episodes * avgLength (mismatched types int and float64)

A conversion is always explicit and written like a call: Type(value).

go
package main

import (
    "fmt"
    "strconv"
)

func main() {
    episodes := 8
    avgLength := 52.5

    total := float64(episodes) * avgLength // 8.0 * 52.5
    rough := episodes * int(avgLength)     // int(52.5) = 52 — the fraction is dropped
    fmt.Println(total, rough)

    year := 2014
    fmt.Println("Year: " + strconv.Itoa(year)) // number → string
    fmt.Println(string(rune(65)))              // a character's code gives the character

    n, err := strconv.Atoi("169") // string → number, may return an error
    fmt.Println(n+1, err)
}
stdout // program output
420 416
Year: 2014
A
170 <nil>
  • Converting "up" is safe: float64(episodes) loses no data — we get 420 minutes.
  • Converting "down" is dangerous: int(52.5) drops the fraction, and instead of 420 you get 416.
  • string(number) gives not the digits but the character with that code. A number becomes a string via strconv.Itoa or fmt.Sprint.

Practice

Homework: converters for GoFlix

  1. A movie's duration is given in seconds, for example 8520. Convert it to the "X h Y min Z s" format with division / and remainder % and print it with Printf.
  2. A movie file's size is given in bytes, for example 4_831_838_208. Convert it to gigabytes with float64 and print it with two digits after the point.
solution
go
package main

import "fmt"

func main() {
    duration := 8520 // seconds
    hours := duration / 3600
    minutes := duration % 3600 / 60
    seconds := duration % 60
    fmt.Printf("Duration: %d h %d min %d s\n", hours, minutes, seconds)

    size := 4_831_838_208 // bytes
    gib := float64(size) / (1024 * 1024 * 1024)
    gb := float64(size) / 1e9
    fmt.Printf("Size: %.2f GiB (%.2f GB)\n", gib, gb)
}
stdout // program output
Duration: 2 h 22 min 0 s
Size: 4.50 GiB (4.83 GB)

Exercise: predict the output

go
package main

import "fmt"

func main() {
    fmt.Println(7/2, 7.0/2, 7%3, -7%3)
    f := 3.99
    fmt.Println(int(f))
}
self-check
text
3 3.5 1 -1
3

Integer division drops the fraction; 7.0/2 is a fractional constant, hence 3.5; the remainder takes the sign of the dividend. int(f) drops the fraction without rounding. But int(3.99) with a constant won't compile: cannot convert 3.99 (untyped float constant) to type int.

Check yourself

questionWhat does "strong typing" mean and why is it useful?

Every variable is bound to a type, and types aren't mixed without an explicit conversion. Errors are caught at compile time, not in production.

questionWhy isn't money stored in float64, and what's the right way?

Fractional numbers are stored in binary with error: 0.1 + 0.2 gives 0.30000000000000004. Money is stored as an integer number of kopecks or cents (int64).

questionWhat is a rune and what does fmt.Println('A') print?

A rune is a Unicode character code, an alias for int32. Println('A') prints 65; the character is printed with %c.

questionWhy does len("Фильм") return 10?

len counts bytes, and the string is stored in UTF-8, where a Cyrillic letter takes 2 bytes. Characters are counted by utf8.RuneCountInString.

self-checkList the zero values for int, string, bool, a slice, and a map.

0, "", false, nil, nil.

questionHow do you convert an int to a string, and why not with string(n)?

strconv.Itoa(n) or fmt.Sprint(n). string(n) returns the character with code n, not the digits.


Key takeaways

  • 🧱 Go is strongly typed: types aren't mixed, the compiler catches the errors.
  • 🔢 int for integers, float64 for fractions; store money as whole kopecks.
  • 🔤 A string is UTF-8 bytes, a rune is one character's code; len counts bytes.
  • 0️⃣ Every type has a zero value: 0, "", false, nil.
  • 🔄 Conversions are explicit only: float64(n), int(f); numbers to strings — via strconv.
// related topics and cheatsheets