Part 2. Language BasicsLesson 08# go# basics# conditions

switch-case

switch without break, multiple values, conditions, fallthrough, type switch

Цели главы

  • Писать switch по значению с default.
  • Перечислять несколько значений в одном case.
  • Использовать switch с инициализацией и без выражения — для диапазонов.
  • Понимать fallthrough и type switch.

Когда if-else становится громоздким

Представь 10 жанров, и для каждого своя обработка: 10 веток else if подряд читать тяжело. switch проверяет значение и выполняет подходящий case; если не подошёл ни один — выполняется default.

go
package main

import "fmt"

func genreName(code int) string {
    switch code {
    case 1:
        return "Боевик"
    case 2:
        return "Комедия"
    case 3:
        return "Драма"
    default:
        return "Неизвестный жанр"
    }
}

func main() {
    fmt.Println(genreName(3))
    fmt.Println(genreName(5))
}
stdout // вывод программы
Драма
Неизвестный жанр

Несколько значений в одном case

Значения перечисляют через запятую — это как «или» в if, только компактнее. Не нужно дублировать одинаковый код в разных case.

go
package main

import "fmt"

func audience(rating string) string {
    switch rating {
    case "G", "PG":
        return "для всей семьи"
    case "PG-13":
        return "с 13 лет"
    case "R", "NC-17":
        return "для взрослых"
    default:
        return "рейтинг не указан"
    }
}

func main() {
    fmt.Println(audience("PG"))
    fmt.Println(audience("PG-13"))
    fmt.Println(audience("NC-17"))
}
stdout // вывод программы
для всей семьи
с 13 лет
для взрослых

switch с инициализацией

Как и в if, переменную можно объявить прямо в switch — она будет видна только внутри него и не засорит внешнюю область видимости.

go
package main

import (
    "fmt"
    "time"
)

func main() {
    switch h := time.Now().Hour(); { // h видна только внутри switch
    case h < 12:
        fmt.Println("Доброе утро")
    case h < 18:
        fmt.Println("Добрый день")
    default:
        fmt.Println("Добрый вечер")
    }
    // недетерминированный вывод
}

Пример вывода — зависит от времени запуска:

text
Добрый день

switch без выражения — для диапазонов

Если после switch ничего не написать, каждый case содержит условие, как в if. По сути это switch true: Go ищет первый case, условие которого истинно. Для диапазонов значений это читается гораздо чище цепочки else if.

go
package main

import "fmt"

func verdict(score float64) string {
    switch {
    case score >= 9.0:
        return "шедевр"
    case score >= 7.5:
        return "хороший фильм"
    case score >= 5.0:
        return "на один раз"
    default:
        return "не стоит времени"
    }
}

func main() {
    for _, s := range []float64{9.3, 7.3, 4.1} {
        fmt.Println(s, "—", verdict(s))
    }
}
stdout // вывод программы
9.3 — шедевр
7.3 — на один раз
4.1 — не стоит времени

fallthrough

Иногда нужно обратное — провалиться в следующий case. Для этого есть fallthrough: он выполняет тело следующего case безусловно, не проверяя его значение или условие. Пригождается для накопительной логики — старший тариф получает всё, что есть у младших.

go
package main

import "fmt"

func main() {
    tier := 1 // 1 — максимальный тариф
    fmt.Println("Тариф", tier, "включает:")
    switch tier {
    case 1:
        fmt.Println("- 4K и Dolby Atmos")
        fallthrough
    case 2:
        fmt.Println("- просмотр без рекламы")
        fallthrough
    default:
        fmt.Println("- базовый каталог")
    }
}
stdout // вывод программы
Тариф 1 включает:
- 4K и Dolby Atmos
- просмотр без рекламы
- базовый каталог

Type switch

Особый вид switch определяет тип значения: switch v := x.(type) { case int: … }. Работает со значениями типа интерфейс — например, с пустым интерфейсом interface{} (его короткое имя any), которому подходит любой тип. Внутри каждой ветки v уже имеет тип этой ветки. Подробно интерфейсы разобраны в 16 — Интерфейсы.

go
package main

import "fmt"

func identify(v any) string {
    switch val := v.(type) {
    case int:
        return fmt.Sprintf("%d → int", val)
    case string:
        return fmt.Sprintf("%q → string", val)
    case float64:
        return fmt.Sprintf("%.1f → float64", val)
    case bool:
        return fmt.Sprintf("%t → bool", val)
    default:
        return fmt.Sprintf("%v → %T", val, val)
    }
}

func main() {
    fmt.Println(identify(42))
    fmt.Println(identify("Матрица"))
    fmt.Println(identify(9.1))
    fmt.Println(identify(true))
    fmt.Println(identify([]int{1, 2}))
}
stdout // вывод программы
42 → int
"Матрица" → string
9.1 → float64
true → bool
[1 2] → []int

Практика в уроке: кнопки плеера

Пользователь жмёт кнопки плеера — у каждого действия свой обработчик. Идеальная задача для switch.

go
package main

import "fmt"

func handleAction(action string) {
    switch action {
    case "play":
        fmt.Println("Воспроизведение")
    case "pause":
        fmt.Println("Пауза")
    default:
        fmt.Println("Нет такого действия:", action)
    }
}

func main() {
    for _, action := range []string{"play", "pause", "skip"} {
        handleAction(action)
    }
}
stdout // вывод программы
Воспроизведение
Пауза
Нет такого действия: skip

Практика

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

  1. Создай слайс команд: play, pause, stop, next, previous, volume_up, volume_down, info, like, share, quit.
  2. Перебери их в цикле и обработай каждую через switch.
  3. Объедини в один case через запятую: управление воспроизведением (play, pause, stop), переключение фильма (next, previous) и громкость (volume_up, volume_down).
  4. Незнакомые команды — в default; quit завершает обработку.
решениеЭталонное решение
go
package main

import "fmt"

func main() {
    commands := []string{
        "play", "pause", "stop", "next", "previous",
        "volume_up", "volume_up", "volume_down",
        "info", "like", "share", "rewind", "quit", "play",
    }

    volume := 50
player:
    for _, cmd := range commands {
        switch cmd {
        case "play", "pause", "stop":
            fmt.Println("Воспроизведение:", cmd)
        case "next", "previous":
            fmt.Println("Переключение фильма:", cmd)
        case "volume_up", "volume_down":
            if cmd == "volume_up" {
                volume += 10
            } else {
                volume -= 10
            }
            fmt.Println("Громкость:", volume)
        case "info":
            fmt.Println("Интерстеллар, 2014, 169 мин")
        case "like":
            fmt.Println("Добавлено в избранное")
        case "share":
            fmt.Println("Ссылка скопирована")
        case "quit":
            fmt.Println("Выход из плеера")
            break player
        default:
            fmt.Println("Неизвестная команда:", cmd)
        }
    }
}
stdout // вывод программы
Воспроизведение: play
Воспроизведение: pause
Воспроизведение: stop
Переключение фильма: next
Переключение фильма: previous
Громкость: 60
Громкость: 70
Громкость: 60
Интерстеллар, 2014, 169 мин
Добавлено в избранное
Ссылка скопирована
Неизвестная команда: rewind
Выход из плеера

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

go
package main

import "fmt"

func main() {
    x := 5
    switch {
    case x > 3:
        fmt.Println("больше 3")
        fallthrough
    case x > 10:
        fmt.Println("больше 10")
    case x > 1:
        fmt.Println("больше 1")
    }
}
самопроверкаОтвет
text
больше 3
больше 10

fallthrough выполняет тело следующего case, не проверяя x > 10. Дальше провала нет: после второй ветки switch завершается, и «больше 1» не печатается.

Проверь себя

вопросНужен ли break в конце case в Go?

Нет. После выполнения ветки Go сам выходит из switch, провала в следующий case нет.

вопросКак обработать несколько значений одним case?

Перечислить их через запятую: case "G", "PG":.

вопросКак с помощью switch проверить диапазоны значений?

Написать switch без выражения и условия в case: case score >= 9: — выполняется первый истинный.

вопросЧто делает fallthrough?

Безусловно выполняет тело следующего case, не проверяя его условие.

вопросКак узнать конкретный тип значения в переменной типа any?

Через type switch: switch v := x.(type) { case int: … case string: … }.

вопросПочему break внутри switch не останавливает окружающий цикл?

В Go break относится к ближайшему switch, select или for. Внутри switch он выходит из switch; для цикла нужна метка: break loop.


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

  • 🔀 switch заменяет длинные цепочки else if и читается проще.
  • 🚫 break в case не нужен — провала по умолчанию нет.
  • 📋 Несколько значений в одном case — через запятую.
  • 📏 switch без выражения удобен для диапазонов; с инициализацией — не засоряет область видимости.
  • ⬇️ fallthrough безусловно проваливается в следующий case — используй редко.
  • 🧬 Type switch выбирает ветку по типу значения в интерфейсе.

Chapter goals

  • Write a value-based switch with default.
  • List several values in one case.
  • Use switch with an initializer and without an expression — for ranges.
  • Understand fallthrough and the type switch.

When if-else gets unwieldy

Imagine 10 genres, each with its own handling: ten else if branches in a row are hard to read. switch checks a value and runs the matching case; if none matches, default runs.

go
package main

import "fmt"

func genreName(code int) string {
    switch code {
    case 1:
        return "Action"
    case 2:
        return "Comedy"
    case 3:
        return "Drama"
    default:
        return "Unknown genre"
    }
}

func main() {
    fmt.Println(genreName(3))
    fmt.Println(genreName(5))
}
stdout // program output
Drama
Unknown genre

Several values in one case

Values are listed separated by commas — it is like «or» in an if, only more compact. No need to duplicate identical code across different cases.

go
package main

import "fmt"

func audience(rating string) string {
    switch rating {
    case "G", "PG":
        return "fun for the whole family"
    case "PG-13":
        return "13 and up"
    case "R", "NC-17":
        return "adults only"
    default:
        return "rating not specified"
    }
}

func main() {
    fmt.Println(audience("PG"))
    fmt.Println(audience("PG-13"))
    fmt.Println(audience("NC-17"))
}
stdout // program output
fun for the whole family
13 and up
adults only

switch with an initializer

As with if, you can declare a variable right in the switch — it stays visible only inside it and does not pollute the outer scope.

go
package main

import (
    "fmt"
    "time"
)

func main() {
    switch h := time.Now().Hour(); { // h is visible only inside the switch
    case h < 12:
        fmt.Println("Good morning")
    case h < 18:
        fmt.Println("Good afternoon")
    default:
        fmt.Println("Good evening")
    }
    // non-deterministic output
}

Sample output — depends on when you run it:

text
Good afternoon

switch without an expression — for ranges

If you write nothing after switch, each case holds a condition, just like in an if. It is essentially switch true: Go picks the first case whose condition holds. For ranges of values this reads far better than an else if chain.

go
package main

import "fmt"

func verdict(score float64) string {
    switch {
    case score >= 9.0:
        return "a masterpiece"
    case score >= 7.5:
        return "a good movie"
    case score >= 5.0:
        return "a one-time watch"
    default:
        return "not worth your time"
    }
}

func main() {
    for _, s := range []float64{9.3, 7.3, 4.1} {
        fmt.Println(s, "—", verdict(s))
    }
}
stdout // program output
9.3 — a masterpiece
7.3 — a one-time watch
4.1 — not worth your time

fallthrough

Sometimes you want the opposite — to fall into the next case. That is what fallthrough is for: it runs the body of the next case unconditionally, without checking its value or condition. It comes in handy for cumulative logic — the top tier gets everything the lower tiers have.

go
package main

import "fmt"

func main() {
    tier := 1 // 1 — the top tier
    fmt.Println("Tier", tier, "includes:")
    switch tier {
    case 1:
        fmt.Println("- 4K and Dolby Atmos")
        fallthrough
    case 2:
        fmt.Println("- ad-free viewing")
        fallthrough
    default:
        fmt.Println("- the basic catalog")
    }
}
stdout // program output
Tier 1 includes:
- 4K and Dolby Atmos
- ad-free viewing
- the basic catalog

Type switch

A special kind of switch determines the type of a value: switch v := x.(type) { case int: … }. It works on values of interface types — for example, the empty interface interface{} (its short name is any), which accepts any type. Inside each branch, v already has that branch's type. Interfaces are covered in detail in 16 — Interfaces.

go
package main

import "fmt"

func identify(v any) string {
    switch val := v.(type) {
    case int:
        return fmt.Sprintf("%d → int", val)
    case string:
        return fmt.Sprintf("%q → string", val)
    case float64:
        return fmt.Sprintf("%.1f → float64", val)
    case bool:
        return fmt.Sprintf("%t → bool", val)
    default:
        return fmt.Sprintf("%v → %T", val, val)
    }
}

func main() {
    fmt.Println(identify(42))
    fmt.Println(identify("The Matrix"))
    fmt.Println(identify(9.1))
    fmt.Println(identify(true))
    fmt.Println(identify([]int{1, 2}))
}
stdout // program output
42 → int
"The Matrix" → string
9.1 → float64
true → bool
[1 2] → []int

In-lesson practice: player buttons

The user presses player buttons — each action gets its own handler. A perfect task for switch.

go
package main

import "fmt"

func handleAction(action string) {
    switch action {
    case "play":
        fmt.Println("Playing")
    case "pause":
        fmt.Println("Paused")
    default:
        fmt.Println("No such action:", action)
    }
}

func main() {
    for _, action := range []string{"play", "pause", "skip"} {
        handleAction(action)
    }
}
stdout // program output
Playing
Paused
No such action: skip

Practice

Homework: an interactive GoFlix player

  1. Create a slice of commands: play, pause, stop, next, previous, volume_up, volume_down, info, like, share, quit.
  2. Loop over them and handle each one with a switch.
  3. Combine related commands into one case, separated by commas: playback control (play, pause, stop), switching the movie (next, previous), and volume (volume_up, volume_down).
  4. Unknown commands go to default; quit ends the processing.
solution
go
package main

import "fmt"

func main() {
    commands := []string{
        "play", "pause", "stop", "next", "previous",
        "volume_up", "volume_up", "volume_down",
        "info", "like", "share", "rewind", "quit", "play",
    }

    volume := 50
player:
    for _, cmd := range commands {
        switch cmd {
        case "play", "pause", "stop":
            fmt.Println("Playback:", cmd)
        case "next", "previous":
            fmt.Println("Switching movie:", cmd)
        case "volume_up", "volume_down":
            if cmd == "volume_up" {
                volume += 10
            } else {
                volume -= 10
            }
            fmt.Println("Volume:", volume)
        case "info":
            fmt.Println("Interstellar, 2014, 169 min")
        case "like":
            fmt.Println("Added to favorites")
        case "share":
            fmt.Println("Link copied")
        case "quit":
            fmt.Println("Exiting the player")
            break player
        default:
            fmt.Println("Unknown command:", cmd)
        }
    }
}
stdout // program output
Playback: play
Playback: pause
Playback: stop
Switching movie: next
Switching movie: previous
Volume: 60
Volume: 70
Volume: 60
Interstellar, 2014, 169 min
Added to favorites
Link copied
Unknown command: rewind
Exiting the player

Drill: predict the output

go
package main

import "fmt"

func main() {
    x := 5
    switch {
    case x > 3:
        fmt.Println("greater than 3")
        fallthrough
    case x > 10:
        fmt.Println("greater than 10")
    case x > 1:
        fmt.Println("greater than 1")
    }
}
self-check
text
greater than 3
greater than 10

fallthrough runs the body of the next case without checking x > 10. There is no further fall-through: after the second branch the switch ends, so «greater than 1» is never printed.

Check yourself

questionDo you need break at the end of a case in Go?

No. Once a branch has run, Go exits the switch on its own; there is no fall-through into the next case.

questionHow do you handle several values in one case?

List them separated by commas: case "G", "PG":.

questionHow do you check ranges of values with a switch?

Write a switch without an expression and put conditions in the cases: case score >= 9: — the first true one runs.

questionWhat does fallthrough do?

It unconditionally runs the body of the next case without checking its condition.

questionHow do you find out the concrete type of a value stored in an any variable?

With a type switch: switch v := x.(type) { case int: … case string: … }.

questionWhy doesn't a break inside a switch stop the surrounding loop?

In Go, break applies to the nearest switch, select, or for. Inside a switch it exits the switch; for the loop you need a label: break loop.


Key takeaways

  • 🔀 switch replaces long else if chains and is easier to read.
  • 🚫 No break needed in a case — there is no fall-through by default.
  • 📋 Several values in one case — separated by commas.
  • 📏 A switch without an expression is great for ranges; one with an initializer keeps the scope clean.
  • ⬇️ fallthrough unconditionally falls into the next case — use it rarely.
  • 🧬 The type switch picks a branch based on the type of the value stored in an interface.
// related topics and cheatsheets