Part 2. Language BasicsLesson 05# go# basics# functions

Functions

scopes and shadowing, pass by value, multiple return values, exports

Цели главы

  • Понимать области видимости: пакет, функция, блок — и ловушку shadowing.
  • Объявлять функции с параметрами и одним или несколькими результатами.
  • Понимать передачу по значению.
  • Хранить функции в переменных.
  • Различать экспортируемые и приватные имена.

Область видимости

Сначала — где «живут» переменные и кто их видит.

Уровень Где объявлена Кто видит
Пакет («глобальная») вне функций все функции пакета
Локальная внутри функции только эта функция, с момента объявления
Блочная внутри { … } — блока, if, for только до закрывающей скобки блока

Локальная переменная рождается при входе в функцию и исчезает при выходе — снаружи её нет. Область видимости привязана к фигурным скобкам.

Shadowing — затенение

Если внутри блока объявить через := переменную с тем же именем, что и снаружи, появится новая переменная, которая затенит внешнюю. Внешняя останется нетронутой. Без двоеточия, через =, меняется именно внешняя.

go
package main

import "fmt"

var totalFilms = 0 // переменная пакета: видна во всех функциях

func addFilm() {
    totalFilms++
}

func main() {
    addFilm()
    addFilm()
    fmt.Println("фильмов:", totalFilms)

    price := 100
    {
        price := 200 // новая переменная, затеняет внешнюю
        fmt.Println("внутри блока:", price)
    }
    fmt.Println("после блока:", price)

    {
        price = 300 // без двоеточия — меняем внешнюю
    }
    fmt.Println("после присваивания:", price)
}
stdout // вывод программы
фильмов: 2
внутри блока: 200
после блока: 100
после присваивания: 300

Синтаксис функции

text
func имя(параметры) результаты { тело }

Параметры и результаты необязательны: func addFilm() { … } — функция без того и другого. Параметры одного типа можно перечислить через запятую.

go
package main

import "fmt"

// ticketPrice: два параметра одного типа записаны через запятую.
func ticketPrice(base, seats int) int {
    return base * seats
}

// splitDuration возвращает сразу два значения.
func splitDuration(minutes int) (int, int) {
    return minutes / 60, minutes % 60
}

func main() {
    fmt.Println(ticketPrice(450, 3))

    h, m := splitDuration(169)
    fmt.Printf("%d ч %d мин\n", h, m)

    _, rest := splitDuration(95) // ненужное значение отбрасываем через _
    fmt.Println(rest)
}
stdout // вывод программы
1350
2 ч 49 мин
35
  • Несколько результатов в Go используются постоянно — самый частый пример значение, ошибка из 13 — Обработка ошибок.
  • Результаты можно сразу разложить по переменным и тут же поменять местами: a, b = b, a.

Передача по значению

В Go аргументы передаются по значению: функция получает копию. Меняй копию сколько угодно — оригинал не изменится.

go
package main

import "fmt"

func addBonus(rating float64) float64 {
    rating += 0.5 // меняем копию
    return rating
}

func main() {
    rating := 8.0
    boosted := addBonus(rating)
    fmt.Println(rating, boosted)
}
stdout // вывод программы
8 8.5

Чтобы функция меняла оригинал, ей передают адрес переменной — об этом 11 — Указатели.

Функции как значения

Функции в Go — значения первого класса (first-class functions): их можно хранить в переменных и передавать в другие функции. Тип переменной описывает сигнатуру: func(int, int) int — функция с двумя int-параметрами и int-результатом.

go
package main

import "fmt"

func ticketPrice(base, seats int) int {
    return base * seats
}

func withService(base, seats int) int {
    return base*seats + 99
}

func main() {
    var calc func(int, int) int // переменная, тип которой — функция
    calc = ticketPrice
    fmt.Println(calc(450, 2))

    calc = withService
    fmt.Println(calc(450, 2))
}
stdout // вывод программы
900
999

Этот механизм лежит в основе callbacks и замыканий — 12 — Продвинутые функции.

Экспорт — заглавная буква

Правило одно на весь язык: имя с заглавной буквы экспортируется — видно из других пакетов; со строчной — приватно для своего пакета. Касается функций, переменных, констант, типов и полей структур.

Практика

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

Напиши три функции и вызови их в main, выведя результаты:

  1. ticketPrice — принимает базовую цену и два bool: вечерний ли сеанс и выходной ли день. Вечером +50 рублей, в выходной +100. Возвращает итоговую цену.
  2. formatReceipt — принимает название фильма, количество билетов и цену одного. Возвращает два значения: текст чека (string) и итоговую сумму (int).
  3. isAllowed — принимает возраст зрителя и возрастной рейтинг фильма, возвращает bool: можно ли смотреть.
решениеЭталонное решение
go
package main

import "fmt"

// ticketPrice возвращает цену билета с надбавками за вечер и выходной.
func ticketPrice(base int, isEvening, isWeekend bool) int {
    price := base
    if isEvening {
        price += 50
    }
    if isWeekend {
        price += 100
    }
    return price
}

// formatReceipt возвращает текст чека и итоговую сумму.
func formatReceipt(title string, count, price int) (string, int) {
    total := count * price
    return fmt.Sprintf("%s: %d × %d = %d руб.", title, count, price, total), total
}

// isAllowed сообщает, можно ли зрителю смотреть фильм с этим рейтингом.
func isAllowed(age, ageRating int) bool {
    return age >= ageRating
}

func main() {
    price := ticketPrice(400, true, true)
    receipt, total := formatReceipt("Дюна", 2, price)
    fmt.Println(receipt)
    fmt.Println("К оплате:", total)
    fmt.Println("Подросток 15 лет на 18+:", isAllowed(15, 18))
}
stdout // вывод программы
Дюна: 2 × 550 = 1100 руб.
К оплате: 1100
Подросток 15 лет на 18+: false

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

go
package main

import "fmt"

var count = 10

func inc(n int) {
    n++
    count++
}

func main() {
    n := 1
    inc(n)
    count := 100
    count++
    fmt.Println(n, count)
}
самопроверкаОтвет
text
1 101

inc увеличила свою копию n, поэтому в main осталось 1. Переменную пакета count функция действительно увеличила до 11, но в main её затенила локальная count := 100, и печатается локальная — 101.

Проверь себя

вопросГде видна переменная, объявленная вне функций?

Во всех функциях и всех файлах своего пакета. С заглавной буквы — ещё и в других пакетах.

вопросЧто такое shadowing и чем он опасен?

Объявление через := во вложенном блоке переменной с тем же именем, что и снаружи. Создаётся новая переменная, внешняя не меняется — легко решить, что изменил одно, а изменил другое.

вопросЧто значит «аргументы передаются по значению»?

Функция получает копию аргумента. Изменения копии не видны вызывающему коду; чтобы менять оригинал, передают указатель.

вопросКак вернуть из функции два значения и как отбросить одно из них?

Объявить результаты в скобках: func f() (int, int), вернуть return a, b. Ненужное отбрасывают через _: _, rest := f().

вопросКакой тип у переменной, в которую можно положить func ticketPrice(a, b int) int?

func(int, int) int.

вопросКак сделать функцию недоступной из других пакетов?

Назвать её со строчной буквы.


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

  • 🎯 Область видимости задают фигурные скобки: пакет → функция → блок.
  • 👥 := во вложенном блоке создаёт новую переменную и затеняет внешнюю — проверяй, где :=, а где =.
  • 📋 Аргументы передаются по значению: функция работает с копией.
  • 🔀 Функция может вернуть несколько значений; ненужные отбрасываются через _.
  • 🧩 Функции — значения: их хранят в переменных и передают в другие функции.
  • 🔠 Заглавная буква — публичное имя, строчная — приватное для пакета.

Chapter goals

  • Understand scopes: package, function, block — and the shadowing trap.
  • Declare functions with parameters and one or several results.
  • Understand pass by value.
  • Store functions in variables.
  • Tell exported names from private ones.

Scope

First — where variables "live" and who can see them.

Level Declared where Who sees it
Package ("global") outside functions all functions of the package
Local inside a function only that function, from the declaration on
Block inside { … } — a block, if, for only until the block's closing brace

A local variable is born when the function starts and disappears when it returns — outside it doesn't exist. Scope follows the curly braces.

Shadowing

If you declare a variable with := inside a block under the same name as one outside, a new variable appears and shadows the outer one. The outer one stays untouched. Without the colon, using =, you change exactly the outer one.

go
package main

import "fmt"

var totalFilms = 0 // package variable: visible in all functions

func addFilm() {
    totalFilms++
}

func main() {
    addFilm()
    addFilm()
    fmt.Println("films:", totalFilms)

    price := 100
    {
        price := 200 // a new variable, shadows the outer one
        fmt.Println("inside block:", price)
    }
    fmt.Println("after the block:", price)

    {
        price = 300 // no colon — changing the outer one
    }
    fmt.Println("after assignment:", price)
}
stdout // program output
films: 2
inside block: 200
after the block: 100
after assignment: 300

Function syntax

text
func name(parameters) results { body }

Parameters and results are optional: func addFilm() { … } is a function with neither. Parameters of the same type can be listed comma-separated.

go
package main

import "fmt"

// ticketPrice: two parameters of one type, written comma-separated.
func ticketPrice(base, seats int) int {
    return base * seats
}

// splitDuration returns two values at once.
func splitDuration(minutes int) (int, int) {
    return minutes / 60, minutes % 60
}

func main() {
    fmt.Println(ticketPrice(450, 3))

    h, m := splitDuration(169)
    fmt.Printf("%d h %d min\n", h, m)

    _, rest := splitDuration(95) // the unneeded value is discarded with _
    fmt.Println(rest)
}
stdout // program output
1350
2 h 49 min
35
  • Multiple results are used everywhere in Go — the most common example is value, error from 13 — Error handling.
  • Results can be unpacked into variables right away and even swapped on the spot: a, b = b, a.

Pass by value

In Go, arguments are passed by value: the function receives a copy. Change the copy as much as you like — the original won't budge.

go
package main

import "fmt"

func addBonus(rating float64) float64 {
    rating += 0.5 // changing the copy
    return rating
}

func main() {
    rating := 8.0
    boosted := addBonus(rating)
    fmt.Println(rating, boosted)
}
stdout // program output
8 8.5

For a function to change the original, pass it the variable's address — that's 11 — Pointers.

Functions as values

Functions in Go are first-class values (first-class functions): they can be stored in variables and passed to other functions. A variable's type describes the signature: func(int, int) int — a function with two int parameters and an int result.

go
package main

import "fmt"

func ticketPrice(base, seats int) int {
    return base * seats
}

func withService(base, seats int) int {
    return base*seats + 99
}

func main() {
    var calc func(int, int) int // a variable whose type is a function
    calc = ticketPrice
    fmt.Println(calc(450, 2))

    calc = withService
    fmt.Println(calc(450, 2))
}
stdout // program output
900
999

This mechanism underlies callbacks and closures — 12 — Advanced functions.

Exporting: capitalization

One rule for the whole language: a name starting with a capital letter is exported — visible from other packages; a lowercase one is private to its own package. It applies to functions, variables, constants, types, and struct fields.

Practice

Homework: the GoFlix box office

Write three functions and call them from main, printing the results:

  1. ticketPrice — takes a base price and two bools: whether the show is in the evening and whether it's a weekend day. Evenings add 50 rubles, weekends add 100. Returns the final price.
  2. formatReceipt — takes a movie title, the number of tickets, and the price of one. Returns two values: the receipt text (string) and the total (int).
  3. isAllowed — takes the viewer's age and the movie's age rating, returns a bool: whether they may watch.
solution
go
package main

import "fmt"

// ticketPrice returns the ticket price with evening and weekend surcharges.
func ticketPrice(base int, isEvening, isWeekend bool) int {
    price := base
    if isEvening {
        price += 50
    }
    if isWeekend {
        price += 100
    }
    return price
}

// formatReceipt returns the receipt text and the total.
func formatReceipt(title string, count, price int) (string, int) {
    total := count * price
    return fmt.Sprintf("%s: %d × %d = %d RUB.", title, count, price, total), total
}

// isAllowed reports whether the viewer may watch a movie with this rating.
func isAllowed(age, ageRating int) bool {
    return age >= ageRating
}

func main() {
    price := ticketPrice(400, true, true)
    receipt, total := formatReceipt("Dune", 2, price)
    fmt.Println(receipt)
    fmt.Println("To pay:", total)
    fmt.Println("A 15-year-old at an 18+ movie:", isAllowed(15, 18))
}
stdout // program output
Dune: 2 × 550 = 1100 RUB.
To pay: 1100
A 15-year-old at an 18+ movie: false

Exercise: predict the output

go
package main

import "fmt"

var count = 10

func inc(n int) {
    n++
    count++
}

func main() {
    n := 1
    inc(n)
    count := 100
    count++
    fmt.Println(n, count)
}
self-check
text
1 101

inc incremented its own copy of n, so main still sees 1. The function really did increment the package variable count to 11, but in main it's shadowed by the local count := 100, and the local one — 101 — is what gets printed.

Check yourself

questionWhere is a variable declared outside functions visible?

In all functions and all files of its package. With a capital first letter — in other packages too.

questionWhat is shadowing and why is it dangerous?

Declaring a variable with := in a nested block under the same name as one outside. A new variable is created and the outer one doesn't change — it's easy to think you changed one thing while you changed another.

questionWhat does "arguments are passed by value" mean?

The function receives a copy of the argument. Changes to the copy aren't visible to the caller; to change the original, pass a pointer.

questionHow do you return two values from a function, and how do you discard one of them?

Declare the results in parentheses: func f() (int, int), return them with return a, b. The unneeded one is discarded with _: _, rest := f().

questionWhat's the type of a variable that can hold func ticketPrice(a, b int) int?

func(int, int) int.

questionHow do you make a function inaccessible from other packages?

Start its name with a lowercase letter.


Key takeaways

  • 🎯 Scope is set by curly braces: package → function → block.
  • 👥 := in a nested block creates a new variable and shadows the outer one — check where you wrote := and where =.
  • 📋 Arguments are passed by value: the function works on a copy.
  • 🔀 A function can return several values; the unneeded ones are discarded with _.
  • 🧩 Functions are values: they're stored in variables and passed to other functions.
  • 🔠 A capital letter is a public name, a lowercase one is private to the package.
// related topics and cheatsheets