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

if-else conditions

if with initialization, logical operators and comparisons

Цели главы

  • Писать if, if-else и цепочки else if без синтаксических ошибок.
  • Объявлять переменную прямо в условии и понимать её область видимости.
  • Комбинировать условия через &&, ||, ! и знать операторы сравнения.
  • Избегать «лесенки» вложенных if.

Зачем нужны условия

До сих пор код выполнялся строго сверху вниз. В реальном приложении логика ветвится: пользователь с Premium смотрит без рекламы, фильм с высоким рейтингом попадает в рекомендации, закончились билеты — об этом надо сказать. Для этого есть if — он проверяет условие и выбирает, какой код выполнить.

Синтаксис if, else и else if

  • Условие пишется без круглых скобок — в отличие от C, Java и JavaScript.
  • Фигурные скобки обязательны, даже если в теле одна строка.
  • else ставится на той же строке, что и закрывающая } блока if.
  • В цепочке else if Go проверяет условия сверху вниз и выполняет первую подошедшую ветку, остальные пропускает.
go
package main

import "fmt"

func ticketStatus(left int) string {
    if left > 0 {
        return "Билеты есть"
    } else if left == 0 {
        return "Билетов нет"
    } else {
        return "Система сломалась: остаток меньше нуля"
    }
}

func main() {
    fmt.Println(ticketStatus(5))
    fmt.Println(ticketStatus(0))
    fmt.Println(ticketStatus(-2))
}
stdout // вывод программы
Билеты есть
Билетов нет
Система сломалась: остаток меньше нуля

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

Фишка, которой нет в большинстве языков: прямо в if можно объявить переменную — if переменная := выражение; условие { … }. Переменная видна только внутри if и всех его else, а снаружи её не существует — внешняя область видимости не засоряется.

go
package main

import "fmt"

func loyaltyDiscount(years int) int {
    if years >= 5 {
        return 15
    } else if years >= 2 {
        return 10
    } else if years >= 1 {
        return 5
    }
    return 0
}

func main() {
    if d := loyaltyDiscount(6); d > 0 {
        fmt.Printf("Скидка %d%%\n", d)
    } else {
        fmt.Println("Скидки нет")
    }

    if d := loyaltyDiscount(0); d > 0 {
        fmt.Printf("Скидка %d%%\n", d)
    } else {
        fmt.Println("Скидки нет") // d видна и в else
    }
    // здесь d уже не существует
}
stdout // вывод программы
Скидка 15%
Скидки нет

Этот приём постоянно встречается с ошибками: if err := save(); err != nil { … } — см. 13 — Обработка ошибок.

Логические операторы

Оператор Смысл Когда true
&& И оба условия истинны
|| ИЛИ хотя бы одно условие истинно
! НЕ инвертирует значение: !true — это false
go
package main

import "fmt"

func main() {
    userAge := 17
    hasPremium := true
    isBanned := false

    fmt.Println(userAge >= 18 && hasPremium) // И: нужны оба условия
    fmt.Println(userAge >= 18 || hasPremium) // ИЛИ: достаточно одного
    fmt.Println(!isBanned)                   // НЕ: инвертирует значение
}
stdout // вывод программы
false
true
true

Операторы сравнения

Оператор Значение
== равно
!= не равно
<, > меньше, больше
<=, >= меньше или равно, больше или равно

Результат любого сравнения — bool: true или false.

Вложенные if и «лесенка»

if можно вкладывать друг в друга, но код быстро превращается в лесенку, которую трудно читать:

go
if isLoggedIn {
    if isVerified {
        if hasTicket {
            fmt.Println("Проходите в зал")
        }
    }
}

Те же проверки в одном условии читаются проще и работают так же:

go
if isLoggedIn && isVerified && hasTicket {
    fmt.Println("Проходите в зал")
}

Практика в уроке: категория фильма по рейтингу

Функция categorizeRating принимает рейтинг и возвращает категорию: от 8.5 — «The best», от 7 — «Good», от 5 — «Okay», ниже — «Bad».

go
package main

import "fmt"

func categorizeRating(r float64) string {
    if r >= 8.5 {
        return "The best"
    } else if r >= 7.0 {
        return "Good"
    } else if r >= 5.0 {
        return "Okay"
    }
    return "Bad"
}

func main() {
    fmt.Println(categorizeRating(9.2))
    fmt.Println(categorizeRating(7.8))
    fmt.Println(categorizeRating(6.1))
    fmt.Println(categorizeRating(3.4))
}
stdout // вывод программы
The best
Good
Okay
Bad

Практика

Домашнее задание: контроль доступа GoFlix

Есть пользователь: имя, возраст, тариф (free или premium) и флаг блокировки. У фильма — возрастной рейтинг: 6, 12, 16 или 18. Программа делает три проверки:

  1. Не заблокирован ли аккаунт — если да, сразу отказ.
  2. Подходит ли возраст под рейтинг фильма.
  3. Тариф free — «Доступно с рекламой», premium — «Приятного просмотра!».

Используй if с инициализацией, операторы &&, || и !. Проверь на взрослом с Premium, подростке 15 лет на фильме 18+ и заблокированном аккаунте.

решениеЭталонное решение
go
package main

import "fmt"

func checkAccess(name string, age int, plan string, isBanned bool, filmRating int) string {
    if age < 0 || age > 120 {
        return name + ": некорректный возраст"
    }
    if filmRating != 6 && filmRating != 12 && filmRating != 16 && filmRating != 18 {
        return name + ": неизвестный возрастной рейтинг"
    }
    if isBanned {
        return name + ": аккаунт заблокирован, доступ запрещён"
    }
    if ageOK := age >= filmRating; !ageOK {
        return fmt.Sprintf("%s: фильм %d+ недоступен по возрасту", name, filmRating)
    }
    if plan == "free" {
        return name + ": доступно с рекламой"
    }
    return name + ": приятного просмотра!"
}

func main() {
    fmt.Println(checkAccess("Анна", 32, "premium", false, 18))
    fmt.Println(checkAccess("Петя", 15, "premium", false, 18))
    fmt.Println(checkAccess("Олег", 40, "free", true, 12))
    fmt.Println(checkAccess("Ира", 16, "free", false, 16))
}
stdout // вывод программы
Анна: приятного просмотра!
Петя: фильм 18+ недоступен по возрасту
Олег: аккаунт заблокирован, доступ запрещён
Ира: доступно с рекламой

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

go
package main

import "fmt"

func main() {
    score := 85
    if score > 50 {
        fmt.Println("больше 50")
    } else if score > 80 {
        fmt.Println("больше 80")
    }
    if x := score / 10; x == 8 {
        fmt.Println("x =", x)
    }
}
самопроверкаОтвет
text
больше 50
x = 8

Выполняется только первая подошедшая ветка: score > 50 уже истинно, до score > 80 дело не доходит. Чтобы ловить более узкий диапазон, проверяй его раньше. 85 / 10 — целочисленное деление, получается 8.

Проверь себя

вопросЧем синтаксис if в Go отличается от C или Java?

Условие пишется без круглых скобок, фигурные скобки обязательны всегда, else стоит на одной строке с закрывающей }.

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

Компилятор ставит точку с запятой в конце строки после }. Оператор if заканчивается, и else оказывается в начале нового оператора — синтаксическая ошибка.

вопросГде видна переменная, объявленная в if d := f(); d > 0?

Только внутри этого if и всех его веток else if и else.

вопросЧто делает ! и когда a || b истинно?

! инвертирует bool. a || b истинно, если истинно хотя бы одно из условий.

вопросЗачем при user != nil && user.Age > 18 проверка на nil стоит слева?

Из-за короткого замыкания: если user равен nil, правая часть не вычисляется, и обращения к полю nil-указателя не будет.

вопросКак избавиться от лесенки вложенных if?

Объединить условия через && или использовать ранние возвраты: проверка → return.


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

  • 🔀 if без круглых скобок, фигурные обязательны, else — на строке с }.
  • 🪜 В цепочке else if выполняется первая подошедшая ветка — порядок проверок важен.
  • 📦 if x := f(); условие ограничивает жизнь переменной блоком условия.
  • ⚙️ &&, ||, ! комбинируют условия и вычисляются с коротким замыканием.
  • 🧹 Вместо лесенки вложенных if — общее условие или ранний return.

Chapter goals

  • Write if, if-else, and else if chains without syntax errors.
  • Declare a variable right in the condition and understand its scope.
  • Combine conditions with &&, ||, ! and know the comparison operators.
  • Avoid the nested-if "staircase".

Why conditions exist

So far the code has run strictly top to bottom. In a real application the logic branches: a Premium user watches without ads, a highly rated movie lands in recommendations, the tickets ran out — and you have to say so. That's what if is for: it checks a condition and picks which code to run.

The syntax of if, else, and else if

  • The condition is written without parentheses — unlike C, Java, and JavaScript.
  • Curly braces are mandatory, even for a one-line body.
  • else goes on the same line as the if block's closing }.
  • In an else if chain, Go checks the conditions top to bottom and runs the first branch that matches, skipping the rest.
go
package main

import "fmt"

func ticketStatus(left int) string {
    if left > 0 {
        return "Tickets available"
    } else if left == 0 {
        return "Sold out"
    } else {
        return "Broken data: tickets left below zero"
    }
}

func main() {
    fmt.Println(ticketStatus(5))
    fmt.Println(ticketStatus(0))
    fmt.Println(ticketStatus(-2))
}
stdout // program output
Tickets available
Sold out
Broken data: tickets left below zero

if with an initializer

A feature most languages don't have: you can declare a variable right in the if — if variable := expression; condition { … }. The variable is visible only inside the if and all of its else branches; outside it doesn't exist — the outer scope isn't polluted.

go
package main

import "fmt"

func loyaltyDiscount(years int) int {
    if years >= 5 {
        return 15
    } else if years >= 2 {
        return 10
    } else if years >= 1 {
        return 5
    }
    return 0
}

func main() {
    if d := loyaltyDiscount(6); d > 0 {
        fmt.Printf("Discount %d%%\n", d)
    } else {
        fmt.Println("No discount")
    }

    if d := loyaltyDiscount(0); d > 0 {
        fmt.Printf("Discount %d%%\n", d)
    } else {
        fmt.Println("No discount") // d is visible in else too
    }
    // here d no longer exists
}
stdout // program output
Discount 15%
No discount

This pattern comes up constantly with errors: if err := save(); err != nil { … } — see 13 — Error handling.

Logical operators

Operator Meaning When it's true
&& AND both conditions are true
|| OR at least one condition is true
! NOT inverts the value: !true is false
go
package main

import "fmt"

func main() {
    userAge := 17
    hasPremium := true
    isBanned := false

    fmt.Println(userAge >= 18 && hasPremium) // AND: both conditions required
    fmt.Println(userAge >= 18 || hasPremium) // OR: one is enough
    fmt.Println(!isBanned)                   // NOT: inverts the value
}
stdout // program output
false
true
true

Comparison operators

Operator Meaning
== equal
!= not equal
<, > less, greater
<=, >= less or equal, greater or equal

The result of any comparison is a bool: true or false.

Nested ifs and the "staircase"

ifs can nest inside each other, but the code quickly turns into a staircase that's hard to read:

go
if isLoggedIn {
    if isVerified {
        if hasTicket {
            fmt.Println("Enter the theater")
        }
    }
}

The same checks in one condition read better and work the same:

go
if isLoggedIn && isVerified && hasTicket {
    fmt.Println("Enter the theater")
}

In-lesson practice: movie rating category

The categorizeRating function takes a rating and returns a category: 8.5 and up — "The best", from 7 — "Good", from 5 — "Okay", below — "Bad".

go
package main

import "fmt"

func categorizeRating(r float64) string {
    if r >= 8.5 {
        return "The best"
    } else if r >= 7.0 {
        return "Good"
    } else if r >= 5.0 {
        return "Okay"
    }
    return "Bad"
}

func main() {
    fmt.Println(categorizeRating(9.2))
    fmt.Println(categorizeRating(7.8))
    fmt.Println(categorizeRating(6.1))
    fmt.Println(categorizeRating(3.4))
}
stdout // program output
The best
Good
Okay
Bad

Practice

Homework: GoFlix access control

There's a user: name, age, plan (free or premium), and a ban flag. A movie has an age rating: 6, 12, 16, or 18. The program runs three checks:

  1. Whether the account is banned — if so, refuse immediately.
  2. Whether the age fits the movie's rating.
  3. free plan — "Available with ads", premium — "Enjoy the movie!".

Use if with an initializer and the &&, ||, ! operators. Test with an adult on Premium, a 15-year-old at an 18+ movie, and a banned account.

solution
go
package main

import "fmt"

func checkAccess(name string, age int, plan string, isBanned bool, filmRating int) string {
    if age < 0 || age > 120 {
        return name + ": invalid age"
    }
    if filmRating != 6 && filmRating != 12 && filmRating != 16 && filmRating != 18 {
        return name + ": unknown age rating"
    }
    if isBanned {
        return name + ": account banned, access denied"
    }
    if ageOK := age >= filmRating; !ageOK {
        return fmt.Sprintf("%s: the %d+ movie is not available at your age", name, filmRating)
    }
    if plan == "free" {
        return name + ": available with ads"
    }
    return name + ": enjoy the movie!"
}

func main() {
    fmt.Println(checkAccess("Anna", 32, "premium", false, 18))
    fmt.Println(checkAccess("Peter", 15, "premium", false, 18))
    fmt.Println(checkAccess("Oleg", 40, "free", true, 12))
    fmt.Println(checkAccess("Ira", 16, "free", false, 16))
}
stdout // program output
Anna: enjoy the movie!
Peter: the 18+ movie is not available at your age
Oleg: account banned, access denied
Ira: available with ads

Exercise: predict the output

go
package main

import "fmt"

func main() {
    score := 85
    if score > 50 {
        fmt.Println("above 50")
    } else if score > 80 {
        fmt.Println("above 80")
    }
    if x := score / 10; x == 8 {
        fmt.Println("x =", x)
    }
}
self-check
text
above 50
x = 8

Only the first matching branch runs: score > 50 is already true, so score > 80 never gets its turn. To catch a narrower range, check it earlier. 85 / 10 is integer division, giving 8.

Check yourself

questionHow does Go's if syntax differ from C or Java?

The condition is written without parentheses, curly braces are always mandatory, and else sits on the same line as the closing }.

questionWhy can't else be moved to a new line?

The compiler puts a semicolon at the end of the line after }. The if statement ends, and else ends up at the start of a new statement — a syntax error.

questionWhere is a variable declared in if d := f(); d > 0 visible?

Only inside that if and all of its else if and else branches.

questionWhat does ! do, and when is a || b true?

! inverts a bool. a || b is true when at least one of the conditions is true.

questionWhy does the nil check go on the left in user != nil && user.Age > 18?

Because of short-circuiting: if user is nil, the right side isn't evaluated, so there's no access through a nil pointer.

questionHow do you get rid of a nested-if staircase?

Combine the conditions with &&, or use early returns: check → return.


Key takeaways

  • 🔀 if without parentheses, braces always mandatory, else on the line with }.
  • 🪜 In an else if chain the first matching branch runs — the order of checks matters.
  • 📦 if x := f(); condition limits the variable's lifetime to the condition's block.
  • ⚙️ &&, ||, ! combine conditions and evaluate with short-circuiting.
  • 🧹 Instead of a nested-if staircase — one combined condition or an early return.
// related topics and cheatsheets