Part 3. Data & MemoryLesson 09# go# collections# slices# interview

Arrays and slices

len and cap, append and reallocation, a shared backing array, copy, memory leaks

Цели главы

  • Объяснить разницу между массивом и слайсом — частый вопрос собеседования.
  • Создавать слайсы литералом, через make и нарезкой; понимать len и cap.
  • Понимать, когда append пишет в тот же массив, а когда переаллоцирует.
  • Копировать, удалять элементы и не ловить утечки памяти.

Зачем коллекции

Нужно хранить сто фильмов каталога — не заводить же film1, film2, film3. Коллекция складывает всё в одну переменную. В Go для последовательностей их два вида: массивы — жёсткие, размер не меняется; слайсы — гибкие, ими пользуются каждый день.

Массивы

Массив — коробка на фиксированное число ячеек: указал 5 — будет ровно 5. Три способа создать:

go
package main

import "fmt"

func main() {
    var a [5]int                           // пять нулей
    b := [3]string{"Go", "Python", "Rust"} // сразу с данными
    c := [...]int{1, 2, 3}                 // размер посчитает компилятор

    fmt.Println(a, b, c, len(c))
    a[1] = 99
    fmt.Println(a[0], a[1])

    for i, v := range b {
        fmt.Println(i, v)
    }
}
stdout // вывод программы
[0 0 0 0 0] [Go Python Rust] [1 2 3] 3
0 99
0 Go
1 Python
2 Rust
  • Индексы начинаются с нуля: первый элемент — a[0].
  • [...] не делает массив резиновым: размер всё равно фиксируется, просто его считает компилятор.
  • range сразу даёт индекс и значение — длину вручную считать не нужно.

Выход за границы

go
package main

import "fmt"

func main() {
    films := []string{"Дюна", "Матрица"}
    i := 5
    fmt.Println(films[i]) // ожидается panic
}

Программа падает с сообщением:

text
panic: runtime error: index out of range [5] with length 2

Почему массивы почти не используют

  1. Массив копируется целиком — при присваивании и при передаче в функцию. В массиве 10 000 элементов — скопируются все 10 000.
  2. Размер — часть типа. [3]int и [5]int — разные типы, один вместо другого не передать.
go
package main

import "fmt"

func resetFirst(arr [3]int) {
    arr[0] = 0 // меняем копию всего массива
}

func main() {
    a := [3]int{1, 2, 3}
    b := a // копия, а не ссылка
    b[0] = 100
    resetFirst(a)
    fmt.Println(a, b)
}
stdout // вывод программы
[1 2 3] [100 2 3]

Жёстко и неудобно — поэтому существуют слайсы.

Слайсы

Слайс — это окно поверх массива. Он знает три вещи: где лежит массив (указатель), сколько элементов сейчас видно (длина, len) и сколько поместится без переезда (ёмкость, cap). Аналогия: массив — книжная полка, слайс — рамка, которую двигаешь по полке, выбирая участок. Рамку можно сузить, расширить или переставить на новую полку побольше.

Пример: массив из 8 ячеек и слайс s := arr[2:6].

Индекс массива 0 1 2 3 4 5 6 7
Значение 10 20 30 40 50 60 70 80
Слайс s s[0] s[1] s[2] s[3] запас запас
  • len(s) = 4 — видны 4 элемента: 30, 40, 50, 60.
  • cap(s) = 6 — от начала слайса до конца массива 6 ячеек.
заголовок слайса sptr · len = 4 · cap = 6ptrмассив из 8 элементов1020304050607080len = 4cap = 6

Как создать слайс

Главное отличие от массива: в квадратных скобках нет числа.

go
package main

import "fmt"

func main() {
    arr := [8]int{10, 20, 30, 40, 50, 60, 70, 80}

    s1 := []int{1, 2, 3}     // литерал
    s2 := make([]int, 5)     // пять нулей
    s3 := make([]int, 0, 10) // пустой, но место на 10 элементов уже выделено
    s4 := arr[2:6]           // нарезка: индексы 2..5, правая граница не входит

    for _, s := range [][]int{s1, s2, s3, s4} {
        fmt.Printf("%v len=%d cap=%d\n", s, len(s), cap(s))
    }
}
stdout // вывод программы
[1 2 3] len=3 cap=3
[0 0 0 0 0] len=5 cap=5
[] len=0 cap=10
[30 40 50 60] len=4 cap=6

Нарезка удобна и для слайсов: первые три жанра для главной страницы — genres[:3], всё начиная с третьего — genres[2:], середина — genres[1:3].

append — добавление элементов

У append одно железное правило: результат всегда присваивают обратно: s = append(s, x). Причина — append может вернуть совсем другой слайс.

  • Если в массиве под слайсом есть свободное место, append дописывает элемент и увеличивает длину — массив тот же.
  • Если места нет, Go создаёт новый массив побольше, копирует туда старые данные и добавляет элемент. Слайс начинает указывать на новый массив.
go
package main

import "fmt"

func main() {
    s := make([]int, 0, 2)
    for i := 1; i <= 5; i++ {
        s = append(s, i) // результат append всегда присваиваем обратно
        fmt.Printf("%v len=%d cap=%d\n", s, len(s), cap(s))
    }

    more := []int{6, 7}
    s = append(s, more...) // три точки распаковывают слайс
    fmt.Println(s)
}
stdout // вывод программы
[1] len=1 cap=2
[1 2] len=2 cap=2
[1 2 3] len=3 cap=4
[1 2 3 4] len=4 cap=4
[1 2 3 4 5] len=5 cap=8
[1 2 3 4 5 6 7]

Видно, как ёмкость удваивается в момент переезда: 2 → 4 → 8. append(a, b...) — распаковка: как будто элементы b перечислили через запятую вручную.

Нарезка и общий массив

Самый частый баг новичков: нарезка не копирует данные. Новый слайс смотрит на тот же массив, поэтому изменение через один слайс видно через другой. Это не баг Go, а задумка — но если про неё не знать, будешь ловить странные ошибки.

Нужна независимая копия — создай слайс через make и скопируй данные функцией copy. Теперь это два отдельных массива.

go
package main

import "fmt"

func main() {
    original := []int{1, 2, 3, 4, 5}
    part := original[1:4] // [2 3 4] — тот же массив
    part[0] = 99
    fmt.Println(original) // оригинал изменился

    clone := make([]int, len(original))
    n := copy(clone, original) // копирует min(len(dst), len(src)) элементов
    clone[0] = -1
    fmt.Println(original, clone, n)
}
stdout // вывод программы
[1 99 3 4 5]
[1 99 3 4 5] [-1 99 3 4 5] 5

nil-слайс

Слайс, объявленный через var без инициализации, равен nil. Звучит страшно, но с ним можно нормально работать: длина 0, range проходит ноль раз, а append сам создаст массив при первом добавлении. Бояться nil-слайсов не нужно.

go
package main

import "fmt"

func main() {
    var films []string // nil-слайс: массива под капотом ещё нет
    fmt.Println(films == nil, len(films))
    films = append(films, "Дюна") // append сам создаст массив
    fmt.Println(films, films == nil)

    empty := []string{} // пустой, но не nil
    fmt.Println(empty == nil, len(empty))
}
stdout // вывод программы
true 0
[Дюна] false
false 0

Удаление элемента

Встроенной функции «удали элемент» в Go нет, но есть трюк через append: берёшь всё, что до удаляемого элемента, и склеиваешь с тем, что после.

go
package main

import (
    "fmt"
    "slices"
)

func main() {
    s := []string{"Боевик", "Мелодрама", "Хоррор", "Комедия"}
    i := 1 // удаляем «Мелодраму»
    s = append(s[:i], s[i+1:]...)
    fmt.Println(s)

    t := []string{"Боевик", "Мелодрама", "Хоррор", "Комедия"}
    t = slices.Delete(t, 1, 2) // то же через пакет slices (Go 1.21+)
    fmt.Println(t)

    orig := []int{1, 2, 3, 4}
    trimmed := append(orig[:1], orig[2:]...)
    fmt.Println(orig, trimmed) // исходный массив тоже изменился
}
stdout // вывод программы
[Боевик Хоррор Комедия]
[Боевик Хоррор Комедия]
[1 3 4 4] [1 3 4]

s[:i] — всё до индекса i, s[i+1:] — всё после него; три точки распаковывают второй кусок, и элемент с индексом i просто не попадает в результат.

Что под капотом

Без этого многие вещи кажутся магией, и это любимая тема собеседований. Слайс — не сам массив, а маленькая структура из трёх полей: указатель на массив, длина и ёмкость. На 64-битной системе она занимает 24 байта, а сам массив живёт отдельно.

Отсюда ответы на частые вопросы:

  • Почему передавать слайс в функцию дёшево? Копируются только 24 байта заголовка — сколько бы элементов ни было: тысяча или миллион.
  • Почему изменение элемента в функции видно снаружи, а append — нет? У функции своя копия заголовка, но указатель в ней смотрит на тот же массив. Запись s[0] = 999 идёт в общий массив. А append меняет длину (и, возможно, указатель) только в локальном заголовке.
go
package main

import (
    "fmt"
    "unsafe"
)

func modify(s []int) {
    s[0] = 999       // пишем в общий массив — видно снаружи
    s = append(s, 4) // меняется только локальный заголовок — не видно снаружи
}

func addFilm(s []int, v int) []int {
    return append(s, v) // идиоматично: вернуть новый слайс
}

func main() {
    s := []int{1, 2, 3}
    modify(s)
    fmt.Println(s)

    s = addFilm(s, 4)
    fmt.Println(s)
    fmt.Println("размер заголовка:", unsafe.Sizeof(s), "байта")
}
stdout // вывод программы
[999 2 3]
[999 2 3 4]
размер заголовка: 24 байта

Чтобы добавление было видно снаружи, есть два варианта: вернуть новый слайс из функции или передать указатель на слайс. Первый — идиоматичный.

заголовок в mainlen = 3 · cap = 3копия заголовка в modifylen = 3 · cap = 3общий массив999 · 2 · 3новый массив999 · 2 · 3 · 4ptrptrappend: cap не хватило

Стратегия роста

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

Зачем это знать? Чтобы заранее делать make с ёмкостью, когда размер известен. Если в слайсе будет 1000 элементов, а cap не указан, append переаллоцирует массив около десяти раз, и каждый раз копирует все данные. Указал cap сразу — ноль переаллокаций.

Утечка памяти при нарезке

Ловит даже опытных. Есть огромный массив на миллион элементов, из него сделали маленький слайс на 10. Кажется, что Go освободит память большого массива. Нет: маленький слайс держит указатель на тот же массив, и сборщик мусора не может его убрать.

go
func getFirst10(huge []int) []int {
    return huge[:10] // держит в памяти весь массив huge
}

func getFirst10Safe(huge []int) []int {
    result := make([]int, 10)
    copy(result, huge[:10]) // копия — большой массив соберёт GC
    return result
}

Практика

Домашнее задание

  1. Сумма. Напиши func sum(nums []int) int — сумму элементов. Проверь на пустом слайсе и на nil-слайсе.
  2. Удаление дубликатов. Напиши removeDuplicates(s []string) []string — новый слайс без повторов, порядок сохраняется. Пригодится мапа из следующей главы, но сначала реши без неё.
  3. Фильтр для каталога. Есть слайс рейтингов фильмов. Напиши filterByRating(ratings []float64, minRating float64) []float64, которая возвращает рейтинги выше порога. Используй make с cap.
решениеЭталонное решение
go
package main

import "fmt"

func sum(nums []int) int {
    total := 0
    for _, n := range nums {
        total += n
    }
    return total
}

func removeDuplicates(s []string) []string {
    result := make([]string, 0, len(s))
    for _, v := range s {
        seen := false
        for _, r := range result {
            if r == v {
                seen = true
                break
            }
        }
        if !seen {
            result = append(result, v)
        }
    }
    return result
}

func filterByRating(ratings []float64, minRating float64) []float64 {
    result := make([]float64, 0, len(ratings)) // ёмкость с запасом — без переаллокаций
    for _, r := range ratings {
        if r > minRating {
            result = append(result, r)
        }
    }
    return result
}

func main() {
    var nilSlice []int
    fmt.Println(sum([]int{1, 2, 3}), sum([]int{}), sum(nilSlice))
    fmt.Println(removeDuplicates([]string{"Дюна", "Матрица", "Дюна", "Довод", "Матрица"}))
    fmt.Println(filterByRating([]float64{7.2, 9.1, 6.5, 8.8, 5.3}, 7.0))
}
stdout // вывод программы
6 0 0
[Дюна Матрица Довод]
[7.2 9.1 8.8]

removeDuplicates с вложенным циклом работает за O(n²); с мапой — за O(n).

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

go
package main

import "fmt"

func main() {
    a := []int{1, 2, 3, 4}
    b := a[:2]
    b = append(b, 99)
    fmt.Println(a, b, len(b), cap(b))
}
самопроверкаОтвет
text
[1 2 99 4] [1 2 99] 3 4

b — окно над тем же массивом с ёмкостью 4. Места хватает, поэтому append записал 99 прямо в a[2].

Проверь себя

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

У массива фиксированный размер, который входит в тип ([3]int ≠ [5]int), и он копируется целиком. Слайс — заголовок (указатель, len, cap) над массивом: размер динамический, копируется только заголовок.

вопросЧто хранит заголовок слайса и сколько он весит?

Указатель на массив, длину и ёмкость — 24 байта на 64-битной системе.

вопросПочему результат append всегда присваивают обратно?

Когда ёмкости не хватает, append создаёт новый массив и возвращает слайс, указывающий на него. Старая переменная продолжит смотреть на старый массив.

вопросФункция получила слайс и сделала s[0] = 1 и s = append(s, 2). Что увидит вызывающий код?

Изменение s[0] — да: запись идёт в общий массив. Новый элемент — нет: append изменил только локальную копию заголовка.

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

clone := make([]T, len(s)) и copy(clone, s) — или slices.Clone(s).

вопросЧем nil-слайс отличается от пустого?

У nil-слайса нет массива под капотом и он равен nil, у пустого массив есть. Оба имеют длину 0, с обоими работают range и append. Разница видна в JSON: null против [].

вопросКак может возникнуть утечка памяти при нарезке и как её избежать?

Маленький слайс от огромного массива держит весь массив, и GC не может его освободить. Нужно скопировать нужную часть в новый слайс.

вопросЗачем указывать ёмкость в make([]T, 0, n)?

Чтобы append не переаллоцировал массив по мере роста — это экономит копирования и память.


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

  • 📦 Массив — фиксированный размер в типе и копирование целиком; на практике работают со слайсами.
  • 🪟 Слайс — 24-байтный заголовок (ptr, len, cap) поверх массива.
  • ➕ s = append(s, x): при нехватке cap создаётся новый массив, поэтому результат присваивают обратно.
  • 🔗 Нарезка делит массив: изменения видны через все слайсы; независимая копия — copy или slices.Clone.
  • 📈 Ёмкость растёт ×2 до 256 элементов, потом медленнее; известен размер — делай make с cap.
  • 🧲 Маленький слайс от большого массива держит его в памяти — копируй нужную часть.

Chapter goals

  • Explain the difference between an array and a slice — a frequent interview question.
  • Create slices with a literal, via make, and by slicing; understand len and cap.
  • Understand when append writes into the same array and when it reallocates.
  • Copy data, remove elements, and avoid memory leaks.

Why collections

You need to store a hundred movies from a catalog — you aren't going to declare film1, film2, film3. A collection keeps everything in a single variable. Go has two kinds of sequences for this: arrays — rigid, with a size that never changes; and slices — flexible, and what you use every day.

Arrays

An array is a box with a fixed number of slots: say 5, and it is exactly 5. Three ways to create one:

go
package main

import "fmt"

func main() {
    var a [5]int                           // five zeros
    b := [3]string{"Go", "Python", "Rust"} // with data right away
    c := [...]int{1, 2, 3}                 // the compiler counts the size

    fmt.Println(a, b, c, len(c))
    a[1] = 99
    fmt.Println(a[0], a[1])

    for i, v := range b {
        fmt.Println(i, v)
    }
}
stdout // program output
[0 0 0 0 0] [Go Python Rust] [1 2 3] 3
0 99
0 Go
1 Python
2 Rust
  • Indexes start at zero: the first element is a[0].
  • [...] does not make the array stretchy: the size is still fixed, the compiler just counts it.
  • range gives you the index and the value at once — no need to track the length manually.

Out of bounds

go
package main

import "fmt"

func main() {
    films := []string{"Dune", "The Matrix"}
    i := 5
    fmt.Println(films[i]) // panic expected
}

The program crashes with the message:

text
panic: runtime error: index out of range [5] with length 2

Why arrays are almost never used

  1. The array is copied as a whole — on assignment and when passed to a function. An array of 10,000 elements copies all 10,000.
  2. The size is part of the type. [3]int and [5]int are different types; one cannot be passed where the other is expected.
go
package main

import "fmt"

func resetFirst(arr [3]int) {
    arr[0] = 0 // changes a copy of the whole array
}

func main() {
    a := [3]int{1, 2, 3}
    b := a // a copy, not a reference
    b[0] = 100
    resetFirst(a)
    fmt.Println(a, b)
}
stdout // program output
[1 2 3] [100 2 3]

Rigid and inconvenient — which is why slices exist.

Slices

A slice is a window over an array. It knows three things: where the array lives (a pointer), how many elements are currently visible (the length, len), and how many fit without moving (the capacity, cap). Analogy: the array is a bookshelf, the slice is a frame you slide along the shelf to pick a section. You can narrow the frame, widen it, or move it to a bigger shelf.

Example: an array of 8 slots and the slice s := arr[2:6].

Array index 0 1 2 3 4 5 6 7
Value 10 20 30 40 50 60 70 80
Slice s s[0] s[1] s[2] s[3] spare spare
  • len(s) = 4 — 4 elements are visible: 30, 40, 50, 60.
  • cap(s) = 6 — from the start of the slice to the end of the array there are 6 slots.
slice header sptr · len = 4 · cap = 6ptrarray of 8 elements1020304050607080len = 4cap = 6

How to create a slice

The key difference from an array: inside the square brackets there is no number.

go
package main

import "fmt"

func main() {
    arr := [8]int{10, 20, 30, 40, 50, 60, 70, 80}

    s1 := []int{1, 2, 3}     // literal
    s2 := make([]int, 5)     // five zeros
    s3 := make([]int, 0, 10) // empty, but space for 10 elements is already allocated
    s4 := arr[2:6]           // slicing: indexes 2..5, the upper bound is excluded

    for _, s := range [][]int{s1, s2, s3, s4} {
        fmt.Printf("%v len=%d cap=%d\n", s, len(s), cap(s))
    }
}
stdout // program output
[1 2 3] len=3 cap=3
[0 0 0 0 0] len=5 cap=5
[] len=0 cap=10
[30 40 50 60] len=4 cap=6

Slicing works on slices too: the first three genres for the home page — genres[:3], everything from the third onward — genres[2:], the middle — genres[1:3].

append — adding elements

append has one ironclad rule: always assign the result back: s = append(s, x). The reason — append may return a completely different slice.

  • If the array under the slice has free space, append writes the element and grows the length — the array stays the same.
  • If there is no room, Go allocates a bigger array, copies the old data there, and adds the element. The slice now points to the new array.
go
package main

import "fmt"

func main() {
    s := make([]int, 0, 2)
    for i := 1; i <= 5; i++ {
        s = append(s, i) // the result of append is always assigned back
        fmt.Printf("%v len=%d cap=%d\n", s, len(s), cap(s))
    }

    more := []int{6, 7}
    s = append(s, more...) // three dots unpack the slice
    fmt.Println(s)
}
stdout // program output
[1] len=1 cap=2
[1 2] len=2 cap=2
[1 2 3] len=3 cap=4
[1 2 3 4] len=4 cap=4
[1 2 3 4 5] len=5 cap=8
[1 2 3 4 5 6 7]

You can see the capacity double at the moment of the move: 2 → 4 → 8. append(a, b...) is unpacking: as if the elements of b were listed by hand, separated by commas.

Slicing and the shared array

The most common beginner bug: slicing does not copy the data. The new slice looks at the same array, so a change through one slice is visible through the other. It is not a Go bug, it is the design — but if you don't know about it, you'll be chasing strange errors.

When you need an independent copy, create a slice with make and copy the data with copy. Now these are two separate arrays.

go
package main

import "fmt"

func main() {
    original := []int{1, 2, 3, 4, 5}
    part := original[1:4] // [2 3 4] — the same array
    part[0] = 99
    fmt.Println(original) // the original changed

    clone := make([]int, len(original))
    n := copy(clone, original) // copies min(len(dst), len(src)) elements
    clone[0] = -1
    fmt.Println(original, clone, n)
}
stdout // program output
[1 99 3 4 5]
[1 99 3 4 5] [-1 99 3 4 5] 5

The nil slice

A slice declared with var and no initializer equals nil. It sounds scary, but you can work with it just fine: length 0, range iterates zero times, and append allocates the array on the first addition. There is nothing to fear in nil slices.

go
package main

import "fmt"

func main() {
    var films []string // a nil slice: no backing array yet
    fmt.Println(films == nil, len(films))
    films = append(films, "Dune") // append creates the array itself
    fmt.Println(films, films == nil)

    empty := []string{} // empty, but not nil
    fmt.Println(empty == nil, len(empty))
}
stdout // program output
true 0
[Dune] false
false 0

Removing an element

Go has no built-in «remove an element» function, but there is a trick with append: take everything before the element being removed and glue it to everything after.

go
package main

import (
    "fmt"
    "slices"
)

func main() {
    s := []string{"Action", "Romance", "Horror", "Comedy"}
    i := 1 // remove "Romance"
    s = append(s[:i], s[i+1:]...)
    fmt.Println(s)

    t := []string{"Action", "Romance", "Horror", "Comedy"}
    t = slices.Delete(t, 1, 2) // the same via the slices package (Go 1.21+)
    fmt.Println(t)

    orig := []int{1, 2, 3, 4}
    trimmed := append(orig[:1], orig[2:]...)
    fmt.Println(orig, trimmed) // the backing array changed too
}
stdout // program output
[Action Horror Comedy]
[Action Horror Comedy]
[1 3 4 4] [1 3 4]

s[:i] is everything before index i, s[i+1:] is everything after it; the three dots unpack the second piece, and the element at index i simply never makes it into the result.

Under the hood

Without this, many things look like magic — and it is a favorite interview topic. A slice is not the array itself but a small structure of three fields: a pointer to the array, the length, and the capacity. On a 64-bit system it takes 24 bytes, and the array itself lives elsewhere.

This answers two common questions:

  • Why is passing a slice to a function cheap? Only the 24-byte header is copied — no matter how many elements there are: a thousand or a million.
  • Why is an element change inside a function visible outside, but append is not? The function has its own copy of the header, but the pointer inside it looks at the same array. The write s[0] = 999 goes into the shared array. And append changes the length (and possibly the pointer) only in the local header.
go
package main

import (
    "fmt"
    "unsafe"
)

func modify(s []int) {
    s[0] = 999       // writes into the shared array — visible outside
    s = append(s, 4) // changes only the local header — not visible outside
}

func addFilm(s []int, v int) []int {
    return append(s, v) // idiomatic: return the new slice
}

func main() {
    s := []int{1, 2, 3}
    modify(s)
    fmt.Println(s)

    s = addFilm(s, 4)
    fmt.Println(s)
    fmt.Println("header size:", unsafe.Sizeof(s), "bytes")
}
stdout // program output
[999 2 3]
[999 2 3 4]
header size: 24 bytes

To make an addition visible outside, there are two options: return the new slice from the function, or pass a pointer to the slice. The first one is idiomatic.

header in mainlen = 3 · cap = 3header copy in modifylen = 3 · cap = 3shared array999 · 2 · 3new array999 · 2 · 3 · 4ptrptrappend: cap exceeded

Growth strategy

When append runs out of room, Go allocates an array with a margin. The rule used to be simple — double it. The strategy is smarter now: small slices roughly double, large ones grow more slowly so memory isn't wasted.

Why does this matter? So you can call make with a capacity in advance when the size is known. If a slice will hold 1000 elements and cap isn't set, append reallocates the array about ten times, copying all the data each time. Set cap up front — zero reallocations.

Memory leaks from slicing

This one catches even experienced developers. There is a huge array of a million elements, and a small 10-element slice is made from it. It seems Go will free the big array's memory. It won't: the small slice holds a pointer to the same array, and the garbage collector cannot reclaim it.

go
func getFirst10(huge []int) []int {
    return huge[:10] // keeps the entire huge array in memory
}

func getFirst10Safe(huge []int) []int {
    result := make([]int, 10)
    copy(result, huge[:10]) // a copy — the GC can collect the big array
    return result
}

Practice

Homework

  1. Sum. Write func sum(nums []int) int — the sum of the elements. Test it on an empty slice and on a nil slice.
  2. Deduplication. Write removeDuplicates(s []string) []string — a new slice without repeats, preserving order. The map from the next chapter will come in handy, but solve it without one first.
  3. Catalog filter. You have a slice of movie ratings. Write filterByRating(ratings []float64, minRating float64) []float64 that returns the ratings above the threshold. Use make with a cap.
solution
go
package main

import "fmt"

func sum(nums []int) int {
    total := 0
    for _, n := range nums {
        total += n
    }
    return total
}

func removeDuplicates(s []string) []string {
    result := make([]string, 0, len(s))
    for _, v := range s {
        seen := false
        for _, r := range result {
            if r == v {
                seen = true
                break
            }
        }
        if !seen {
            result = append(result, v)
        }
    }
    return result
}

func filterByRating(ratings []float64, minRating float64) []float64 {
    result := make([]float64, 0, len(ratings)) // capacity with headroom — no reallocations
    for _, r := range ratings {
        if r > minRating {
            result = append(result, r)
        }
    }
    return result
}

func main() {
    var nilSlice []int
    fmt.Println(sum([]int{1, 2, 3}), sum([]int{}), sum(nilSlice))
    fmt.Println(removeDuplicates([]string{"Dune", "The Matrix", "Dune", "Tenet", "The Matrix"}))
    fmt.Println(filterByRating([]float64{7.2, 9.1, 6.5, 8.8, 5.3}, 7.0))
}
stdout // program output
6 0 0
[Dune The Matrix Tenet]
[7.2 9.1 8.8]

The nested-loop removeDuplicates runs in O(n²); with a map — O(n).

Drill: predict the output

go
package main

import "fmt"

func main() {
    a := []int{1, 2, 3, 4}
    b := a[:2]
    b = append(b, 99)
    fmt.Println(a, b, len(b), cap(b))
}
self-check
text
[1 2 99 4] [1 2 99] 3 4

b is a window over the same array with a capacity of 4. There was room, so append wrote 99 straight into a[2].

Check yourself

questionHow does a slice differ from an array?

An array has a fixed size that is part of the type ([3]int ≠ [5]int) and is copied as a whole. A slice is a header (pointer, len, cap) over an array: the size is dynamic, and only the header is copied.

questionWhat does a slice header store, and how much does it weigh?

A pointer to the array, the length, and the capacity — 24 bytes on a 64-bit system.

questionWhy is the result of append always assigned back?

When the capacity runs out, append creates a new array and returns a slice pointing to it. The old variable would keep looking at the old array.

questionA function received a slice and did s[0] = 1 and s = append(s, 2). What will the caller see?

The s[0] change — yes: the write goes into the shared array. The new element — no: append changed only the local copy of the header.

questionHow do you make an independent copy of a slice?

clone := make([]T, len(s)) and copy(clone, s) — or slices.Clone(s).

questionHow does a nil slice differ from an empty one?

A nil slice has no backing array and equals nil; an empty one has an array. Both have length 0, and both work with range and append. The difference shows up in JSON: null versus [].

questionHow can slicing cause a memory leak, and how do you avoid it?

A small slice of a huge array keeps the whole array alive, and the GC cannot free it. Copy the part you need into a new slice.

questionWhy specify the capacity in make([]T, 0, n)?

So that append doesn't reallocate the array as it grows — this saves copies and memory.


Key takeaways

  • 📦 An array — fixed size in the type and full-copy semantics; in practice you work with slices.
  • 🪟 A slice — a 24-byte header (ptr, len, cap) over an array.
  • ➕ s = append(s, x): when cap runs out, a new array is created, hence the result is assigned back.
  • 🔗 Slicing shares the array: changes are visible through all slices; an independent copy is copy or slices.Clone.
  • 📈 Capacity grows ×2 up to 256 elements, then more slowly; when the size is known — make with a cap.
  • 🧲 A small slice of a big array keeps it in memory — copy the part you need.
// related topics and cheatsheets