Part 5. Types & AbstractionsLesson 15# go# structs# oop# interview

Structs

OOP in Go, methods and receivers, embedding, tags, constructors

Цели главы

  • Объяснить, как в Go устроено ООП — частый вопрос собеседования.
  • Объявлять структуры, создавать их пятью способами, читать и менять поля.
  • Писать методы и выбирать получатель: по значению или по указателю.
  • Использовать встраивание, анонимные и пустые структуры, теги.
  • Писать функции-конструкторы.

Зачем структуры

До сих пор мы работали с переменными, функциями, слайсами и мапами. Но в GoFlix фильм — это не строка, а набор свойств: название, год, рейтинг. Подписчик — не просто имя, а ещё email и тариф; сессия просмотра хранит время начала, фильм и статус. Обновлять рейтинг, когда данные лежат в несвязанных переменных, неудобно. Нужен тип, который свяжет данные, — структура.

ООП в Go

Во многих языках ООП строится вокруг классов, наследования и полиморфизма. Go идёт другим путём:

Идея ООП Как в Go
Класс структура + методы
Инкапсуляция заглавная буква — экспортировано (как public), строчная — приватно для пакета (как private)
Наследование нет; вместо него — композиция: встраивание одной структуры в другую
Полиморфизм через интерфейсы — 16 — Интерфейсы
Зависимости передаются явно: через параметры и поля (Dependency Injection)

Для повторного использования кода структуры встраивают друг в друга, а не строят иерархии наследования.

Объявление и создание

Структура — набор именованных полей, у каждого свой тип. Объявляется через type Имя struct { … }. Поля одного типа можно записать в одну строку: Lat, Lng float64.

Способы создать структуру:

  1. var — все поля получают нулевые значения.
  2. Именованная инициализация — явно указываем, какое поле чему равно. Самый безопасный и читаемый способ, его рекомендуют официальные руководства.
  3. Позиционная — значения по порядку полей. Добавят поле — код сломается; годится только для очень простых структур.
  4. Частичная — часть полей явно, остальные получат нулевые значения.
  5. new(T) — указатель на структуру с нулевыми полями.
go
package main

import "fmt"

// Film — описание фильма в GoFlix.
type Film struct {
    Title    string
    Year     int
    Rating   float64
    Genre    string
    Duration int // минуты
}

func main() {
    var f1 Film                                              // все поля — нулевые значения
    f2 := Film{Title: "Дюна", Year: 2021, Rating: 8.1}       // именованная и частичная
    f3 := Film{"Интерстеллар", 2014, 8.6, "Фантастика", 169} // позиционная: все поля по порядку
    f4 := new(Film)                                          // указатель на структуру

    fmt.Printf("%+v\n%+v\n%+v\n%+v\n", f1, f2, f3, f4)
}
stdout // вывод программы
{Title: Year:0 Rating:0 Genre: Duration:0}
{Title:Дюна Year:2021 Rating:8.1 Genre: Duration:0}
{Title:Интерстеллар Year:2014 Rating:8.6 Genre:Фантастика Duration:169}
&{Title: Year:0 Rating:0 Genre: Duration:0}

%+v печатает структуру с именами полей — незаменимо при отладке.

Поля и указатели

К полю обращаются через точку: film.Title, sub.Email — как достать нужную вещь из коробки. Поле со строчной буквы не видно из других пакетов, поэтому публичные поля пишут с заглавной.

Структуры бывают объёмными, и копировать их дорого. К тому же изменить поля из функции можно только через указатель. Поэтому структуры часто передают по указателю — и обращаются к полям так же через точку: Go сам разыменует указатель (11 — Указатели → Указатели на структуры).

go
package main

import "fmt"

type Subscriber struct {
    Name  string
    Email string
    Age   int
    Plan  string
}

func main() {
    sub := Subscriber{Name: "Алексей", Email: "alex@goflix.ru", Age: 28, Plan: "Premium"}
    fmt.Println(sub.Name, sub.Plan) // чтение через точку
    sub.Plan = "Standard"           // запись

    p := &sub
    p.Age = 29 // через указатель меняем оригинал

    copied := sub
    copied.Name = "Копия" // копия — отдельная коробка
    fmt.Println(sub.Plan, sub.Age, sub.Name, copied.Name)
}
stdout // вывод программы
Алексей Premium
Standard 29 Алексей Копия

Аналогия: структура — коробка с вещами. Копия — отдельная коробка с тем же содержимым: меняешь её, оригинал не трогаешь. Указатель — бирка с местом хранения оригинальной коробки на складе: по ней находишь ту самую коробку и меняешь вещи прямо в ней.

Методы

Метод — функция, привязанная к типу. Тип указывают между func и именем метода — это получатель (receiver). Методы связывают поведение с данными.

go
package main

import "fmt"

type FilmCard struct {
    Title     string
    Year      int
    Rating    float64
    Watched   bool
    ViewCount int
}

// Info — получатель по значению: работает с копией и только читает поля.
func (f FilmCard) Info() string {
    return fmt.Sprintf("%s (%d), рейтинг %.1f", f.Title, f.Year, f.Rating)
}

// Watch — получатель по указателю: меняет исходную структуру.
func (f *FilmCard) Watch() {
    f.Watched = true
    f.ViewCount++
}

// RenameCopy пытается переименовать фильм через получатель по значению — не выйдет.
func (f FilmCard) RenameCopy(title string) {
    f.Title = title
}

func main() {
    card := FilmCard{Title: "Довод", Year: 2020, Rating: 7.8}
    card.Watch() // Go сам возьмёт адрес: (&card).Watch()
    card.Watch()
    card.RenameCopy("Tenet")
    fmt.Println(card.Info(), card.Watched, card.ViewCount)
}
stdout // вывод программы
Довод (2020), рейтинг 7.8 true 2

Как выбрать получатель:

По указателю (f *T) По значению (f T)
метод меняет состояние метод только читает поля
структура большая — копировать дорого структура маленькая
в структуре есть поле, которое нельзя копировать, например sync.Mutex тип по смыслу — значение: координаты, деньги

Встраивание — композиция вместо наследования

Наследования в Go нет, но одну структуру можно встроить в другую: записать тип без имени поля. Поля и методы встроенной структуры становятся доступны напрямую у внешней — их «продвигают» наверх. Аналогия — матрёшка: внутри AdminUser лежит Subscriber.

go
package main

import "fmt"

type Subscriber struct {
    Name  string
    Email string
    Plan  string
}

func (s Subscriber) Contact() string {
    return s.Name + " <" + s.Email + ">"
}

// AdminUser встраивает Subscriber: его поля и методы доступны напрямую.
type AdminUser struct {
    Subscriber
    AccessLevel string
    Department  string
}

func main() {
    admin := AdminUser{
        Subscriber:  Subscriber{Name: "Елена", Email: "e@goflix.ru", Plan: "Premium"},
        AccessLevel: "superadmin",
        Department:  "Billing",
    }
    fmt.Println(admin.Name)            // поле Subscriber доступно напрямую
    fmt.Println(admin.Subscriber.Plan) // полный путь тоже работает
    fmt.Println(admin.Contact())       // и методы тоже
}
stdout // вывод программы
Елена
Premium
Елена <e@goflix.ru>

Новая структура собирается из готовых частей и дополняется своими полями.

Анонимные структуры

Иногда данные нужно временно сгруппировать, а заводить отдельный тип незачем — его больше нигде не используют. Тогда структуру объявляют прямо на месте. Два частых сценария: разовая конфигурация и табличные тесты (table-driven tests), где каждый элемент слайса — входные данные и ожидаемый результат.

go
package main

import "fmt"

func discount(plan string) int {
    switch plan {
    case "Premium":
        return 20
    case "Standard":
        return 10
    default:
        return 0
    }
}

func main() {
    config := struct {
        Host string
        Port int
    }{Host: "api.goflix.ru", Port: 443}
    fmt.Printf("%s:%d\n", config.Host, config.Port)

    tests := []struct {
        plan string
        want int
    }{
        {"Premium", 20},
        {"Standard", 10},
        {"Free", 0},
    }
    for _, tt := range tests {
        got := discount(tt.plan)
        fmt.Printf("%-8s → %2d%% ok=%t\n", tt.plan, got, got == tt.want)
    }
}
stdout // вывод программы
api.goflix.ru:443
Premium  → 20% ok=true
Standard → 10% ok=true
Free     →  0% ok=true

Табличные тесты компактны и легко расширяются: новый случай — новая строка. В настоящих тестах такой цикл живёт в функции TestXxx и запускается командой go test — пример в 18 — Backend — HTTP-сервер → Тестирование хендлеров.

Пустая структура

У struct{} нет ни одного поля, поэтому она не хранит данных и занимает 0 байт. Её используют там, где важен сам факт наличия, а не данные. Самый частый пример — множество: map[string]struct{} вместо map[string]bool экономит память. Ещё один — сигнальные каналы (17 — Конкурентность — горутины и каналы → Сигнальный канал).

go
package main

import (
    "fmt"
    "maps"
    "slices"
    "unsafe"
)

func main() {
    fmt.Println(unsafe.Sizeof(struct{}{})) // размер в байтах

    genres := map[string]struct{}{"Фантастика": {}, "Драма": {}, "Комедия": {}}
    genres["Боевик"] = struct{}{} // добавить
    if _, exists := genres["Драма"]; exists {
        fmt.Println("Драма есть в наборе")
    }
    delete(genres, "Комедия") // удалить
    fmt.Println(slices.Sorted(maps.Keys(genres)))
}
stdout // вывод программы
0
Драма есть в наборе
[Боевик Драма Фантастика]

Теги

Тег — строка в обратных кавычках после типа поля. На саму структуру теги не влияют, это подсказки для библиотек. Самый известный пример — сериализация в JSON: тег json:"id" говорит пакету encoding/json, как называть поле. Тег db:"item_id" — подсказка библиотекам для работы с базой данных. В коде к полям по-прежнему обращаются по обычным именам: item.ID, item.Title.

go
package main

import (
    "encoding/json"
    "fmt"
)

type CatalogItem struct {
    ID        int     `json:"id" db:"item_id"`
    Title     string  `json:"title" db:"title"`
    Price     float64 `json:"price" db:"price"`
    Available bool    `json:"available" db:"is_available"`
    Internal  string  `json:"-"`              // не попадёт в JSON
    Note      string  `json:"note,omitempty"` // пустое значение пропускается
}

func main() {
    item := CatalogItem{ID: 1, Title: "Интерстеллар", Price: 12.99, Available: true, Internal: "служебное"}
    data, err := json.Marshal(item)
    if err != nil {
        fmt.Println("ошибка:", err)
        return
    }
    fmt.Println(string(data))
    fmt.Println(item.Title) // в коде — обычные имена полей
}
stdout // вывод программы
{"id":1,"title":"Интерстеллар","price":12.99,"available":true}
Интерстеллар

Сравнение и копирование

  • Структуры можно сравнивать ==, если все их поля сравнимы; сравнение идёт по каждому полю. Структуру со слайсом внутри сравнить нельзя: invalid operation: a == b (struct containing []string cannot be compared).
  • Присваивание структуры создаёт копию: изменения копии не затрагивают оригинал — это было видно на примере с copied выше.

Структуры в Go по умолчанию ведут себя как значения: и сравнение, и присваивание работают с содержимым, а не со ссылкой.

Конструкторы

Встроенных конструкторов, как в Java или C#, в Go нет. Есть идиома: функция NewТип(...) возвращает готовый экземпляр. В ней ставят значения по умолчанию, проверяют входные данные и инициализируют сложные поля — время старта, мьютекс. Обычно конструктор возвращает указатель: с объектом дальше работают без лишнего копирования.

go
package main

import (
    "errors"
    "fmt"
    "time"
)

type StreamSession struct {
    UserName  string
    MovieName string
    StartedAt time.Time
    IsActive  bool
}

// NewStreamSession проверяет данные и ставит значения по умолчанию.
func NewStreamSession(user, movie string) (*StreamSession, error) {
    if user == "" || movie == "" {
        return nil, errors.New("нужны пользователь и фильм")
    }
    return &StreamSession{
        UserName:  user,
        MovieName: movie,
        StartedAt: time.Now(),
        IsActive:  true,
    }, nil
}

func main() {
    s, err := NewStreamSession("Алексей", "Интерстеллар")
    if err != nil {
        fmt.Println("ошибка:", err)
        return
    }
    fmt.Println(s.UserName, s.MovieName, s.IsActive, !s.StartedAt.IsZero())

    _, err = NewStreamSession("", "Дюна")
    fmt.Println("ошибка:", err)
}
stdout // вывод программы
Алексей Интерстеллар true true
ошибка: нужны пользователь и фильм

Практика

Домашнее задание

  1. Профиль. Структура Profile: UserName, Email (string), Age (int), Country (string), Premium (bool). Создай заполненный профиль и выведи поля; затем профиль без инициализации; затем профиль, где заданы только UserName и Email.
  2. Устройство. Структура Device: Name, Type (string), Active (bool). Методы Info() string, Activate(), Deactivate(). Создай устройство, выведи состояние, активируй, выведи, деактивируй, выведи.
  3. Подписка. Структура Subscription: Plan (string), Price (float64), AutoRenew (bool). Конструктор NewSubscription(plan string, price float64) *Subscription ставит AutoRenew = true. Методы CancelAutoRenew() и PrintDetails(). Создай подписку, выведи, отключи автопродление, выведи снова.
  4. История просмотра. Episode с полями Title, Season, Duration и JSON-тегами title, season, duration. WatchHistory с полями Profile, Episode, WatchedPercent, LastPositionMin. Выведи имя, email, название эпизода, процент и позицию; переведи Episode в JSON.
  5. Избранное. FavoriteList со слайсом Titles []string. Методы Add(title string), PrintAll() и PrintUnique() — уникальные названия через map[string]struct{}. В main создай анонимную структуру статистики с полями Owner string и ItemsCount int.
решениеЭталонное решение
go
package main

import (
    "encoding/json"
    "fmt"
)

// Задание 1: профиль пользователя.
type Profile struct {
    UserName string
    Email    string
    Age      int
    Country  string
    Premium  bool
}

// Задание 2: устройство просмотра.
type Device struct {
    Name   string
    Type   string
    Active bool
}

func (d *Device) Info() string {
    status := "неактивно"
    if d.Active {
        status = "активно"
    }
    return fmt.Sprintf("%s (%s): %s", d.Name, d.Type, status)
}

func (d *Device) Activate() { d.Active = true }

func (d *Device) Deactivate() { d.Active = false }

// Задание 3: подписка с конструктором.
type Subscription struct {
    Plan      string
    Price     float64
    AutoRenew bool
}

func NewSubscription(plan string, price float64) *Subscription {
    return &Subscription{Plan: plan, Price: price, AutoRenew: true}
}

func (s *Subscription) CancelAutoRenew() { s.AutoRenew = false }

func (s *Subscription) PrintDetails() {
    fmt.Printf("подписка %s: %.2f руб., автопродление: %t\n", s.Plan, s.Price, s.AutoRenew)
}

// Задание 4: история просмотра.
type Episode struct {
    Title    string `json:"title"`
    Season   int    `json:"season"`
    Duration int    `json:"duration"`
}

type WatchHistory struct {
    Profile         Profile
    Episode         Episode
    WatchedPercent  int
    LastPositionMin int
}

// Задание 5: избранное.
type FavoriteList struct {
    Titles []string
}

func (f *FavoriteList) Add(title string) { f.Titles = append(f.Titles, title) }

func (f *FavoriteList) PrintAll() { fmt.Println("все:", f.Titles) }

func (f *FavoriteList) PrintUnique() {
    seen := make(map[string]struct{})
    var unique []string
    for _, t := range f.Titles {
        if _, ok := seen[t]; !ok {
            seen[t] = struct{}{}
            unique = append(unique, t)
        }
    }
    fmt.Println("уникальные:", unique)
}

func main() {
    // 1
    profile := Profile{UserName: "alex", Email: "alex@goflix.ru", Age: 28, Country: "RU", Premium: true}
    var empty Profile
    partial := Profile{UserName: "maria", Email: "maria@goflix.ru"}
    fmt.Printf("%+v\n%+v\n%+v\n", profile, empty, partial)

    // 2
    tv := Device{Name: "Гостиная", Type: "Smart TV"}
    fmt.Println(tv.Info())
    tv.Activate()
    fmt.Println(tv.Info())
    tv.Deactivate()
    fmt.Println(tv.Info())

    // 3
    sub := NewSubscription("Premium", 999)
    sub.PrintDetails()
    sub.CancelAutoRenew()
    sub.PrintDetails()

    // 4
    history := WatchHistory{
        Profile:         profile,
        Episode:         Episode{Title: "Пилот", Season: 1, Duration: 52},
        WatchedPercent:  75,
        LastPositionMin: 39,
    }
    fmt.Println(history.Profile.UserName, history.Profile.Email, history.Episode.Title,
        history.WatchedPercent, history.LastPositionMin)
    data, err := json.Marshal(history.Episode)
    if err != nil {
        fmt.Println("ошибка:", err)
        return
    }
    fmt.Println(string(data))

    // 5
    var fav FavoriteList
    for _, t := range []string{"Дюна", "Матрица", "Дюна"} {
        fav.Add(t)
    }
    fav.PrintAll()
    fav.PrintUnique()
    stats := struct {
        Owner      string
        ItemsCount int
    }{Owner: profile.UserName, ItemsCount: len(fav.Titles)}
    fmt.Printf("%+v\n", stats)
}
stdout // вывод программы
{UserName:alex Email:alex@goflix.ru Age:28 Country:RU Premium:true}
{UserName: Email: Age:0 Country: Premium:false}
{UserName:maria Email:maria@goflix.ru Age:0 Country: Premium:false}
Гостиная (Smart TV): неактивно
Гостиная (Smart TV): активно
Гостиная (Smart TV): неактивно
подписка Premium: 999.00 руб., автопродление: true
подписка Premium: 999.00 руб., автопродление: false
alex alex@goflix.ru Пилот 75 39
{"title":"Пилот","season":1,"duration":52}
все: [Дюна Матрица Дюна]
уникальные: [Дюна Матрица]
{Owner:alex ItemsCount:3}

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

go
package main

import "fmt"

type Counter struct{ n int }

func (c Counter) IncValue() { c.n++ }

func (c *Counter) IncPointer() { c.n++ }

func main() {
    var c Counter
    c.IncValue()
    c.IncPointer()
    c.IncPointer()
    fmt.Println(c.n)
}
самопроверкаОтвет
text
2

IncValue увеличил копию, оригинал не изменился. Два вызова IncPointer изменили сам c.

Проверь себя

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

Структуры с методами вместо классов; инкапсуляция через регистр первой буквы; наследования нет — вместо него композиция (встраивание); полиморфизм — через интерфейсы с неявной реализацией.

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

var s T, именованный литерал T{Field: v}, позиционный T{v1, v2}, частичный литерал, new(T). Самый безопасный — именованный: он не ломается при добавлении полей.

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

По значению метод получает копию и не может изменить оригинал. По указателю — меняет исходную структуру и не копирует её.

вопросЧто даёт встраивание структуры?

Поля и методы встроенной структуры доступны напрямую у внешней. Это композиция, а не наследование: тип внешней структуры не становится типом встроенной.

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

0 байт. Во множествах map[T]struct{} и в сигнальных каналах chan struct{}.

вопросЗачем нужны теги и какие поля видит encoding/json?

Теги — подсказки библиотекам: как назвать поле в JSON или в базе, пропускать ли пустое. encoding/json видит только экспортированные поля.

вопросМожно ли сравнить две структуры через ==?

Да, если все их поля сравнимы: сравнение идёт по каждому полю. Со слайсом, мапой или функцией внутри — ошибка компиляции.

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

Обычная функция NewТип(...), которая возвращает готовый экземпляр — как правило указатель — с проверенными данными и значениями по умолчанию.


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

  • 🧱 Структура связывает данные: один тип вместо разрозненных переменных.
  • 🧭 ООП в Go: методы и инкапсуляция есть, наследования нет — композиция и интерфейсы.
  • 🏷️ Именованная инициализация — самый безопасный способ создать структуру.
  • ✏️ Получатель по указателю меняет оригинал, по значению — работает с копией.
  • 🪆 Встраивание поднимает поля и методы наверх, но не делает типы взаимозаменяемыми.
  • 🏭 Конструктор NewX ставит значения по умолчанию и проверяет данные.

Chapter goals

  • Explain how OOP works in Go — a frequent interview question.
  • Declare structs, create them in five ways, read and modify fields.
  • Write methods and choose the receiver: by value or by pointer.
  • Use embedding, anonymous and empty structs, and tags.
  • Write constructor functions.

Why structs

So far we have worked with variables, functions, slices, and maps. But in GoFlix a movie is not a string — it is a set of properties: title, year, rating. A subscriber is not just a name, but also an email and a plan; a viewing session stores the start time, the movie, and a status. Updating a rating when the data lives in unrelated variables is awkward. You need a type that ties the data together — a struct.

OOP in Go

In many languages OOP is built around classes, inheritance, and polymorphism. Go takes a different path:

OOP idea How Go does it
Class struct + methods
Encapsulation capital first letter — exported (like public), lowercase — private to the package (like private)
Inheritance none; composition instead: embedding one struct into another
Polymorphism through interfaces — 16 — Interfaces
Dependencies passed explicitly: through parameters and fields (Dependency Injection)

To reuse code, structs are embedded into each other rather than arranged into inheritance hierarchies.

Declaration and creation

A struct is a set of named fields, each with its own type. It is declared with type Name struct { … }. Fields of the same type can be written on one line: Lat, Lng float64.

Ways to create a struct:

  1. var — all fields get their zero values.
  2. Named initialization — you explicitly say which field equals what. The safest and most readable way; official guides recommend it.
  3. Positional — values in field order. Add a field and the code breaks; only suitable for very simple structs.
  4. Partial — some fields explicitly, the rest get zero values.
  5. new(T) — a pointer to a struct with zeroed fields.
go
package main

import "fmt"

// Film — a movie description in GoFlix.
type Film struct {
    Title    string
    Year     int
    Rating   float64
    Genre    string
    Duration int // minutes
}

func main() {
    var f1 Film                                          // all fields — zero values
    f2 := Film{Title: "Dune", Year: 2021, Rating: 8.1}   // named and partial
    f3 := Film{"Interstellar", 2014, 8.6, "Sci-fi", 169} // positional: all fields in order
    f4 := new(Film)                                      // pointer to a struct

    fmt.Printf("%+v\n%+v\n%+v\n%+v\n", f1, f2, f3, f4)
}
stdout // program output
{Title: Year:0 Rating:0 Genre: Duration:0}
{Title:Dune Year:2021 Rating:8.1 Genre: Duration:0}
{Title:Interstellar Year:2014 Rating:8.6 Genre:Sci-fi Duration:169}
&{Title: Year:0 Rating:0 Genre: Duration:0}

%+v prints a struct with field names — indispensable when debugging.

Fields and pointers

You access a field with a dot: film.Title, sub.Email — like picking the right thing out of a box. A lowercase field is not visible from other packages, so public fields are written with a capital letter.

Structs can be large, and copying them is expensive. Besides, a function can only modify fields through a pointer. That is why structs are often passed by pointer — and fields are still accessed with a dot: Go dereferences the pointer itself (11 — Pointers → Pointers to structs).

go
package main

import "fmt"

type Subscriber struct {
    Name  string
    Email string
    Age   int
    Plan  string
}

func main() {
    sub := Subscriber{Name: "Alex", Email: "alex@goflix.ru", Age: 28, Plan: "Premium"}
    fmt.Println(sub.Name, sub.Plan) // reading through the dot
    sub.Plan = "Standard"           // writing

    p := &sub
    p.Age = 29 // through the pointer we change the original

    copied := sub
    copied.Name = "Copy" // a copy is a separate box
    fmt.Println(sub.Plan, sub.Age, sub.Name, copied.Name)
}
stdout // program output
Alex Premium
Standard 29 Alex Copy

An analogy: a struct is a box with things in it. A copy is a separate box with the same contents: change it, and the original stays untouched. A pointer is a tag with the storage location of the original box in a warehouse: follow it to find that exact box and change the things right inside it.

Methods

A method is a function attached to a type. The type goes between func and the method name — it is the receiver. Methods bind behavior to data.

go
package main

import "fmt"

type FilmCard struct {
    Title     string
    Year      int
    Rating    float64
    Watched   bool
    ViewCount int
}

// Info — value receiver: works on a copy and only reads fields.
func (f FilmCard) Info() string {
    return fmt.Sprintf("%s (%d), rating %.1f", f.Title, f.Year, f.Rating)
}

// Watch — pointer receiver: modifies the original struct.
func (f *FilmCard) Watch() {
    f.Watched = true
    f.ViewCount++
}

// RenameCopy tries to rename the movie through a value receiver — it won't work.
func (f FilmCard) RenameCopy(title string) {
    f.Title = title
}

func main() {
    card := FilmCard{Title: "Tenet", Year: 2020, Rating: 7.8}
    card.Watch() // Go takes the address itself: (&card).Watch()
    card.Watch()
    card.RenameCopy("Tenet 2")
    fmt.Println(card.Info(), card.Watched, card.ViewCount)
}
stdout // program output
Tenet (2020), rating 7.8 true 2

How to choose the receiver:

Pointer receiver (f *T) Value receiver (f T)
the method mutates state the method only reads fields
the struct is big — copying is expensive the struct is small
the struct has a field that must not be copied, e.g. sync.Mutex the type is semantically a value: coordinates, money

Embedding: composition instead of inheritance

Go has no inheritance, but one struct can be embedded into another: you write the type without a field name. The embedded struct's fields and methods become directly available on the outer one — they are "promoted" upward. The analogy is a matryoshka doll: inside AdminUser there is a Subscriber.

go
package main

import "fmt"

type Subscriber struct {
    Name  string
    Email string
    Plan  string
}

func (s Subscriber) Contact() string {
    return s.Name + " <" + s.Email + ">"
}

// AdminUser embeds Subscriber: its fields and methods are available directly.
type AdminUser struct {
    Subscriber
    AccessLevel string
    Department  string
}

func main() {
    admin := AdminUser{
        Subscriber:  Subscriber{Name: "Elena", Email: "e@goflix.ru", Plan: "Premium"},
        AccessLevel: "superadmin",
        Department:  "Billing",
    }
    fmt.Println(admin.Name)            // the Subscriber field is available directly
    fmt.Println(admin.Subscriber.Plan) // the full path works too
    fmt.Println(admin.Contact())       // and so do the methods
}
stdout // program output
Elena
Premium
Elena <e@goflix.ru>

The new struct is assembled from ready-made parts and extended with its own fields.

Anonymous structs

Sometimes data needs to be grouped temporarily, and there is no reason to declare a separate type — it is used nowhere else. Then the struct is declared right on the spot. Two common scenarios: one-off configuration and table-driven tests, where each slice element is an input and an expected result.

go
package main

import "fmt"

func discount(plan string) int {
    switch plan {
    case "Premium":
        return 20
    case "Standard":
        return 10
    default:
        return 0
    }
}

func main() {
    config := struct {
        Host string
        Port int
    }{Host: "api.goflix.ru", Port: 443}
    fmt.Printf("%s:%d\n", config.Host, config.Port)

    tests := []struct {
        plan string
        want int
    }{
        {"Premium", 20},
        {"Standard", 10},
        {"Free", 0},
    }
    for _, tt := range tests {
        got := discount(tt.plan)
        fmt.Printf("%-8s → %2d%% ok=%t\n", tt.plan, got, got == tt.want)
    }
}
stdout // program output
api.goflix.ru:443
Premium  → 20% ok=true
Standard → 10% ok=true
Free     →  0% ok=true

Table-driven tests are compact and easy to extend: a new case is a new line. In real tests such a loop lives inside a TestXxx function and runs via go test — see the example in 18 — Backend — HTTP server → Testing handlers.

Empty struct

struct{} has no fields at all, so it stores no data and takes up 0 bytes. It is used where the mere fact of presence matters, not the data. The most common example is a set: map[string]struct{} instead of map[string]bool saves memory. Another one is signal channels (17 — Concurrency — goroutines and channels → Signal channel).

go
package main

import (
    "fmt"
    "maps"
    "slices"
    "unsafe"
)

func main() {
    fmt.Println(unsafe.Sizeof(struct{}{})) // size in bytes

    genres := map[string]struct{}{"Sci-fi": {}, "Drama": {}, "Comedy": {}}
    genres["Action"] = struct{}{} // add
    if _, exists := genres["Drama"]; exists {
        fmt.Println("Drama is in the set")
    }
    delete(genres, "Comedy") // remove
    fmt.Println(slices.Sorted(maps.Keys(genres)))
}
stdout // program output
0
Drama is in the set
[Action Drama Sci-fi]

Tags

A tag is a backquoted string after a field's type. Tags do not affect the struct itself; they are hints for libraries. The best-known example is JSON serialization: the tag json:"id" tells the encoding/json package what to call the field. The tag db:"item_id" is a hint for database libraries. In code you still refer to fields by their regular names: item.ID, item.Title.

go
package main

import (
    "encoding/json"
    "fmt"
)

type CatalogItem struct {
    ID        int     `json:"id" db:"item_id"`
    Title     string  `json:"title" db:"title"`
    Price     float64 `json:"price" db:"price"`
    Available bool    `json:"available" db:"is_available"`
    Internal  string  `json:"-"`              // never gets into the JSON
    Note      string  `json:"note,omitempty"` // a zero value is skipped
}

func main() {
    item := CatalogItem{ID: 1, Title: "Interstellar", Price: 12.99, Available: true, Internal: "internal"}
    data, err := json.Marshal(item)
    if err != nil {
        fmt.Println("error:", err)
        return
    }
    fmt.Println(string(data))
    fmt.Println(item.Title) // in code — the regular field names
}
stdout // program output
{"id":1,"title":"Interstellar","price":12.99,"available":true}
Interstellar

Comparison and copying

  • Structs can be compared with == if all of their fields are comparable; the comparison walks every field. A struct with a slice inside cannot be compared: invalid operation: a == b (struct containing []string cannot be compared).
  • Assigning a struct creates a copy: changes to the copy do not affect the original — you saw this with copied above.

Structs in Go behave as values by default: both comparison and assignment work with the contents, not with a reference.

Constructors

Go has no built-in constructors like Java or C#. There is an idiom instead: a NewType(...) function returns a ready instance. It sets default values, validates inputs, and initializes complex fields — a start time, a mutex. A constructor usually returns a pointer: the object is then used without extra copying.

go
package main

import (
    "errors"
    "fmt"
    "time"
)

type StreamSession struct {
    UserName  string
    MovieName string
    StartedAt time.Time
    IsActive  bool
}

// NewStreamSession validates the data and sets default values.
func NewStreamSession(user, movie string) (*StreamSession, error) {
    if user == "" || movie == "" {
        return nil, errors.New("user and movie are required")
    }
    return &StreamSession{
        UserName:  user,
        MovieName: movie,
        StartedAt: time.Now(),
        IsActive:  true,
    }, nil
}

func main() {
    s, err := NewStreamSession("Alex", "Interstellar")
    if err != nil {
        fmt.Println("error:", err)
        return
    }
    fmt.Println(s.UserName, s.MovieName, s.IsActive, !s.StartedAt.IsZero())

    _, err = NewStreamSession("", "Dune")
    fmt.Println("error:", err)
}
stdout // program output
Alex Interstellar true true
error: user and movie are required

Practice

Homework

  1. Profile. A Profile struct: UserName, Email (string), Age (int), Country (string), Premium (bool). Create a filled-in profile and print its fields; then a profile without initialization; then one where only UserName and Email are set.
  2. Device. A Device struct: Name, Type (string), Active (bool). Methods Info() string, Activate(), Deactivate(). Create a device, print its state, activate it, print, deactivate, print again.
  3. Subscription. A Subscription struct: Plan (string), Price (float64), AutoRenew (bool). The constructor NewSubscription(plan string, price float64) *Subscription sets AutoRenew = true. Methods CancelAutoRenew() and PrintDetails(). Create a subscription, print it, turn off auto-renewal, print again.
  4. Watch history. Episode with fields Title, Season, Duration and JSON tags title, season, duration. WatchHistory with fields Profile, Episode, WatchedPercent, LastPositionMin. Print the name, email, episode title, percent, and position; marshal Episode to JSON.
  5. Favorites. FavoriteList with a Titles []string slice. Methods Add(title string), PrintAll(), and PrintUnique() — unique titles via map[string]struct{}. In main, create an anonymous stats struct with fields Owner string and ItemsCount int.
solution
go
package main

import (
    "encoding/json"
    "fmt"
)

// Task 1: user profile.
type Profile struct {
    UserName string
    Email    string
    Age      int
    Country  string
    Premium  bool
}

// Task 2: a viewing device.
type Device struct {
    Name   string
    Type   string
    Active bool
}

func (d *Device) Info() string {
    status := "inactive"
    if d.Active {
        status = "active"
    }
    return fmt.Sprintf("%s (%s): %s", d.Name, d.Type, status)
}

func (d *Device) Activate() { d.Active = true }

func (d *Device) Deactivate() { d.Active = false }

// Task 3: a subscription with a constructor.
type Subscription struct {
    Plan      string
    Price     float64
    AutoRenew bool
}

func NewSubscription(plan string, price float64) *Subscription {
    return &Subscription{Plan: plan, Price: price, AutoRenew: true}
}

func (s *Subscription) CancelAutoRenew() { s.AutoRenew = false }

func (s *Subscription) PrintDetails() {
    fmt.Printf("subscription %s: $%.2f, auto-renew: %t\n", s.Plan, s.Price, s.AutoRenew)
}

// Task 4: watch history.
type Episode struct {
    Title    string `json:"title"`
    Season   int    `json:"season"`
    Duration int    `json:"duration"`
}

type WatchHistory struct {
    Profile         Profile
    Episode         Episode
    WatchedPercent  int
    LastPositionMin int
}

// Task 5: favorites.
type FavoriteList struct {
    Titles []string
}

func (f *FavoriteList) Add(title string) { f.Titles = append(f.Titles, title) }

func (f *FavoriteList) PrintAll() { fmt.Println("all:", f.Titles) }

func (f *FavoriteList) PrintUnique() {
    seen := make(map[string]struct{})
    var unique []string
    for _, t := range f.Titles {
        if _, ok := seen[t]; !ok {
            seen[t] = struct{}{}
            unique = append(unique, t)
        }
    }
    fmt.Println("unique:", unique)
}

func main() {
    // 1
    profile := Profile{UserName: "alex", Email: "alex@goflix.ru", Age: 28, Country: "RU", Premium: true}
    var empty Profile
    partial := Profile{UserName: "maria", Email: "maria@goflix.ru"}
    fmt.Printf("%+v\n%+v\n%+v\n", profile, empty, partial)

    // 2
    tv := Device{Name: "Living room", Type: "Smart TV"}
    fmt.Println(tv.Info())
    tv.Activate()
    fmt.Println(tv.Info())
    tv.Deactivate()
    fmt.Println(tv.Info())

    // 3
    sub := NewSubscription("Premium", 9.99)
    sub.PrintDetails()
    sub.CancelAutoRenew()
    sub.PrintDetails()

    // 4
    history := WatchHistory{
        Profile:         profile,
        Episode:         Episode{Title: "Pilot", Season: 1, Duration: 52},
        WatchedPercent:  75,
        LastPositionMin: 39,
    }
    fmt.Println(history.Profile.UserName, history.Profile.Email, history.Episode.Title,
        history.WatchedPercent, history.LastPositionMin)
    data, err := json.Marshal(history.Episode)
    if err != nil {
        fmt.Println("error:", err)
        return
    }
    fmt.Println(string(data))

    // 5
    var fav FavoriteList
    for _, t := range []string{"Dune", "The Matrix", "Dune"} {
        fav.Add(t)
    }
    fav.PrintAll()
    fav.PrintUnique()
    stats := struct {
        Owner      string
        ItemsCount int
    }{Owner: profile.UserName, ItemsCount: len(fav.Titles)}
    fmt.Printf("%+v\n", stats)
}
stdout // program output
{UserName:alex Email:alex@goflix.ru Age:28 Country:RU Premium:true}
{UserName: Email: Age:0 Country: Premium:false}
{UserName:maria Email:maria@goflix.ru Age:0 Country: Premium:false}
Living room (Smart TV): inactive
Living room (Smart TV): active
Living room (Smart TV): inactive
subscription Premium: $9.99, auto-renew: true
subscription Premium: $9.99, auto-renew: false
alex alex@goflix.ru Pilot 75 39
{"title":"Pilot","season":1,"duration":52}
all: [Dune The Matrix Dune]
unique: [Dune The Matrix]
{Owner:alex ItemsCount:3}

Exercise: predict the output

go
package main

import "fmt"

type Counter struct{ n int }

func (c Counter) IncValue() { c.n++ }

func (c *Counter) IncPointer() { c.n++ }

func main() {
    var c Counter
    c.IncValue()
    c.IncPointer()
    c.IncPointer()
    fmt.Println(c.n)
}
self-check
text
2

IncValue incremented a copy; the original stayed the same. The two IncPointer calls changed c itself.

Check yourself

questionHow is OOP implemented in Go?

Structs with methods instead of classes; encapsulation through the case of the first letter; no inheritance — composition (embedding) instead; polymorphism through interfaces with implicit implementation.

questionWhat ways of creating a struct do you know, and which is the safest?

var s T, the named literal T{Field: v}, positional T{v1, v2}, a partial literal, new(T). The safest is the named one: it does not break when fields are added.

questionHow does a value receiver differ from a pointer receiver?

By value, the method gets a copy and cannot change the original. By pointer, it modifies the original struct and does not copy it.

questionWhat does embedding a struct give you?

The embedded struct's fields and methods are available directly on the outer one. It is composition, not inheritance: the outer type does not become the embedded type.

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

0 bytes. In sets map[T]struct{} and in signal channels chan struct{}.

questionWhat are tags for, and which fields does encoding/json see?

Tags are hints for libraries: what to call a field in JSON or the database, whether to skip empty values. encoding/json sees only exported fields.

questionCan two structs be compared with ==?

Yes, if all their fields are comparable: the comparison walks each field. With a slice, map, or function inside — a compile error.

questionWhat is a constructor in Go?

An ordinary NewType(...) function that returns a ready instance — usually a pointer — with validated data and default values.


Key takeaways

  • 🧱 A struct ties data together: one type instead of scattered variables.
  • 🧭 OOP in Go: methods and encapsulation exist, inheritance does not — composition and interfaces instead.
  • 🏷️ Named initialization is the safest way to create a struct.
  • ✏️ A pointer receiver modifies the original; a value receiver works on a copy.
  • 🪆 Embedding lifts fields and methods upward but does not make the types interchangeable.
  • 🏭 The NewX constructor sets default values and validates the data.
// related topics and cheatsheets