SyntaxPilot
Courses/Go Programming/Lesson 13

Go Programming · Lesson 13 of 89 · 12 min

Slices: the basics

slice typeslice literalsmake([]T, len, cap)len and capappendslicing expressions s[low:high]nil slice vs empty slicecopyrange over slices (index, value)2D slicesslices as function arguments

These are the notes for Go episode 13. Last episode, arrays gave us one name for many values, but an array's length is fixed forever, because the length is part of its type. Today you meet the type Go programmers use far more often: the slice, a list that can grow. You will learn the slice type, slice literals, append, nil slices and empty slices, len and cap, the backing array, make([]T, len, cap), slicing expressions s[low:high], copy, range over slices, slices as function arguments, and 2D slices. Every example runs as-is in the SyntaxPilot compiler (language: Go); outputs and errors are from real runs (Go 1.24).

The problem: the array that can't grow

Raju's chai stall from episode 12 stored a week of sales in [7]int. But the stall stays open for a month. Day eight arrives:

package main

import "fmt"

func main() {
    sales := [7]int{120, 95, 140, 80, 110, 150, 200}
    sales[7] = 90
    fmt.Println(sales)
}
# command-line-arguments
./main.go:7:11: invalid argument: index 7 out of bounds [0:7]

Then let's size the array from a variable:

package main

import "fmt"

func main() {
    days := 30
    var month [days]int
    fmt.Println(days, len(month))
}
# command-line-arguments
./main.go:7:16: invalid array length days

An array's length is part of its type, so it must be a constant (a value fixed when the code is written). Raju doesn't know how many days his stall will run. We need a list whose length can change while the program runs.

Your first slice

Think of a school register:

A school register In Go Name
One notebook, many rows []int a slice type: no length in the brackets
A new student joins: write a new row append(s, x) append adds to the end
Row number 3 s[3] indexes still start at 0
  • A slice is a list of values of one type whose length can change.
  • Its type is written []T (empty brackets): []int is "a slice of ints".
  • A slice literal looks like an array literal without the length: []int{120, 95, 140}.
  • append(s, values...) is a built-in function that adds one or more values at the end and returns the new slice.
package main

import "fmt"

func main() {
    sales := []int{120, 95, 140}
    fmt.Printf("%T %v len=%d\n", sales, sales, len(sales))

    sales = append(sales, 80)
    sales = append(sales, 110, 150, 200, 90)
    fmt.Println(sales, len(sales))
}
[]int [120 95 140] len=3
[120 95 140 80 110 150 200 90] 8

%T prints the type. Indexing (sales[2]), len, and loops work exactly like arrays.

Always assign append's result

package main

import "fmt"

func main() {
    sales := []int{120, 95, 140}
    append(sales, 80)
    fmt.Println(sales)
}
# command-line-arguments
./main.go:7:5: append(sales, 80) (value of type []int) is not used

append does not change the slice you pass in place; it returns the longer slice. Dropping that result would lose the 80, so Go refuses to compile. Always write s = append(s, x).

nil slices and empty slices

package main

import "fmt"

func main() {
    var orders []int
    fmt.Println(orders, len(orders), orders == nil)

    empty := []int{}
    fmt.Println(empty, len(empty), empty == nil)

    orders = append(orders, 3)
    fmt.Println(orders, len(orders), orders == nil)
}
[] 0 true
[] 0 false
[3] 1 false
  • nil is Go's word for "no value at all". The zero value of a slice is nil: a nil slice has length 0 and no backing array yet.
  • An empty slice ([]int{}) also has length 0, but it is not nil.
  • For almost all code they behave the same: len is 0, range loops zero times, and append works on a nil slice, so you never need to "set one up" first.
  • Real-life picture: a nil slice is a register nobody has bought yet; an empty slice is a register with no rows.

Indexing can't add elements

package main

import "fmt"

func main() {
    var orders []int
    orders[0] = 5
    fmt.Println(orders)
}
panic: runtime error: index out of range [0] with length 0

goroutine 1 [running]:
main.main()
    /tmp/.../main.go:7 +0x12
exit status 2

Indexing only reads or replaces elements that already exist. To add one, append.

len and cap

Under the hood a slice keeps its elements in an ordinary array called the backing array. Picture a classroom bench:

A classroom bench In Go Meaning
3 students sitting len(s) length: elements in use
Room for 4 cap(s) capacity: how many fit in the backing array (from the slice's start)
A 5th student arrives append on a full slice Go makes a bigger backing array, copies everything, then adds
package main

import "fmt"

func main() {
    var s []int
    for i := 1; i <= 6; i++ {
        s = append(s, i)
        fmt.Println("len", len(s), "cap", cap(s))
    }
}
len 1 cap 1
len 2 cap 2
len 3 cap 4
len 4 cap 4
len 5 cap 8
len 6 cap 8

Length grows by one each time; capacity jumps (1, 2, 4, 8). Each jump is a new backing array plus a copy of all elements. The exact growth rule is a runtime detail; episode 14 opens it up. Always: 0 ≤ len(s) ≤ cap(s).

make: choosing length and capacity

make([]T, length, capacity) is a built-in that creates a slice with a backing array of the given capacity. Reserving room in advance is called preallocation.

package main

import "fmt"

func main() {
    cups := make([]int, 0, 30)
    fmt.Println(cups, len(cups), cap(cups))

    for day := 1; day <= 3; day++ {
        cups = append(cups, day*100)
    }
    fmt.Println(cups, len(cups), cap(cups))
}
[] 0 30
[100 200 300] 3 30

No new backing array was needed: capacity stayed 30.

The make + append trap

make([]int, 3) (no capacity given, so capacity = length) creates three zeros already inside:

package main

import "fmt"

func main() {
    cups := make([]int, 3)
    cups = append(cups, 120, 95, 140)
    fmt.Println(cups, len(cups))

    fixed := make([]int, 3)
    fixed[0], fixed[1], fixed[2] = 120, 95, 140
    fmt.Println(fixed, len(fixed))
}
[0 0 0 120 95 140] 6
[120 95 140] 3

Rule: make([]T, n) + set by index, or make([]T, 0, n) + append. Never make([]T, n) + append.

Slicing: s[low:high]

A slicing expression s[low:high] cuts out the elements from index low up to but not including high. Including the start and excluding the end is called half-open. Like a train ticket from station 1 to station 4: you board at 1 and are off at 4.

  • Length of the result = high - low.
  • Leave out low → starts at 0. Leave out high → runs to len(s). s[:] is everything.
  • Slicing does not copy. The new slice shares the backing array with the old one.
package main

import "fmt"

func main() {
    sales := []int{120, 95, 140, 80, 110, 150, 200}

    fmt.Println(sales[1:4])
    fmt.Println(sales[:3])
    fmt.Println(sales[4:])
    fmt.Println(sales[:])

    weekend := sales[5:7]
    weekend[0] = 999
    fmt.Println(weekend, sales)
}
[95 140 80]
[120 95 140]
[110 150 200]
[120 95 140 80 110 150 200]
[999 200] [120 95 140 80 110 999 200]

We only changed weekend[0], but sales[5] became 999 too: same memory. Episode 14 is all about this sharing.

Slicing past the end

package main

import "fmt"

func main() {
    sales := []int{120, 95, 140, 80, 110, 150, 200}
    end := 9
    fmt.Println(sales[2:end])
}
panic: runtime error: slice bounds out of range [:9] with capacity 7

Rule: 0 ≤ low ≤ high ≤ cap(s).

copy: a real, independent copy

copy(dst, src) copies elements from src into dst and returns how many it copied: the smaller of the two lengths. It never grows dst.

package main

import "fmt"

func main() {
    sales := []int{120, 95, 140}
    backup := make([]int, len(sales))
    n := copy(backup, sales)
    backup[0] = 0
    fmt.Println(n, sales, backup)

    var none []int
    fmt.Println(copy(none, sales), none)
}
3 [120 95 140] [0 95 140]
0 []

Copying into a nil slice copies 0 elements, which is why we made backup with len(sales) first. (Episode 14 shows the shortcut slices.Clone.)

range over a slice

for i, v := range s gives the index and a copy of the value. Changing v changes only the copy:

package main

import "fmt"

func main() {
    prices := []int{10, 20, 15}
    for _, p := range prices {
        p = p * 2
    }
    fmt.Println(prices)

    for i := range prices {
        prices[i] = prices[i] * 2
    }
    fmt.Println(prices)
}
[10 20 15]
[20 40 30]

To change elements, write through the index: s[i] = .... for i := range s gives only the index.

Slices and functions

Passing an array copies all its elements (episode 12). Passing a slice copies only a small description of it (pointer, length, capacity; episode 14), so the function shares the elements with the caller, but has its own length:

package main

import "fmt"

func discount(p []int) {
    for i := range p {
        p[i] -= 5
    }
}
func addTea(p []int) {
    p = append(p, 12)
}

func main() {
    prices := []int{20, 25, 30}
    discount(prices)
    addTea(prices)
    fmt.Println(prices)
}
[15 20 25]

discount changed the caller's elements (every price is 5 lower). But there is no 12: addTea's append only changed the function's own copy of the slice. Fix: return the slice and assign it, the same pattern as append:

package main

import "fmt"

func addTea(p []int) []int {
    return append(p, 12)
}

func main() {
    prices := []int{20, 25, 30}
    prices = addTea(prices)
    fmt.Println(prices)
}
[20 25 30 12]

2D slices

A school timetable has one row per day, and each day has a different number of periods. A slice of slices, [][]string, allows exactly that. Rows of different lengths are called jagged.

package main

import "fmt"

func main() {
    week := [][]string{
        {"Maths", "English", "Go"},
        {"Science"},
        {"Go", "Art"},
    }
    week[1] = append(week[1], "Music")
    for i, day := range week {
        fmt.Println(i, len(day), day)
    }
}
0 3 [Maths English Go]
1 2 [Science Music]
2 2 [Go Art]

week[i][j] is day i, period j. Each row is its own slice and grows on its own. Compare: an array grid [3][5]bool (episode 12) has the same number of columns in every row.

Mini project: Raju's chai order list

package main

import "fmt"

func main() {
    orders := []string{"masala chai", "samosa", "bun maska"}
    prices := []int{20, 15, 35}
    orders, prices = append(orders, "cold coffee"), append(prices, 60)
    total := 0
    var big []string
    for i, item := range orders {
        fmt.Printf("%d. %-12s Rs %d\n", i+1, item, prices[i])
        total += prices[i]
        if prices[i] >= 30 {
            big = append(big, item)
        }
    }
    fmt.Println("total:", total, "| Rs 30 and up:", big)
}
1. masala chai  Rs 20
2. samosa       Rs 15
3. bun maska    Rs 35
4. cold coffee  Rs 60
total: 130 | Rs 30 and up: [bun maska cold coffee]
  • orders, prices = append(...), append(...) is a multiple assignment (episode 3): both slices grow in one line, so they can't drift apart.
  • %-12s pads the text to 12 characters, left-aligned, so the prices line up.
  • Building a new slice from the elements that pass a test is called filtering: start with a nil slice and append the ones that pass.

Extension: also collect the items under Rs 30, and print the average price.

The next problem: the 999 that appeared in the wrong slice, and the tea that vanished inside a function, both come from the shared backing array. Episode 14 opens a slice up.

Common mistakes (and the real error messages)

You wrote Real error / what happens Fix
append(sales, 80) append(sales, 80) (value of type []int) is not used sales = append(sales, 80)
var s []int; s[0] = 5 panic: runtime error: index out of range [0] with length 0 s = append(s, 5)
make([]int, 3) then append no error: [0 0 0 120 95 140] make([]int, 0, 3)
sales[2:9] on 7 elements panic: runtime error: slice bounds out of range [:9] with capacity 7 keep high ≤ cap(s)
days := 30; var month [days]int invalid array length days use a slice: make([]int, days)
a == b with two slices invalid operation: a == b (slice can only be compared to nil) compare element by element (or slices.Equal, episode 14)
copy(none, sales) with a nil none no error: copies 0 make([]T, len(src)) first
changing v in for _, v := range s no error: the slice is unchanged s[i] = ...
append inside a function no error: the caller doesn't see it return the slice and assign it

Practice

  1. Append five numbers to a nil slice and print the largest.
  2. Remove the first person from a queue slice using slicing.
  3. Filter the even numbers of a slice into a new slice.
  4. Build a jagged [][]int triangle with rows of length 1 to 5.
Solutions

1.

package main

import "fmt"

func main() {
    var nums []int
    for _, n := range []int{12, 7, 31, 4, 19} {
        nums = append(nums, n)
    }
    max := nums[0]
    for _, n := range nums[1:] {
        if n > max {
            max = n
        }
    }
    fmt.Println(nums, "max:", max)
}
[12 7 31 4 19] max: 31
  1. queue[1:] starts at index 1. Notice the capacity is now 2: the slice starts one element later in the same backing array.
package main

import "fmt"

func main() {
    queue := []string{"Asha", "Ravi", "Meena"}
    queue = queue[1:]
    fmt.Println(queue, len(queue), cap(queue))
}
[Ravi Meena] 2 2

3.

package main

import "fmt"

func main() {
    nums := []int{3, 8, 5, 12, 7, 6}
    var even []int
    for _, n := range nums {
        if n%2 == 0 {
            even = append(even, n)
        }
    }
    fmt.Println(even)
}
[8 12 6]

4.

package main

import "fmt"

func main() {
    var tri [][]int
    for row := 1; row <= 5; row++ {
        var r []int
        for j := 1; j <= row; j++ {
            r = append(r, j)
        }
        tri = append(tri, r)
    }
    for _, r := range tri {
        fmt.Println(r)
    }
}
[1]
[1 2]
[1 2 3]
[1 2 3 4]
[1 2 3 4 5]

Quick quiz

What does this print?

func main() {
    s := make([]int, 2, 5)
    s = append(s, 7)
    fmt.Println(s, len(s), cap(s))
}
  • A. [7] 1 5
  • B. [0 0 7] 3 5
  • C. [0 0 7] 3 3
  • D. [7 0 0] 3 5
Answer

B. [0 0 7] 3 5. make([]int, 2, 5) already holds two zeros, with room for five. append adds 7 after them; there was room, so the capacity stays 5.

Interview questions

  • What is the difference between an array and a slice in Go?
  • Why must you write s = append(s, x)?
  • What is a nil slice? How is it different from an empty slice? Can you append to a nil slice?
  • What do len and cap return for a slice? What happens when len == cap and you append?
  • What does make([]int, 3, 10) create? What's the trap with make([]int, 3) followed by append?
  • What does s[2:5] return? Is it a copy?
  • How do you make an independent copy of a slice?
  • Why can a function change a slice's elements but not its length?
  • Can you compare two slices with ==?

Glossary

Term Meaning Example
Slice a list of values of one type whose length can change []int{120, 95}
Slice type []T: brackets with no length []string
Slice literal a slice written in code []int{1, 2, 3}
Element one value in the slice sales[2]
Index an element's position, from 0 sales[0]
append built-in: adds values at the end, returns the new slice s = append(s, 90)
Constant a value fixed when the code is written 7 in [7]int
nil Go's "no value": the zero value of a slice (and map, pointer) var s []int
nil slice a slice with no backing array yet; len 0, == nil var orders []int
Empty slice a non-nil slice with length 0 []int{}
Length (len) the number of elements in use len(s)
Capacity (cap) how many elements fit before a new backing array is needed cap(s)
Backing array the ordinary array where a slice's elements live hidden under every slice
make built-in that creates a slice with a length and capacity make([]int, 0, 30)
Preallocation reserving capacity in advance to avoid copies make([]T, 0, n)
Slicing expression cuts out part of a slice or array s[1:4]
Half-open range includes the start, excludes the end s[1:4] = indexes 1, 2, 3
Sharing two slices using the same backing array weekend := sales[5:7]
copy built-in: copies min(len(dst), len(src)) elements, returns the count copy(dst, src)
range walks a slice giving index and a copy of the value for i, v := range s
2D slice a slice whose elements are slices [][]string
Jagged rows of different lengths the timetable
Filtering building a new slice from elements that pass a test the big slice
%T Printf verb that prints a value's type []int
%-12s Printf: text padded to 12 characters, left-aligned samosa
Panic Go stopping the program on a run-time error index out of range [0] with length 0

Summary

  • A slice []T is a list that can grow. s = append(s, x): always assign the result.
  • The zero value is a nil slice: length 0, ready for append. Indexing only reaches existing elements.
  • len = elements in use, cap = room in the backing array; a full slice gets a bigger array on append.
  • make([]T, len, cap): use make([]T, 0, n) + append, or make([]T, n) + indexes.
  • s[low:high] is half-open and shares memory. copy(dst, src) makes a real copy.
  • range gives copies of values. Functions share a slice's elements but not its length: return the slice after appending.
  • [][]T makes rows of any length.

Next episode: slice internals and gotchas: the slice header, aliasing bugs, growth, s[low:high:max], and the slices package.