Part 3. Data & MemoryLesson 11# go# pointers# memory# interview

Pointers

& and *, mutating the original, nil, optional values, escape analysis

Цели главы

  • Понимать операторы & и * и тип указателя.
  • Менять оригинальную переменную из функции.
  • Работать с указателями на структуры и new.
  • Безопасно обращаться с nil и использовать указатель как опциональное значение.
  • Знать, почему возврат указателя на локальную переменную безопасен.

Зачем указатели

Функции в Go получают копию аргумента (05 — Функции → Передача по значению). Это безопасно, но что, если нужно изменить оригинал — например, обновить рейтинг фильма из функции? Функция работает с копией, и снаружи изменения не видны. Указатели решают эту проблему.

& и *

Указатель — адрес переменной в памяти. Два оператора:

  • & (амперсанд) — взять адрес переменной;
  • * (звёздочка) — разыменовать указатель: обратиться к значению по адресу.

У указателя есть свой тип: *int — указатель на int. Положить в такую переменную адрес string не получится — код не скомпилируется.

go
package main

import "fmt"

func main() {
    movieID := 42
    ptr := &movieID // ptr хранит адрес movieID

    fmt.Println("movieID =", movieID)
    fmt.Println("*ptr =", *ptr) // значение по адресу
    fmt.Printf("тип ptr: %T\n", ptr)
    fmt.Println("адрес:", ptr)
    // недетерминированный вывод: адрес меняется от запуска к запуску
}

Пример вывода — адрес у тебя будет другим:

text
movieID = 42
*ptr = 42
тип ptr: *int
адрес: 0x14000110018

Аналогия: указатель — адрес дома. & — записать адрес на бумажке или продиктовать его. * — пойти по адресу и посмотреть на сам дом.

Изменение через указатель

Разыменуй указатель и запиши новое значение — изменится оригинальная переменная, ведь обе смотрят на одну область памяти.

go
package main

import "fmt"

func main() {
    viewCount := 1000
    viewPtr := &viewCount
    *viewPtr = 5000 // «по адресу из viewPtr запиши 5000»
    fmt.Println(viewCount)
}
stdout // вывод программы
5000

Указатели в параметрах функций

Без указателя функция получает копию и меняет копию — оригинал цел. С указателем функция получает адрес и меняет оригинал.

go
package main

import "fmt"

// tryChangeRating получает копию — оригинал не изменится.
func tryChangeRating(r float64) {
    r = 10.0
}

// changeRating получает адрес и меняет оригинал.
func changeRating(r *float64, newRating float64) {
    *r = newRating
}

func main() {
    rating := 8.0
    tryChangeRating(rating)
    fmt.Println("после tryChangeRating:", rating)

    changeRating(&rating, 9.5)
    fmt.Println("после changeRating:", rating)
}
stdout // вывод программы
после tryChangeRating: 8
после changeRating: 9.5

Указатели на структуры

Указатели особенно полезны со структурами: большую структуру дорого копировать, поэтому её передают по указателю. При этом в Go есть автоматическое разыменование: вместо (*p).Views пишут просто p.Views — Go сам подставит *. Подробно структуры — в 15 — Структуры.

go
package main

import "fmt"

type Movie struct {
    Title  string
    Rating float64
    Views  int
}

func addView(m *Movie) {
    m.Views++ // то же, что (*m).Views++ — Go разыменует сам
}

func main() {
    film := Movie{Title: "Довод", Rating: 7.8, Views: 50000}
    addView(&film)
    addView(&film)
    fmt.Println(film.Views)

    p := &film
    p.Rating = 8.0
    fmt.Println(film.Rating, (*p).Title, p.Title)
}
stdout // вывод программы
50002
8 Довод Довод

new

Встроенная функция new(T) создаёт переменную типа T с нулевым значением и возвращает указатель на неё. Используется нечасто: обычно проще взять адрес через &.

go
package main

import "fmt"

func main() {
    numPtr := new(int) // *int, указывает на 0
    fmt.Println(*numPtr)
    *numPtr = 999
    fmt.Println(*numPtr)

    rating := 0.0
    same := &rating // то же самое, но привычнее
    *same = 8.5
    fmt.Println(rating)
}
stdout // вывод программы
0
999
8.5

nil-указатель

Нулевое значение указателя — nil: указатель никуда не указывает. Разыменовать его — паника.

go
package main

import "fmt"

func main() {
    var p *int
    fmt.Println(*p) // ожидается panic
}
text
panic: runtime error: invalid memory address or nil pointer dereference

Поэтому перед разыменованием указатель проверяют:

go
package main

import "fmt"

func main() {
    var p *int
    fmt.Println(p == nil, p)
    if p != nil {
        fmt.Println(*p) // без проверки здесь была бы паника
    }
}
stdout // вывод программы
true <nil>

Указатель как опциональное значение

Полезный паттерн: nil означает «значение не задано», не-nil — «задано». Так различают две ситуации, которые обычный float64 не различает: «пользователь не поставил оценку» и «поставил 0».

go
package main

import "fmt"

func printUserRating(name string, rating *float64) {
    if rating == nil {
        fmt.Printf("%s: не оценил\n", name)
        return
    }
    fmt.Printf("%s: %.1f\n", name, *rating)
}

func main() {
    score := 8.5
    zero := 0.0
    printUserRating("Алексей", &score)
    printUserRating("Мария", nil)
    printUserRating("Олег", &zero) // поставил 0 — это не то же самое, что «не оценил»
}
stdout // вывод программы
Алексей: 8.5
Мария: не оценил
Олег: 0.0

Возврат указателя на локальную переменную

В C и C++ это опасно: локальная переменная умирает при выходе из функции. В Go — безопасно: компилятор видит, что на переменную ещё ссылаются, и размещает её не на стеке, а в куче. Там она живёт, пока на неё есть указатель, а потом её уберёт сборщик мусора.

go
package main

import "fmt"

type Movie struct {
    Title  string
    Rating float64
}

func createMovie(title string, rating float64) *Movie {
    m := Movie{Title: title, Rating: rating}
    return &m // безопасно: компилятор перенесёт m в кучу
}

func main() {
    film := createMovie("Оппенгеймер", 8.5)
    fmt.Println(*film)
    fmt.Printf("%+v\n", film)
}
stdout // вывод программы
{Оппенгеймер 8.5}
&{Title:Оппенгеймер Rating:8.5}

Ссылочные типы

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

go
package main

import "fmt"

func modifySlice(s []string) {
    if len(s) > 0 {
        s[0] = "ИЗМЕНЁН"
    }
}

func modifyMap(m map[string]float64) {
    m["Гладиатор"] = 8.6
}

func main() {
    films := []string{"A", "B", "C"}
    modifySlice(films)
    fmt.Println(films)

    scores := map[string]float64{"Дюна": 8.1}
    modifyMap(scores)
    fmt.Println(scores)
}
stdout // вывод программы
[ИЗМЕНЁН B C]
map[Гладиатор:8.6 Дюна:8.1]

Итоги

Зачем нужны указатели:

  1. Менять оригинальную переменную из функции.
  2. Не копировать большие структуры.
  3. Выражать опциональные значения: nil — не задано.

Правила работы:

  1. Проверяй указатель на nil перед разыменованием.
  2. Go сам разыменовывает указатель на структуру при обращении к полям.
  3. Вернуть из функции указатель на локальную переменную — безопасно.
  4. Слайсы и мапы уже ссылочные — указатель на них обычно не нужен.

Практика

  1. Напиши swap(a, b *int), которая меняет местами значения двух переменных.
  2. Напиши applyDiscount(priceKopecks *int, percent int), которая уменьшает цену на процент. Вызов с nil не должен паниковать.
  3. Напиши averageRated(ratings []*float64) (float64, int) — средняя оценка и число оценок; nil в слайсе означает «не оценил» и пропускается.
решениеЭталонное решение
go
package main

import "fmt"

func swap(a, b *int) {
    *a, *b = *b, *a
}

func applyDiscount(priceKopecks *int, percent int) {
    if priceKopecks == nil {
        return
    }
    *priceKopecks = *priceKopecks * (100 - percent) / 100
}

func averageRated(ratings []*float64) (float64, int) {
    sum, count := 0.0, 0
    for _, r := range ratings {
        if r == nil {
            continue // пользователь не оценил
        }
        sum += *r
        count++
    }
    if count == 0 {
        return 0, 0
    }
    return sum / float64(count), count
}

func main() {
    x, y := 1, 2
    swap(&x, &y)
    fmt.Println(x, y)

    price := 99_900
    applyDiscount(&price, 15)
    applyDiscount(nil, 15) // не паникует
    fmt.Println(price)

    a, b := 8.0, 9.0
    avg, n := averageRated([]*float64{&a, nil, &b, nil})
    fmt.Printf("%.1f по %d оценкам\n", avg, n)
}
stdout // вывод программы
2 1
84915
8.5 по 2 оценкам

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

go
package main

import "fmt"

func update(p *int) {
    *p = 10
    p = nil
}

func main() {
    n := 1
    p := &n
    update(p)
    fmt.Println(n, p == nil)
}
самопроверкаОтвет
text
10 false

Указатель тоже передаётся по значению: функция получает копию адреса. Запись через *p меняет n, а p = nil обнуляет только локальную копию указателя.

Проверь себя

вопросЧто делают операторы & и *?

&x — берёт адрес переменной x. *p — разыменовывает указатель p: читает или меняет значение по адресу.

вопросКакой тип у &x, если x — float64?

*float64.

вопросКак функции изменить переменную вызывающего кода?

Принять указатель (func f(p *T)), а вызывающий передаёт адрес: f(&x). Внутри — *p = ….

вопросЧто будет при разыменовании nil-указателя?

Паника: invalid memory address or nil pointer dereference. Перед разыменованием проверяют p != nil.

вопросБезопасно ли вернуть из функции указатель на локальную переменную?

Да. Escape analysis заметит, что переменная «убегает» из функции, и разместит её в куче; GC удалит её, когда указателей не останется.

вопросНужно ли передавать мапу в функцию по указателю, чтобы добавить элемент?

Нет. Мапа содержит указатель на данные внутри, изменения видны снаружи и так.

вопросЗачем использовать *float64 вместо float64 для оценки пользователя?

Чтобы отличать «оценки нет» (nil) от «оценка 0».


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

  • 📍 Указатель — адрес: & берёт адрес, * читает и меняет значение по адресу.
  • ✏️ Через указатель функция меняет оригинал и не копирует большие структуры.
  • 🪄 К полям структуры через указатель обращаются просто через точку — Go разыменует сам.
  • 💥 nil-указатель разыменовывать нельзя — проверяй перед использованием.
  • 🏠 Указатель на локальную переменную можно вернуть: escape analysis перенесёт её в кучу.
  • 🔗 Слайсы, мапы и каналы уже ссылочные — указатель на них обычно не нужен.

Chapter goals

  • Understand the & and * operators and the pointer type.
  • Modify the caller's variable from a function.
  • Work with pointers to structs and with new.
  • Handle nil safely and use a pointer as an optional value.
  • Know why returning a pointer to a local variable is safe.

Why pointers

Functions in Go receive a copy of the argument (05 — Functions → Pass by value). That's safe, but what if you need to modify the original — say, update a movie's rating from a function? The function works on a copy, and the change isn't visible outside. Pointers solve this problem.

& and *

A pointer is a variable's address in memory. Two operators:

  • & (ampersand) — take the address of a variable;
  • * (asterisk) — dereference a pointer: access the value at the address.

A pointer has its own type: *int is a pointer to an int. You can't put the address of a string into such a variable — the code won't compile.

go
package main

import "fmt"

func main() {
    movieID := 42
    ptr := &movieID // ptr holds the address of movieID

    fmt.Println("movieID =", movieID)
    fmt.Println("*ptr =", *ptr) // the value at the address
    fmt.Printf("ptr type: %T\n", ptr)
    fmt.Println("address:", ptr)
    // non-deterministic output: the address changes from run to run
}

Sample output — your address will be different:

text
movieID = 42
*ptr = 42
ptr type: *int
address: 0x14000110018

Analogy: a pointer is a house address. & — write the address on a note or dictate it. * — walk to the address and look at the house itself.

Modifying through a pointer

Dereference the pointer and write a new value — the original variable changes, because both refer to the same memory.

go
package main

import "fmt"

func main() {
    viewCount := 1000
    viewPtr := &viewCount
    *viewPtr = 5000 // «write 5000 at the address in viewPtr»
    fmt.Println(viewCount)
}
stdout // program output
5000

Pointers in function parameters

Without a pointer the function gets a copy and modifies the copy — the original is intact. With a pointer the function gets the address and modifies the original.

go
package main

import "fmt"

// tryChangeRating receives a copy — the original won't change.
func tryChangeRating(r float64) {
    r = 10.0
}

// changeRating receives the address and modifies the original.
func changeRating(r *float64, newRating float64) {
    *r = newRating
}

func main() {
    rating := 8.0
    tryChangeRating(rating)
    fmt.Println("after tryChangeRating:", rating)

    changeRating(&rating, 9.5)
    fmt.Println("after changeRating:", rating)
}
stdout // program output
after tryChangeRating: 8
after changeRating: 9.5

Pointers to structs

Pointers are especially useful with structs: a large struct is expensive to copy, so it is passed by pointer. And Go has automatic dereferencing: instead of (*p).Views you write simply p.Views — Go inserts the * itself. Structs are covered in detail in 15 — Structs.

go
package main

import "fmt"

type Movie struct {
    Title  string
    Rating float64
    Views  int
}

func addView(m *Movie) {
    m.Views++ // the same as (*m).Views++ — Go dereferences on its own
}

func main() {
    film := Movie{Title: "Tenet", Rating: 7.8, Views: 50000}
    addView(&film)
    addView(&film)
    fmt.Println(film.Views)

    p := &film
    p.Rating = 8.0
    fmt.Println(film.Rating, (*p).Title, p.Title)
}
stdout // program output
50002
8 Tenet Tenet

new

The built-in function new(T) creates a variable of type T with the zero value and returns a pointer to it. It isn't used often: usually it's simpler to take an address with &.

go
package main

import "fmt"

func main() {
    numPtr := new(int) // *int, points at 0
    fmt.Println(*numPtr)
    *numPtr = 999
    fmt.Println(*numPtr)

    rating := 0.0
    same := &rating // the same thing, but more familiar
    *same = 8.5
    fmt.Println(rating)
}
stdout // program output
0
999
8.5

The nil pointer

A pointer's zero value is nil: the pointer points nowhere. Dereferencing it is a panic.

go
package main

import "fmt"

func main() {
    var p *int
    fmt.Println(*p) // panic expected
}
text
panic: runtime error: invalid memory address or nil pointer dereference

That's why pointers are checked before dereferencing:

go
package main

import "fmt"

func main() {
    var p *int
    fmt.Println(p == nil, p)
    if p != nil {
        fmt.Println(*p) // without the check this would panic
    }
}
stdout // program output
true <nil>

A pointer as an optional value

A useful pattern: nil means «the value isn't set», non-nil means «it is set». This distinguishes two situations that a plain float64 cannot: «the user didn't rate» and «they rated 0».

go
package main

import "fmt"

func printUserRating(name string, rating *float64) {
    if rating == nil {
        fmt.Printf("%s: no rating\n", name)
        return
    }
    fmt.Printf("%s: %.1f\n", name, *rating)
}

func main() {
    score := 8.5
    zero := 0.0
    printUserRating("Alexey", &score)
    printUserRating("Maria", nil)
    printUserRating("Oleg", &zero) // rated 0 — not the same as «no rating»
}
stdout // program output
Alexey: 8.5
Maria: no rating
Oleg: 0.0

Returning a pointer to a local variable

In C and C++ this is dangerous: a local variable dies when the function returns. In Go it's safe: the compiler sees that the variable is still referenced and places it not on the stack but on the heap. There it lives as long as a pointer to it exists, and then the garbage collector removes it.

go
package main

import "fmt"

type Movie struct {
    Title  string
    Rating float64
}

func createMovie(title string, rating float64) *Movie {
    m := Movie{Title: title, Rating: rating}
    return &m // safe: the compiler will move m to the heap
}

func main() {
    film := createMovie("Oppenheimer", 8.5)
    fmt.Println(*film)
    fmt.Printf("%+v\n", film)
}
stdout // program output
{Oppenheimer 8.5}
&{Title:Oppenheimer Rating:8.5}

Reference types

Slices, maps, and channels already contain a pointer inside. They are also passed by value, but only the small header is copied while the data stays shared. So a pointer to them is usually unnecessary: element changes are visible outside.

go
package main

import "fmt"

func modifySlice(s []string) {
    if len(s) > 0 {
        s[0] = "CHANGED"
    }
}

func modifyMap(m map[string]float64) {
    m["Gladiator"] = 8.6
}

func main() {
    films := []string{"A", "B", "C"}
    modifySlice(films)
    fmt.Println(films)

    scores := map[string]float64{"Dune": 8.1}
    modifyMap(scores)
    fmt.Println(scores)
}
stdout // program output
[CHANGED B C]
map[Dune:8.1 Gladiator:8.6]

Summary

What pointers are for:

  1. Modifying the caller's variable from a function.
  2. Not copying large structs.
  3. Expressing optional values: nil — not set.

Rules of use:

  1. Check a pointer for nil before dereferencing.
  2. Go dereferences a pointer to a struct automatically when you access fields.
  3. Returning a pointer to a local variable from a function is safe.
  4. Slices and maps are already reference types — a pointer to them is usually unnecessary.

Practice

  1. Write swap(a, b *int) that swaps the values of two variables.
  2. Write applyDiscount(priceKopecks *int, percent int) that reduces a price by a percentage. Calling it with nil must not panic.
  3. Write averageRated(ratings []*float64) (float64, int) — the average rating and the number of ratings; nil in the slice means «didn't rate» and is skipped.
solution
go
package main

import "fmt"

func swap(a, b *int) {
    *a, *b = *b, *a
}

func applyDiscount(priceKopecks *int, percent int) {
    if priceKopecks == nil {
        return
    }
    *priceKopecks = *priceKopecks * (100 - percent) / 100
}

func averageRated(ratings []*float64) (float64, int) {
    sum, count := 0.0, 0
    for _, r := range ratings {
        if r == nil {
            continue // the user didn't rate
        }
        sum += *r
        count++
    }
    if count == 0 {
        return 0, 0
    }
    return sum / float64(count), count
}

func main() {
    x, y := 1, 2
    swap(&x, &y)
    fmt.Println(x, y)

    price := 99_900
    applyDiscount(&price, 15)
    applyDiscount(nil, 15) // doesn't panic
    fmt.Println(price)

    a, b := 8.0, 9.0
    avg, n := averageRated([]*float64{&a, nil, &b, nil})
    fmt.Printf("%.1f across %d ratings\n", avg, n)
}
stdout // program output
2 1
84915
8.5 across 2 ratings

Drill: predict the output

go
package main

import "fmt"

func update(p *int) {
    *p = 10
    p = nil
}

func main() {
    n := 1
    p := &n
    update(p)
    fmt.Println(n, p == nil)
}
self-check
text
10 false

A pointer is passed by value too: the function receives a copy of the address. Writing through *p changes n, while p = nil only nulls the local copy of the pointer.

Check yourself

questionWhat do the & and * operators do?

&x — takes the address of the variable x. *p — dereferences the pointer p: reads or writes the value at the address.

questionWhat is the type of &x if x is a float64?

*float64.

questionHow can a function modify the caller's variable?

Take a pointer (func f(p *T)), and the caller passes the address: f(&x). Inside — *p = ….

questionWhat happens when you dereference a nil pointer?

A panic: invalid memory address or nil pointer dereference. Check p != nil before dereferencing.

questionIs it safe to return a pointer to a local variable from a function?

Yes. Escape analysis notices that the variable «escapes» the function and places it on the heap; the GC removes it when no pointers remain.

questionDo you need to pass a map to a function by pointer to add an element?

No. A map contains a pointer to its data inside; changes are visible outside as is.

questionWhy use *float64 instead of float64 for a user's rating?

To distinguish «no rating» (nil) from «a rating of 0».


Key takeaways

  • 📍 A pointer is an address: & takes the address, * reads and writes the value at it.
  • ✏️ Through a pointer a function modifies the original and avoids copying large structs.
  • 🪄 Struct fields are accessed through a pointer with a plain dot — Go dereferences on its own.
  • 💥 A nil pointer must not be dereferenced — check before use.
  • 🏠 A pointer to a local variable can be returned: escape analysis moves it to the heap.
  • 🔗 Slices, maps, and channels are already reference types — a pointer to them is usually unnecessary.
// related topics and cheatsheets