implicit implementation, polymorphism, any, type assertion, nil interface, generics
Цели главы
Объявлять интерфейсы и понимать неявную реализацию.
Использовать полиморфизм: интерфейсные переменные, слайсы и параметры.
Работать с any: type assertion и type switch.
Собирать интерфейсы из маленьких и реализовывать fmt.Stringer и error.
Объяснить ловушку nil-интерфейса.
Интерфейс — контракт поведения
В GoFlix есть фильмы, сериалы и подкасты. У всех есть название и длительность, но считаются они по-разному. В классическом ООП завели бы базовый класс Content и наследовали бы от него. В Go вместо этого описывают интерфейс — набор методов, которые должен уметь тип. Интерфейс не содержит данных и ничего не знает о реализации: это договор «тип умеет делать вот это».
Неявная реализация — главная особенность Go. В Java и C# пишут implements, а в Go тип автоматически удовлетворяет интерфейсу, если у него есть все перечисленные методы. Это работает даже для интерфейса из чужого пакета, о котором тип ничего не знает, и уменьшает связность кода.
В примере ниже:
Content — название, длительность и описание;
Playable — воспроизведение и пауза;
Movie и Series реализуют оба интерфейса, а Podcast — только Content;
MediaPlayer собран из двух интерфейсов — это композиция интерфейсов.
go
package mainimport "fmt"// Content — всё, у чего есть название, длительность и описание.type Content interface { Title() string Duration() int Description() string}// Playable — то, что умеет воспроизводиться.type Playable interface { Play() string Pause() string}// MediaPlayer = Content + Playable.type MediaPlayer interface { Content Playable}type Movie struct { Name string Year int Minutes int Genre string}func (m Movie) Title() string { return m.Name }func (m Movie) Duration() int { return m.Minutes }func (m Movie) Description() string { return fmt.Sprintf("%s (%d), %s", m.Name, m.Year, m.Genre) }func (m Movie) Play() string { return "▶ " + m.Name }func (m Movie) Pause() string { return "⏸ " + m.Name }type Series struct { Name string Seasons int Episodes int AvgLen int}func (s Series) Title() string { return s.Name }func (s Series) Duration() int { return s.Episodes * s.AvgLen }func (s Series) Description() string { return fmt.Sprintf("%s, сезонов: %d", s.Name, s.Seasons) }func (s Series) Play() string { return "▶ " + s.Name + " S01E01" }func (s Series) Pause() string { return "⏸ " + s.Name }// Podcast реализует только Content: методов Play и Pause у него нет.type Podcast struct { Name string Host string Minutes int}func (p Podcast) Title() string { return p.Name }func (p Podcast) Duration() int { return p.Minutes }func (p Podcast) Description() string { return fmt.Sprintf("подкаст %q, ведущий %s", p.Name, p.Host)}func printContentInfo(c Content) { fmt.Printf("%s — %d мин\n", c.Description(), c.Duration())}func main() { var item Content = Movie{Name: "Интерстеллар", Year: 2014, Minutes: 169, Genre: "фантастика"} printContentInfo(item) item = Series{Name: "Во все тяжкие", Seasons: 5, Episodes: 62, AvgLen: 47} printContentInfo(item) catalog := []Content{ Movie{Name: "Дюна", Year: 2021, Minutes: 155, Genre: "фантастика"}, Series{Name: "Чернобыль", Seasons: 1, Episodes: 5, AvgLen: 65}, Podcast{Name: "GoFlix Talks", Host: "Анна", Minutes: 45}, } total := 0 for _, c := range catalog { fmt.Printf("%s: %d мин\n", c.Title(), c.Duration()) total += c.Duration() } fmt.Println("итого:", total, "мин") var player MediaPlayer = Movie{Name: "Начало", Year: 2010, Minutes: 148, Genre: "фантастика"} fmt.Println(player.Description()) // метод из Content fmt.Println(player.Play()) // метод из Playable}
Один и тот же код работает с разными типами, если они удовлетворяют интерфейсу. Функция printContentInfo принимает не конкретный тип, а Content — ей всё равно, фильм пришёл или сериал. В слайсе []Content рядом лежат три разных структуры, и в цикле Go сам вызывает нужную реализацию метода в зависимости от того, какой тип лежит внутри.
То же с геометрией: интерфейс Shape требует два метода, а прямоугольник и круг считают их по своим формулам.
main.Rectangle: площадь 144.00, периметр 50.00main.Circle: площадь 78.54, периметр 31.42
Тип, которому не хватает метода, интерфейсу не подходит — и это ловит компилятор. Подкаст нельзя положить в MediaPlayer:
go
var p MediaPlayer = Podcast{} // Podcast does not implement MediaPlayer (missing method Pause)
any — пустой интерфейс
У пустого интерфейса interface{} нет методов, поэтому ему удовлетворяет любой тип — аналог Object в Java или Any в Kotlin. С Go 1.18 у него есть короткое имя any — это просто псевдоним.
За гибкость приходится платить: компилятор уже не знает, что лежит внутри, поэтому реальный тип приходится проверять отдельно. any полезен в универсальных местах — разбор JSON, логирование, произвольные данные, — но в обычном коде его используют аккуратно, чтобы не терять типобезопасность.
Type assertion
Конкретное значение достают через type assertionx.(T). Короткая форма предполагает, что тип угадан, и паникует, если нет. Безопасная форма v, ok := x.(T) возвращает флаг: при несовпадении — нулевое значение и false, без паники. Используй безопасную.
go
package mainimport "fmt"func main() { var anything any = "строка" // any — то же, что interface{} fmt.Printf("%v (%T)\n", anything, anything) anything = 42 fmt.Printf("%v (%T)\n", anything, anything) var i any = "Привет" s := i.(string) // небезопасно: паника, если внутри не string fmt.Println(s) s2, ok := i.(string) // безопасно: ok сообщает, удалось ли fmt.Println(s2, ok) n, ok := i.(int) fmt.Println(n, ok) // нулевое значение и false — без паники}
stdout // вывод программы
строка (string)42 (int)ПриветПривет true0 false
Короткая форма с неверным типом:
go
package mainimport "fmt"func main() { var i any = "Привет" n := i.(int) // ожидается panic fmt.Println(n)}
text
panic: interface conversion: interface {} is string, not int
Type switch
Если вариантов типа несколько, вместо цепочки assertion пишут type switch — он перебирает типы и выбирает первый совпавший case. Внутри ветки переменная уже имеет тип этой ветки — например, у Movie можно читать поля. default ловит всё остальное.
go
package mainimport "fmt"type Movie struct { Name string Year int}func classify(v any) string { switch val := v.(type) { case Movie: return fmt.Sprintf("фильм %s (%d)", val.Name, val.Year) case string: return "строка " + val case int: return fmt.Sprintf("число %d", val) case nil: return "nil" default: return fmt.Sprintf("другое: %T", val) }}func main() { for _, v := range []any{Movie{Name: "Матрица", Year: 1999}, "поиск", 42, nil, 8.7} { fmt.Println(classify(v)) }}
stdout // вывод программы
фильм Матрица (1999)строка поискчисло 42nilдругое: float64
Композиция интерфейсов
Интерфейсы, как и структуры, встраиваются друг в друга. MediaPlayer из первого примера не объявляет методы заново, а объединяет Content и Playable: тип подходит под него, только если умеет всё, что требуют оба. Фильм подходит, подкаст — нет.
Так большой контракт собирают из маленьких и понятных. Это ISP (Interface Segregation Principle, принцип разделения интерфейсов): лучше много маленьких интерфейсов, чем один огромный. В стандартной библиотеке это повсюду: io.Reader — один метод Read, io.Writer — один метод Write, а io.ReadWriter — их композиция.
fmt.Stringer
Пакет fmt проверяет, реализует ли значение интерфейс fmt.Stringer — метод String() string. Если да, Println и %v печатают результат этого метода вместо стандартного вывода всех полей. Удобно для логирования, отладки и человекочитаемого вида объектов. В стандартной библиотеке таких интерфейсов много — например, json.Marshaler для своей сериализации.
Алексей (Premium, 45 просмотров)пользователь: Алексей (Premium, 45 просмотров)
Интерфейс error
Ошибки в Go — значения, а error — встроенный интерфейс с одним методом Error() string. Любой тип с этим методом можно вернуть как ошибку и добавить ему поля: статус, код, контекст. Снаружи код работает с общим интерфейсом и не зависит от конкретного типа, а когда нужны поля — достаёт конкретный тип.
go
package mainimport ( "errors" "fmt")type SubscriptionError struct { Status string Code int}func (e *SubscriptionError) Error() string { return fmt.Sprintf("подписка: %s (код %d)", e.Status, e.Code)}func checkSubscription(status string) error { switch status { case "expired": return &SubscriptionError{Status: status, Code: 402} case "banned": return &SubscriptionError{Status: status, Code: 403} } return nil}func main() { err := checkSubscription("expired") if err != nil { fmt.Println("ошибка:", err) if subErr, ok := err.(*SubscriptionError); ok { // type assertion fmt.Println("статус:", subErr.Status, "код:", subErr.Code) } } wrapped := fmt.Errorf("запуск фильма: %w", checkSubscription("banned")) var subErr *SubscriptionError found := errors.As(wrapped, &subErr) _, asserted := wrapped.(*SubscriptionError) fmt.Println(asserted, found, subErr.Code)}
Интерфейсная переменная хранит два элемента: динамический тип и динамическое значение. Она равна nil, только если nilоба. Если положить в интерфейс nil-указатель конкретного типа, тип запишется, а значение останется nil — и сравнение с nil вернёт false, хотя внутри «пусто». Это один из самых коварных моментов Go и любимый вопрос на собеседованиях.
go
package mainimport "fmt"type Content interface{ Title() string }type Movie struct{ Name string }func (m *Movie) Title() string { if m == nil { return "<нет фильма>" } return m.Name}func main() { var c Content fmt.Println(c == nil) // нет ни типа, ни значения var m *Movie // nil-указатель c = m fmt.Println(c == nil) // внутри тип *Movie и значение nil fmt.Println(c.Title()) // метод вызвался: интерфейс не пустой}
stdout // вывод программы
truefalse<нет фильма>
Дженерики
Функция с параметром типа[T ограничение] работает с любым типом, который подходит под ограничение. Частые ограничения: any — любой тип, comparable — типы с ==, cmp.Ordered — числа и строки с < и >.
go
package mainimport ( "cmp" "fmt")// Map применяет функцию к каждому элементу слайса любого типа.func Map[T, U any](items []T, fn func(T) U) []U { result := make([]U, 0, len(items)) for _, item := range items { result = append(result, fn(item)) } return result}// MaxOf возвращает максимум; cmp.Ordered — типы, которые сравниваются через < и >.func MaxOf[T cmp.Ordered](items ...T) T { best := items[0] for _, v := range items[1:] { if v > best { best = v } } return best}// Contains работает с любым сравнимым типом.func Contains[T comparable](items []T, target T) bool { for _, v := range items { if v == target { return true } } return false}func main() { durations := Map([]int{148, 169, 155}, func(m int) string { return fmt.Sprintf("%d мин", m) }) fmt.Println(durations) fmt.Println(MaxOf(8.1, 8.8, 7.5), MaxOf("Дюна", "Матрица")) fmt.Println(Contains([]string{"Дюна", "Довод"}, "Довод"))}
stdout // вывод программы
[148 мин 169 мин 155 мин]8.8 Матрицаtrue
Интерфейс
Дженерик
Разные типы с общим поведением (методами)
Один и тот же алгоритм для разных типов данных
Конкретный тип выбирается во время выполнения
Тип подставляется при компиляции
[]Content с фильмами и сериалами
Map, Contains, MaxOf для слайсов любых типов
Многие такие функции уже есть в стандартной библиотеке: пакеты slices и maps, встроенные min и max (Go 1.21+).
Практика
Домашнее задание
Каналы уведомлений. Интерфейс Notifier с методами Send() string и ChannelName() string. Структуры EmailNotification и PushNotification его реализуют. Положи по объекту каждого типа в []Notifier и в цикле выведи канал доставки и результат отправки.
Экспорт в разные форматы. Интерфейс Exporter с методом Export(). Структуры CSVExport и JSONExport. Функция RunExport(e Exporter) вызывает Export(); передай в неё оба типа.
Композиция интерфейсов. Интерфейсы Authorizer с Authorize() string и Capturer с Capture() string. Составной PaymentProvider объединяет оба. Структура StripeProvider реализует оба интерфейса и метод String() string. Сохрани её в переменную PaymentProvider, вызови оба метода и выведи объект через fmt.Println.
any в результатах поиска. Функция InspectSearchResult(value any): безопасным assertion проверь, строка ли это, потом — int; затем type switch по string, int, bool, SeriesResult (структура с полем Title) и default. Вызови для строки, числа, bool, SeriesResult и []string.
Ошибка модерации. Структура ModerationError с полями ContentID и Reason и методом Error() string. Функция CheckPoster(status string) error: для approved — nil, иначе ModerationError. Вызови для approved и rejected, через assertion достань ContentID и Reason. Отдельно покажи nil-указатель внутри интерфейса error.
решениеЭталонное решение
go
package mainimport ( "fmt" "strings")// 1. Каналы уведомлений.type Notifier interface { Send() string ChannelName() string}type EmailNotification struct{ To, Subject string }func (e EmailNotification) Send() string { return "письмо для " + e.To + ": " + e.Subject }func (e EmailNotification) ChannelName() string { return "email" }type PushNotification struct{ DeviceID, Text string }func (p PushNotification) Send() string { return "push на " + p.DeviceID + ": " + p.Text }func (p PushNotification) ChannelName() string { return "push" }// 2. Экспорт.type Exporter interface { Export() string}type CSVExport struct{ Rows [][]string }func (c CSVExport) Export() string { lines := make([]string, 0, len(c.Rows)) for _, row := range c.Rows { lines = append(lines, strings.Join(row, ",")) } return strings.Join(lines, "\n")}type JSONExport struct{ Title string }func (j JSONExport) Export() string { return fmt.Sprintf(`{"title":%q}`, j.Title) }func RunExport(e Exporter) { fmt.Printf("%T:\n%s\n", e, e.Export())}// 3. Платёжный провайдер.type Authorizer interface{ Authorize() string }type Capturer interface{ Capture() string }type PaymentProvider interface { Authorizer Capturer}type StripeProvider struct{ Account string }func (s StripeProvider) Authorize() string { return "авторизация в " + s.Account }func (s StripeProvider) Capture() string { return "списание в " + s.Account }func (s StripeProvider) String() string { return "Stripe(" + s.Account + ")" }// 4. Результаты поиска.type SeriesResult struct{ Title string }func InspectSearchResult(value any) { if s, ok := value.(string); ok { fmt.Println("assertion: строка", s) } if n, ok := value.(int); ok { fmt.Println("assertion: число", n) } switch v := value.(type) { case string: fmt.Println("switch: string", v) case int: fmt.Println("switch: int", v) case bool: fmt.Println("switch: bool", v) case SeriesResult: fmt.Println("switch: сериал", v.Title) default: fmt.Printf("switch: другой тип %T\n", v) }}// 5. Ошибка модерации.type ModerationError struct { ContentID string Reason string}func (e *ModerationError) Error() string { return fmt.Sprintf("постер %s отклонён: %s", e.ContentID, e.Reason)}func CheckPoster(status string) error { if status == "approved" { return nil } return &ModerationError{ContentID: "poster-42", Reason: "status=" + status}}func CheckPosterBuggy(status string) error { var err *ModerationError if status != "approved" { err = &ModerationError{ContentID: "poster-42", Reason: "status=" + status} } return err // ловушка: nil-указатель внутри интерфейса error}func main() { for _, n := range []Notifier{ EmailNotification{To: "alex@goflix.ru", Subject: "Новый сезон"}, PushNotification{DeviceID: "iphone-7", Text: "Скидка 50%"}, } { fmt.Println(n.ChannelName(), "→", n.Send()) } RunExport(CSVExport{Rows: [][]string{{"title", "year"}, {"Дюна", "2021"}}}) RunExport(JSONExport{Title: "Дюна"}) var provider PaymentProvider = StripeProvider{Account: "goflix-main"} fmt.Println(provider.Authorize()) fmt.Println(provider.Capture()) fmt.Println(provider) for _, v := range []any{"дюна", 42, true, SeriesResult{Title: "Чернобыль"}, []string{"a"}} { InspectSearchResult(v) } fmt.Println(CheckPoster("approved") == nil) err := CheckPoster("rejected") fmt.Println(err) if modErr, ok := err.(*ModerationError); ok { fmt.Println("ContentID:", modErr.ContentID, "| Reason:", modErr.Reason) } fmt.Println("buggy approved == nil:", CheckPosterBuggy("approved") == nil)}
stdout // вывод программы
email → письмо для alex@goflix.ru: Новый сезонpush → push на iphone-7: Скидка 50%main.CSVExport:title,yearДюна,2021main.JSONExport:{"title":"Дюна"}авторизация в goflix-mainсписание в goflix-mainStripe(goflix-main)assertion: строка дюнаswitch: string дюнаassertion: число 42switch: int 42switch: bool trueswitch: сериал Чернобыльswitch: другой тип []stringtrueпостер poster-42 отклонён: status=rejectedContentID: poster-42 | Reason: status=rejectedbuggy approved == nil: false
Проверь себя
вопросЧто такое интерфейс и как тип его реализует?
Набор сигнатур методов — контракт поведения без данных. Тип реализует интерфейс неявно: достаточно иметь все его методы, implements не пишут.
вопросКак в Go достигается полиморфизм?
Через интерфейсы: переменная, параметр или слайс интерфейсного типа хранит значения разных типов, и вызов метода уходит в реализацию конкретного типа.
вопросЧем короткая форма type assertion отличается от формы с ok?
v := x.(T) паникует при несовпадении типа. v, ok := x.(T) возвращает нулевое значение и false.
вопросКогда интерфейсная переменная равна nil?
Только когда в ней нет ни динамического типа, ни значения. Интерфейс с nil-указателем конкретного типа внутри не равен nil.
вопросПочему функция, вернувшая var e *MyErr как error, даёт err != nil?
В интерфейс записался тип *MyErr со значением nil — такой интерфейс не пустой. Возвращать нужно буквальный nil.
вопросЧто такое ISP и как композиция интерфейсов помогает его соблюдать?
Принцип разделения интерфейсов: лучше много маленьких интерфейсов, чем один большой. Большой контракт собирают встраиванием маленьких: io.ReadWriter = io.Reader + io.Writer.
вопросПочему Dog{} не реализует интерфейс, если метод объявлен как func (d *Dog) Speak()?
Метод с получателем-указателем входит в набор методов только *Dog. Нужно класть указатель: &Dog{}.
вопросЧем дженерики отличаются от интерфейсов?
Интерфейс — общее поведение разных типов, тип выбирается во время выполнения. Дженерик — один алгоритм для разных типов данных, тип подставляется при компиляции; ограничения параметров типа — интерфейсы.
Ключевые выводы
📜 Интерфейс — контракт поведения; реализация неявная, без implements.
🎭 Полиморфизм: интерфейсные переменные, параметры и слайсы работают с любыми подходящими типами.
🧩 Маленькие интерфейсы собирают в большие композицией — принцип ISP.
🔍 any принимает всё; тип достают через v, ok := x.(T) или type switch.
🖨️ String() настраивает вывод через fmt, Error() делает тип ошибкой.
🕳️ Интерфейс равен nil, только если пусты и тип, и значение — возвращай буквальный nil.
🧬 Дженерики — один алгоритм для разных типов; ограничения задаются интерфейсами.
Chapter goals
Declare interfaces and understand implicit implementation.
Use polymorphism: interface variables, slices, and parameters.
Work with any: type assertions and type switches.
Compose interfaces from small ones and implement fmt.Stringer and error.
Explain the nil-interface trap.
Interface: a behavior contract
GoFlix has movies, series, and podcasts. All of them have a title and a duration, but each computes them differently. Classic OOP would define a base class Content and inherit from it. Go instead describes an interface — a set of methods a type must support. An interface holds no data and knows nothing about implementations: it is a contract that says "a type can do this".
Implicit implementation is Go's defining trait. In Java and C# you write implements; in Go a type automatically satisfies an interface if it has all the listed methods. This works even for an interface from a third-party package the type knows nothing about, and it reduces coupling in the code.
In the example below:
Content — title, duration, and description;
Playable — play and pause;
Movie and Series implement both interfaces, while Podcast implements only Content;
MediaPlayer is assembled from two interfaces — this is interface composition.
go
package mainimport "fmt"// Content — anything that has a title, a duration, and a description.type Content interface { Title() string Duration() int Description() string}// Playable — anything that can be played.type Playable interface { Play() string Pause() string}// MediaPlayer = Content + Playable.type MediaPlayer interface { Content Playable}type Movie struct { Name string Year int Minutes int Genre string}func (m Movie) Title() string { return m.Name }func (m Movie) Duration() int { return m.Minutes }func (m Movie) Description() string { return fmt.Sprintf("%s (%d), %s", m.Name, m.Year, m.Genre) }func (m Movie) Play() string { return "▶ " + m.Name }func (m Movie) Pause() string { return "⏸ " + m.Name }type Series struct { Name string Seasons int Episodes int AvgLen int}func (s Series) Title() string { return s.Name }func (s Series) Duration() int { return s.Episodes * s.AvgLen }func (s Series) Description() string { return fmt.Sprintf("%s, seasons: %d", s.Name, s.Seasons) }func (s Series) Play() string { return "▶ " + s.Name + " S01E01" }func (s Series) Pause() string { return "⏸ " + s.Name }// Podcast implements only Content: it has no Play or Pause methods.type Podcast struct { Name string Host string Minutes int}func (p Podcast) Title() string { return p.Name }func (p Podcast) Duration() int { return p.Minutes }func (p Podcast) Description() string { return fmt.Sprintf("podcast %q, host %s", p.Name, p.Host)}func printContentInfo(c Content) { fmt.Printf("%s — %d min\n", c.Description(), c.Duration())}func main() { var item Content = Movie{Name: "Interstellar", Year: 2014, Minutes: 169, Genre: "sci-fi"} printContentInfo(item) item = Series{Name: "Breaking Bad", Seasons: 5, Episodes: 62, AvgLen: 47} printContentInfo(item) catalog := []Content{ Movie{Name: "Dune", Year: 2021, Minutes: 155, Genre: "sci-fi"}, Series{Name: "Chernobyl", Seasons: 1, Episodes: 5, AvgLen: 65}, Podcast{Name: "GoFlix Talks", Host: "Anna", Minutes: 45}, } total := 0 for _, c := range catalog { fmt.Printf("%s: %d min\n", c.Title(), c.Duration()) total += c.Duration() } fmt.Println("total:", total, "min") var player MediaPlayer = Movie{Name: "Inception", Year: 2010, Minutes: 148, Genre: "sci-fi"} fmt.Println(player.Description()) // a method from Content fmt.Println(player.Play()) // a method from Playable}
The same code works with different types as long as they satisfy the interface. The printContentInfo function accepts not a concrete type but Content — it does not care whether a movie or a series arrived. In a []Content slice three different structs sit side by side, and in the loop Go itself dispatches to the right method implementation depending on which type is stored inside.
The same works for geometry: the Shape interface requires two methods, and the rectangle and the circle compute each by its own formula.
main.Rectangle: area 144.00, perimeter 50.00main.Circle: area 78.54, perimeter 31.42
A type that is missing a method does not fit the interface — and the compiler catches that. A podcast cannot be put into a MediaPlayer:
go
var p MediaPlayer = Podcast{} // Podcast does not implement MediaPlayer (missing method Pause)
any: the empty interface
The empty interface interface{} has no methods, so any type satisfies it — the analogue of Object in Java or Any in Kotlin. Since Go 1.18 it has a short name, any — it is just an alias.
The flexibility has a price: the compiler no longer knows what is inside, so the concrete type has to be checked separately. any is useful in generic places — parsing JSON, logging, arbitrary data — but in regular code it is used carefully, so as not to lose type safety.
Type assertion
The concrete value is extracted with a type assertionx.(T). The short form assumes you guessed the type and panics if you did not. The safe form v, ok := x.(T) returns a flag: on a mismatch — the zero value and false, without a panic. Use the safe one.
go
package mainimport "fmt"func main() { var anything any = "a string" // any is the same as interface{} fmt.Printf("%v (%T)\n", anything, anything) anything = 42 fmt.Printf("%v (%T)\n", anything, anything) var i any = "Hello" s := i.(string) // unsafe: panics if there is not a string inside fmt.Println(s) s2, ok := i.(string) // safe: ok tells whether it worked fmt.Println(s2, ok) n, ok := i.(int) fmt.Println(n, ok) // zero value and false — no panic}
stdout // program output
a string (string)42 (int)HelloHello true0 false
The short form with the wrong type:
go
package mainimport "fmt"func main() { var i any = "Hello" n := i.(int) // panic expected fmt.Println(n)}
text
panic: interface conversion: interface {} is string, not int
Type switch
When there are several possible types, instead of a chain of assertions you write a type switch — it goes through the types and picks the first matching case. Inside a branch the variable already has that branch's type — for example, Movie fields can be read. default catches everything else.
go
package mainimport "fmt"type Movie struct { Name string Year int}func classify(v any) string { switch val := v.(type) { case Movie: return fmt.Sprintf("movie %s (%d)", val.Name, val.Year) case string: return "string " + val case int: return fmt.Sprintf("number %d", val) case nil: return "nil" default: return fmt.Sprintf("other: %T", val) }}func main() { for _, v := range []any{Movie{Name: "The Matrix", Year: 1999}, "search", 42, nil, 8.7} { fmt.Println(classify(v)) }}
stdout // program output
movie The Matrix (1999)string searchnumber 42nilother: float64
Interface composition
Interfaces, like structs, are embedded into each other. The MediaPlayer from the first example does not redeclare methods — it combines Content and Playable: a type fits only if it can do everything both of them require. A movie fits; a podcast does not.
That is how a big contract is assembled from small, understandable pieces. This is ISP (the Interface Segregation Principle): many small interfaces beat one huge one. The standard library does this everywhere: io.Reader — one method Read, io.Writer — one method Write, and io.ReadWriter — their composition.
fmt.Stringer
The fmt package checks whether a value implements the fmt.Stringer interface — the method String() string. If it does, Println and %v print that method's result instead of the default dump of all fields. Handy for logging, debugging, and human-readable object views. The standard library has many such interfaces — for example, json.Marshaler for custom serialization.
go
package mainimport "fmt"type GoFlixUser struct { Name string Plan string MoviesWatched int}func (u GoFlixUser) String() string { return fmt.Sprintf("%s (%s, %d watched)", u.Name, u.Plan, u.MoviesWatched)}func main() { user := GoFlixUser{Name: "Alex", Plan: "Premium", MoviesWatched: 45} fmt.Println(user) // will call String() fmt.Printf("user: %v\n", user)}
stdout // program output
Alex (Premium, 45 watched)user: Alex (Premium, 45 watched)
The error interface
Errors in Go are values, and error is a built-in interface with a single method Error() string. Any type with this method can be returned as an error and given extra fields: status, code, context. Outside, the code works with the general interface and does not depend on the concrete type; when fields are needed, it extracts the concrete type.
go
package mainimport ( "errors" "fmt")type SubscriptionError struct { Status string Code int}func (e *SubscriptionError) Error() string { return fmt.Sprintf("subscription: %s (code %d)", e.Status, e.Code)}func checkSubscription(status string) error { switch status { case "expired": return &SubscriptionError{Status: status, Code: 402} case "banned": return &SubscriptionError{Status: status, Code: 403} } return nil}func main() { err := checkSubscription("expired") if err != nil { fmt.Println("error:", err) if subErr, ok := err.(*SubscriptionError); ok { // type assertion fmt.Println("status:", subErr.Status, "code:", subErr.Code) } } wrapped := fmt.Errorf("start movie: %w", checkSubscription("banned")) var subErr *SubscriptionError found := errors.As(wrapped, &subErr) _, asserted := wrapped.(*SubscriptionError) fmt.Println(asserted, found, subErr.Code)}
An interface variable stores two things: a dynamic type and a dynamic value. It equals nil only when both are nil. If you put a nil pointer of a concrete type into an interface, the type gets recorded while the value stays nil — and comparing with nil returns false even though it is "empty" inside. This is one of the most insidious corners of Go and a favorite interview question.
go
package mainimport "fmt"type Content interface{ Title() string }type Movie struct{ Name string }func (m *Movie) Title() string { if m == nil { return "<no movie>" } return m.Name}func main() { var c Content fmt.Println(c == nil) // no type, no value var m *Movie // nil pointer c = m fmt.Println(c == nil) // inside: type *Movie and value nil fmt.Println(c.Title()) // the method ran: the interface is not empty}
stdout // program output
truefalse<no movie>
Generics
A function with a type parameter[T constraint] works with any type that fits the constraint. Common constraints: any — any type, comparable — types with ==, cmp.Ordered — numbers and strings with < and >.
go
package mainimport ( "cmp" "fmt")// Map applies a function to every element of a slice of any type.func Map[T, U any](items []T, fn func(T) U) []U { result := make([]U, 0, len(items)) for _, item := range items { result = append(result, fn(item)) } return result}// MaxOf returns the maximum; cmp.Ordered — types comparable with < and >.func MaxOf[T cmp.Ordered](items ...T) T { best := items[0] for _, v := range items[1:] { if v > best { best = v } } return best}// Contains works with any comparable type.func Contains[T comparable](items []T, target T) bool { for _, v := range items { if v == target { return true } } return false}func main() { durations := Map([]int{148, 169, 155}, func(m int) string { return fmt.Sprintf("%d min", m) }) fmt.Println(durations) fmt.Println(MaxOf(8.1, 8.8, 7.5), MaxOf("Dune", "The Matrix")) fmt.Println(Contains([]string{"Dune", "Tenet"}, "Tenet"))}
stdout // program output
[148 min 169 min 155 min]8.8 The Matrixtrue
Interface
Generic
Different types with shared behavior (methods)
The same algorithm for different data types
The concrete type is chosen at runtime
The type is substituted at compile time
[]Content with movies and series
Map, Contains, MaxOf for slices of any type
Many of these functions already exist in the standard library: the slices and maps packages, the built-in min and max (Go 1.21+).
Practice
Homework
Notification channels. A Notifier interface with methods Send() string and ChannelName() string. Structs EmailNotification and PushNotification implement it. Put one object of each type into []Notifier and, in a loop, print the delivery channel and the send result.
Export to different formats. An Exporter interface with the method Export(). Structs CSVExport and JSONExport. A function RunExport(e Exporter) calls Export(); pass both types into it.
Interface composition. Interfaces Authorizer with Authorize() string and Capturer with Capture() string. A composite PaymentProvider combining both. A StripeProvider struct implements both interfaces plus the method String() string. Store it in a PaymentProvider variable, call both methods, and print the object with fmt.Println.
any in search results. A function InspectSearchResult(value any): with a safe assertion check whether it is a string, then an int; then a type switch over string, int, bool, SeriesResult (a struct with a Title field) and default. Call it with a string, a number, a bool, a SeriesResult, and a []string.
Moderation error. A ModerationError struct with fields ContentID and Reason and the method Error() string. A function CheckPoster(status string) error: nil for approved, otherwise ModerationError. Call it for approved and rejected; through an assertion, extract ContentID and Reason. Separately, demonstrate a nil pointer inside an error interface.
solution
go
package mainimport ( "fmt" "strings")// 1. Notification channels.type Notifier interface { Send() string ChannelName() string}type EmailNotification struct{ To, Subject string }func (e EmailNotification) Send() string { return "email to " + e.To + ": " + e.Subject }func (e EmailNotification) ChannelName() string { return "email" }type PushNotification struct{ DeviceID, Text string }func (p PushNotification) Send() string { return "push to " + p.DeviceID + ": " + p.Text }func (p PushNotification) ChannelName() string { return "push" }// 2. Export.type Exporter interface { Export() string}type CSVExport struct{ Rows [][]string }func (c CSVExport) Export() string { lines := make([]string, 0, len(c.Rows)) for _, row := range c.Rows { lines = append(lines, strings.Join(row, ",")) } return strings.Join(lines, "\n")}type JSONExport struct{ Title string }func (j JSONExport) Export() string { return fmt.Sprintf(`{"title":%q}`, j.Title) }func RunExport(e Exporter) { fmt.Printf("%T:\n%s\n", e, e.Export())}// 3. Payment provider.type Authorizer interface{ Authorize() string }type Capturer interface{ Capture() string }type PaymentProvider interface { Authorizer Capturer}type StripeProvider struct{ Account string }func (s StripeProvider) Authorize() string { return "authorize at " + s.Account }func (s StripeProvider) Capture() string { return "capture at " + s.Account }func (s StripeProvider) String() string { return "Stripe(" + s.Account + ")" }// 4. Search results.type SeriesResult struct{ Title string }func InspectSearchResult(value any) { if s, ok := value.(string); ok { fmt.Println("assertion: string", s) } if n, ok := value.(int); ok { fmt.Println("assertion: number", n) } switch v := value.(type) { case string: fmt.Println("switch: string", v) case int: fmt.Println("switch: int", v) case bool: fmt.Println("switch: bool", v) case SeriesResult: fmt.Println("switch: series", v.Title) default: fmt.Printf("switch: other type %T\n", v) }}// 5. Moderation error.type ModerationError struct { ContentID string Reason string}func (e *ModerationError) Error() string { return fmt.Sprintf("poster %s rejected: %s", e.ContentID, e.Reason)}func CheckPoster(status string) error { if status == "approved" { return nil } return &ModerationError{ContentID: "poster-42", Reason: "status=" + status}}func CheckPosterBuggy(status string) error { var err *ModerationError if status != "approved" { err = &ModerationError{ContentID: "poster-42", Reason: "status=" + status} } return err // trap: a nil pointer inside the error interface}func main() { for _, n := range []Notifier{ EmailNotification{To: "alex@goflix.ru", Subject: "New season"}, PushNotification{DeviceID: "iphone-7", Text: "50% off"}, } { fmt.Println(n.ChannelName(), "→", n.Send()) } RunExport(CSVExport{Rows: [][]string{{"title", "year"}, {"Dune", "2021"}}}) RunExport(JSONExport{Title: "Dune"}) var provider PaymentProvider = StripeProvider{Account: "goflix-main"} fmt.Println(provider.Authorize()) fmt.Println(provider.Capture()) fmt.Println(provider) for _, v := range []any{"dune", 42, true, SeriesResult{Title: "Chernobyl"}, []string{"a"}} { InspectSearchResult(v) } fmt.Println(CheckPoster("approved") == nil) err := CheckPoster("rejected") fmt.Println(err) if modErr, ok := err.(*ModerationError); ok { fmt.Println("ContentID:", modErr.ContentID, "| Reason:", modErr.Reason) } fmt.Println("buggy approved == nil:", CheckPosterBuggy("approved") == nil)}
stdout // program output
email → email to alex@goflix.ru: New seasonpush → push to iphone-7: 50% offmain.CSVExport:title,yearDune,2021main.JSONExport:{"title":"Dune"}authorize at goflix-maincapture at goflix-mainStripe(goflix-main)assertion: string duneswitch: string duneassertion: number 42switch: int 42switch: bool trueswitch: series Chernobylswitch: other type []stringtrueposter poster-42 rejected: status=rejectedContentID: poster-42 | Reason: status=rejectedbuggy approved == nil: false
Check yourself
questionWhat is an interface, and how does a type implement it?
A set of method signatures — a behavior contract without data. A type implements an interface implicitly: it is enough to have all its methods; nobody writes implements.
questionHow is polymorphism achieved in Go?
Through interfaces: a variable, parameter, or slice of an interface type stores values of different types, and a method call dispatches to the concrete type's implementation.
questionHow does the short type assertion form differ from the ok form?
v := x.(T) panics on a type mismatch. v, ok := x.(T) returns the zero value and false.
questionWhen is an interface variable equal to nil?
Only when it holds neither a dynamic type nor a value. An interface with a nil pointer of a concrete type inside is not equal to nil.
questionWhy does a function returning var e *MyErr as error produce err != nil?
The interface recorded the type *MyErr with a nil value — such an interface is not empty. You must return a literal nil.
questionWhat is ISP, and how does interface composition help follow it?
The Interface Segregation Principle: many small interfaces beat one big one. A big contract is assembled by embedding small ones: io.ReadWriter = io.Reader + io.Writer.
questionWhy doesn't Dog{} implement the interface if the method is declared as func (d *Dog) Speak()?
A method with a pointer receiver is only in the method set of *Dog. You have to put the pointer in: &Dog{}.
questionHow do generics differ from interfaces?
An interface is shared behavior of different types, with the type chosen at runtime. A generic is one algorithm for different data types, with the type substituted at compile time; type parameter constraints are interfaces.
Key takeaways
📜 An interface is a behavior contract; implementation is implicit, without implements.
🎭 Polymorphism: interface variables, parameters, and slices work with any fitting types.
🧩 Small interfaces are composed into big ones — the ISP principle.
🔍 any accepts everything; the type is extracted via v, ok := x.(T) or a type switch.
🖨️ String() customizes fmt output, Error() makes a type an error.
🕳️ An interface equals nil only when both the type and the value are empty — return a literal nil.
🧬 Generics are one algorithm for many types; constraints are interfaces.