Part 2. Language BasicsLesson 07# go# basics# loops

for loops

four forms of for, range over slices, strings and maps, nested loops

Цели главы

  • Писать все четыре формы for.
  • Управлять циклом через break и continue.
  • Обходить слайсы, строки и мапы через range и понимать, что он возвращает.
  • Писать вложенные циклы и циклы с несколькими переменными.

Один цикл — четыре формы

Форма Синтаксис Аналог в других языках
Классическая for i := 0; i < n; i++ { } for в C, Java, JS
Только условие for условие { } while
Бесконечная for { } while (true)
По коллекции for i, v := range коллекция { } foreach, for…of

Ключевого слова while в Go нет — и оно не нужно. Круглых скобок вокруг заголовка цикла, как и у if, нет.

Классический for

Три части через ;: инициализация, условие, шаг.

go
package main

import "fmt"

func main() {
    for ep := 1; ep <= 3; ep++ {
        fmt.Println("Серия", ep)
    }
    // fmt.Println(ep) — ошибка: ep существует только внутри цикла
}
stdout // вывод программы
Серия 1
Серия 2
Серия 3

Переменная ep, объявленная в заголовке, живёт только внутри цикла.

Условие и бесконечный цикл

go
package main

import "fmt"

func main() {
    ep := 0
    for ep < 3 { // аналог while
        fmt.Print(ep, " ")
        ep++
    }
    fmt.Println()

    attempt := 0
    for { // бесконечный цикл
        attempt++
        if attempt > 3 {
            break // немедленный выход из цикла
        }
        fmt.Println("Попытка подключения", attempt)
    }
}
stdout // вывод программы
0 1 2
Попытка подключения 1
Попытка подключения 2
Попытка подключения 3

Цикл for ep < 3 крутится, пока условие истинно, — ep растёт, и рано или поздно цикл завершится. В бесконечном for { } выход обязателен: без break или return программа зависнет.

break и continue

  • break — моментально прерывает цикл и выходит наружу.
  • continue — пропускает остаток текущей итерации и переходит к следующей.
go
package main

import "fmt"

func main() {
    for i := 1; i <= 10; i++ {
        if i%3 == 0 {
            continue // пропускаем числа, кратные 3
        }
        fmt.Print(i, " ")
    }
    fmt.Println()
}
stdout // вывод программы
1 2 4 5 7 8 10

Если поменять условие на i%3 != 0, останутся только кратные трём: 3 6 9.

for range по слайсу

range — самый частый способ обойти коллекцию. Для слайса он возвращает два значения: индекс и элемент. Ненужное отбрасывают через _.

go
package main

import "fmt"

func main() {
    genres := []string{"Боевик", "Комедия", "Драма"}

    for i, g := range genres { // индекс и значение
        fmt.Println(i, g)
    }
    for _, g := range genres { // только значение
        fmt.Print(g, "; ")
    }
    fmt.Println()
    for i := range genres { // только индекс
        fmt.Print(i, " ")
    }
    fmt.Println()
}
stdout // вывод программы
0 Боевик
1 Комедия
2 Драма
Боевик; Комедия; Драма;
0 1 2

Чаще всего нужен второй вариант — значения без индексов.

range по строке

По строке range идёт не по байтам, а по символам: на каждом шаге он возвращает позицию байта, с которого начинается символ, и сам символ — rune. Кириллическая буква в UTF-8 занимает 2 байта, поэтому позиции «прыгают» через одну.

go
package main

import "fmt"

func main() {
    for pos, ch := range "Фильм" {
        fmt.Printf("позиция %d: %c (код %d)\n", pos, ch, ch)
    }
}
stdout // вывод программы
позиция 0: Ф (код 1060)
позиция 2: и (код 1080)
позиция 4: л (код 1083)
позиция 6: ь (код 1100)
позиция 8: м (код 1084)

range по мапе

Для мапы range возвращает ключ и значение. Порядок обхода не гарантирован: каждый запуск может выдать пары в другом порядке, и Go делает это намеренно.

go
package main

import "fmt"

func main() {
    ratings := map[string]float64{
        "Начало":        8.8,
        "Интерстеллар":  8.7,
        "Тёмный рыцарь": 9.0,
    }
    for film, score := range ratings {
        fmt.Printf("%s → %.1f\n", film, score)
    }
    // недетерминированный вывод
}

Пример вывода — у тебя порядок может отличаться:

text
Интерстеллар → 8.7
Тёмный рыцарь → 9.0
Начало → 8.8

Как обойти мапу в нужном порядке — в 10 — Мапы → Обход и порядок.

Вложенные циклы

Цикл внутри цикла нужен для таблиц и матриц: внутренний проходит целиком на каждом шаге внешнего.

go
package main

import "fmt"

func main() {
    for row := 1; row <= 2; row++ {
        for seat := 1; seat <= 3; seat++ {
            fmt.Printf("ряд %d, место %d\n", row, seat)
        }
    }
}
stdout // вывод программы
ряд 1, место 1
ряд 1, место 2
ряд 1, место 3
ряд 2, место 1
ряд 2, место 2
ряд 2, место 3

Несколько переменных в цикле

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

go
package main

import "fmt"

func main() {
    seq := []string{"A", "B", "C", "D", "E"}
    for lo, hi := 0, len(seq)-1; lo < hi; lo, hi = lo+1, hi-1 {
        seq[lo], seq[hi] = seq[hi], seq[lo]
    }
    fmt.Println(seq)
}
stdout // вывод программы
[E D C B A]

Практика

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

  1. Создай слайс из четырёх фильмов и слайс из четырёх времён сеансов: 10:00, 13:00, 16:00, 19:00.
  2. Залов три. Через вложенные циклы выведи расписание залов 1, 2 и 3.
  3. Добавь поиск: перебери расписание и найди, в каком зале и во сколько идёт «Начало».
решениеЭталонное решение
go
package main

import "fmt"

func main() {
    films := []string{"Дюна", "Начало", "Матрица", "Интерстеллар"}
    times := []string{"10:00", "13:00", "16:00", "19:00"}
    const halls = 3

    for hall := 1; hall <= halls; hall++ {
        fmt.Printf("Зал %d:\n", hall)
        for slot, t := range times {
            film := films[(hall+slot)%len(films)] // сдвиг, чтобы залы не повторялись
            fmt.Printf("  %s — %s\n", t, film)
        }
    }

    fmt.Println("Где идёт «Начало»:")
    for hall := 1; hall <= halls; hall++ {
        for slot, t := range times {
            if films[(hall+slot)%len(films)] == "Начало" {
                fmt.Printf("  зал %d в %s\n", hall, t)
            }
        }
    }
}
stdout // вывод программы
Зал 1:
  10:00 — Начало
  13:00 — Матрица
  16:00 — Интерстеллар
  19:00 — Дюна
Зал 2:
  10:00 — Матрица
  13:00 — Интерстеллар
  16:00 — Дюна
  19:00 — Начало
Зал 3:
  10:00 — Интерстеллар
  13:00 — Дюна
  16:00 — Начало
  19:00 — Матрица
Где идёт «Начало»:
  зал 1 в 10:00
  зал 2 в 19:00
  зал 3 в 16:00

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

go
package main

import "fmt"

func main() {
    for i := 0; i < 3; i++ {
        for j := 0; j < 3; j++ {
            if j == 1 {
                break
            }
            fmt.Printf("%d%d ", i, j)
        }
    }
    fmt.Println()
}
самопроверкаОтвет
text
00 10 20

break прерывает только внутренний цикл: для каждого i успевает напечататься лишь пара с j == 0, а внешний цикл продолжается.

Проверь себя

вопросСколько циклов в Go и как написать аналог while?

Один — for. Аналог while: for условие { … }.

вопросЧем break отличается от continue?

break завершает цикл целиком, continue пропускает остаток текущей итерации и переходит к следующей.

вопросЧто возвращает range для слайса и как взять только значения?

Индекс и элемент. Только значения: for _, v := range s.

вопросПочему при range по строке «Фильм» позиции идут 0, 2, 4, 6, 8?

range возвращает позицию байта, с которого начинается символ, а кириллическая буква в UTF-8 занимает 2 байта.

вопросВ каком порядке range обходит мапу?

Порядок не гарантирован и меняется от запуска к запуску — Go делает это специально.

вопросКак выйти сразу из двух вложенных циклов?

Пометить внешний цикл меткой и написать break метка — или вынести циклы в функцию и сделать return.


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

  • 🔁 Один for на всё: классический, «while», бесконечный и range.
  • ⏭️ break выходит из ближайшего цикла, continue переходит к следующей итерации, метка — выход из вложенных.
  • 📚 range по слайсу даёт индекс и значение, лишнее отбрасывается через _.
  • 🔤 range по строке идёт по символам, но позиции — в байтах.
  • 🎲 Порядок обхода мапы случайный — на него нельзя полагаться.

Chapter goals

  • Write all four forms of for.
  • Control a loop with break and continue.
  • Walk slices, strings, and maps with range and understand what it returns.
  • Write nested loops and loops with several variables.

One loop — four forms

Form Syntax Analogue in other languages
Classic for i := 0; i < n; i++ { } for in C, Java, JS
Condition only for condition { } while
Infinite for { } while (true)
Over a collection for i, v := range collection { } foreach, for…of

There's no while keyword in Go — and none is needed. As with if, the loop header takes no parentheses.

The classic for

Three parts separated by ;: initialization, condition, step.

go
package main

import "fmt"

func main() {
    for ep := 1; ep <= 3; ep++ {
        fmt.Println("Episode", ep)
    }
    // fmt.Println(ep) — error: ep exists only inside the loop
}
stdout // program output
Episode 1
Episode 2
Episode 3

The ep variable declared in the header lives only inside the loop.

Condition-only and infinite loops

go
package main

import "fmt"

func main() {
    ep := 0
    for ep < 3 { // the while analogue
        fmt.Print(ep, " ")
        ep++
    }
    fmt.Println()

    attempt := 0
    for { // infinite loop
        attempt++
        if attempt > 3 {
            break // leave the loop immediately
        }
        fmt.Println("Connection attempt", attempt)
    }
}
stdout // program output
0 1 2
Connection attempt 1
Connection attempt 2
Connection attempt 3

The for ep < 3 loop spins while the condition is true — ep grows, and sooner or later the loop ends. An infinite for { } must have an exit: without break or return the program hangs.

break and continue

  • break — instantly interrupts the loop and breaks out of it.
  • continue — skips the rest of the current iteration and jumps to the next one.
go
package main

import "fmt"

func main() {
    for i := 1; i <= 10; i++ {
        if i%3 == 0 {
            continue // skip the multiples of 3
        }
        fmt.Print(i, " ")
    }
    fmt.Println()
}
stdout // program output
1 2 4 5 7 8 10

Change the condition to i%3 != 0 and only the multiples of three remain: 3 6 9.

for range over a slice

range is the most common way to walk a collection. For a slice it returns two values: the index and the element. The unneeded one is discarded with _.

go
package main

import "fmt"

func main() {
    genres := []string{"Action", "Comedy", "Drama"}

    for i, g := range genres { // index and value
        fmt.Println(i, g)
    }
    for _, g := range genres { // value only
        fmt.Print(g, "; ")
    }
    fmt.Println()
    for i := range genres { // index only
        fmt.Print(i, " ")
    }
    fmt.Println()
}
stdout // program output
0 Action
1 Comedy
2 Drama
Action; Comedy; Drama;
0 1 2

Most often you want the second variant — values without indexes.

range over a string

Over a string, range steps not by bytes but by characters: on each step it returns the byte position where the character starts, plus the character itself — a rune. A Cyrillic letter takes 2 bytes in UTF-8, so the positions jump by two.

go
package main

import "fmt"

func main() {
    for pos, ch := range "Фильм" {
        fmt.Printf("position %d: %c (code %d)\n", pos, ch, ch)
    }
}
stdout // program output
position 0: Ф (code 1060)
position 2: и (code 1080)
position 4: л (code 1083)
position 6: ь (code 1100)
position 8: м (code 1084)

range over a map

For a map, range returns the key and the value. The iteration order is not guaranteed: every run may produce the pairs in a different order, and Go does that on purpose.

go
package main

import "fmt"

func main() {
    ratings := map[string]float64{
        "Inception":       8.8,
        "Interstellar":    8.7,
        "The Dark Knight": 9.0,
    }
    for film, score := range ratings {
        fmt.Printf("%s → %.1f\n", film, score)
    }
    // non-deterministic output
}

Example output — your order may differ:

text
Interstellar → 8.7
The Dark Knight → 9.0
Inception → 8.8

How to walk a map in a specific order — in 10 — Maps → Iteration and order.

Nested loops

A loop inside a loop is what tables and matrices need: the inner one runs to completion on every step of the outer one.

go
package main

import "fmt"

func main() {
    for row := 1; row <= 2; row++ {
        for seat := 1; seat <= 3; seat++ {
            fmt.Printf("row %d, seat %d\n", row, seat)
        }
    }
}
stdout // program output
row 1, seat 1
row 1, seat 2
row 1, seat 3
row 2, seat 1
row 2, seat 2
row 2, seat 3

Several variables in one loop

The for header can declare and update several variables at once. A classic technique is two pointers moving toward each other: that's how you reverse an array or find pairs at both ends.

go
package main

import "fmt"

func main() {
    seq := []string{"A", "B", "C", "D", "E"}
    for lo, hi := 0, len(seq)-1; lo < hi; lo, hi = lo+1, hi-1 {
        seq[lo], seq[hi] = seq[hi], seq[lo]
    }
    fmt.Println(seq)
}
stdout // program output
[E D C B A]

Practice

Homework: the GoFlix cinema schedule

  1. Create a slice of four movies and a slice of four showtimes: 10:00, 13:00, 16:00, 19:00.
  2. There are three halls. With nested loops, print the schedules of halls 1, 2, and 3.
  3. Add a search: walk the schedule and find which hall and at what time Inception is playing.
solution
go
package main

import "fmt"

func main() {
    films := []string{"Dune", "Inception", "The Matrix", "Interstellar"}
    times := []string{"10:00", "13:00", "16:00", "19:00"}
    const halls = 3

    for hall := 1; hall <= halls; hall++ {
        fmt.Printf("Hall %d:\n", hall)
        for slot, t := range times {
            film := films[(hall+slot)%len(films)] // the shift keeps halls from repeating
            fmt.Printf("  %s — %s\n", t, film)
        }
    }

    fmt.Println("Where Inception is playing:")
    for hall := 1; hall <= halls; hall++ {
        for slot, t := range times {
            if films[(hall+slot)%len(films)] == "Inception" {
                fmt.Printf("  hall %d at %s\n", hall, t)
            }
        }
    }
}
stdout // program output
Hall 1:
  10:00 — Inception
  13:00 — The Matrix
  16:00 — Interstellar
  19:00 — Dune
Hall 2:
  10:00 — The Matrix
  13:00 — Interstellar
  16:00 — Dune
  19:00 — Inception
Hall 3:
  10:00 — Interstellar
  13:00 — Dune
  16:00 — Inception
  19:00 — The Matrix
Where Inception is playing:
  hall 1 at 10:00
  hall 2 at 19:00
  hall 3 at 16:00

Exercise: predict the output

go
package main

import "fmt"

func main() {
    for i := 0; i < 3; i++ {
        for j := 0; j < 3; j++ {
            if j == 1 {
                break
            }
            fmt.Printf("%d%d ", i, j)
        }
    }
    fmt.Println()
}
self-check
text
00 10 20

break interrupts only the inner loop: for every i only the pair with j == 0 gets printed, while the outer loop keeps going.

Check yourself

questionHow many loops does Go have, and how do you write a while?

One — for. The while analogue: for condition { … }.

questionHow is break different from continue?

break ends the whole loop; continue skips the rest of the current iteration and jumps to the next one.

questionWhat does range return for a slice, and how do you get only the values?

The index and the element. Values only: for _, v := range s.

questionWhy do the positions go 0, 2, 4, 6, 8 when ranging over the string "Фильм"?

range returns the byte position where the character starts, and a Cyrillic letter takes 2 bytes in UTF-8.

questionIn what order does range walk a map?

The order isn't guaranteed and changes from run to run — Go does it on purpose.

questionHow do you leave two nested loops at once?

Mark the outer loop with a label and write break label — or move the loops into a function and return.


Key takeaways

  • 🔁 One for for everything: classic, "while", infinite, and range.
  • ⏭️ break leaves the nearest loop, continue jumps to the next iteration, a label breaks out of nesting.
  • 📚 range over a slice gives the index and the value; the extra one is discarded with _.
  • 🔤 range over a string walks characters, but the positions are in bytes.
  • 🎲 Map iteration order is random — never rely on it.
// related topics and cheatsheets