Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 147 ยท Collections

Slices

Learn Go slices - how they differ from arrays, literals, len and cap, append, slicing expressions, nil versus empty slices, make, copy, 2D slices, inserting and deleting items, clear, min and max.

A slice is Go's everyday sequence type. It holds an ordered list of values of one type, it can grow and shrink, and you can hand a piece of it to a function without copying anything. Almost every Go program you read uses slices for lists of users, lines of text, bytes read from a file and results from a database.

Where an array has a fixed length that is part of its type, a slice's type is just []T. Under the hood a slice is a small window onto an array that the runtime manages for you. This lesson covers the everyday operations: creating slices, len and cap, append, slicing, copy, nil versus empty, two-dimensional slices, and the idioms for inserting and deleting. The next lesson opens the hood and explains why slices sometimes behave in surprising ways.

Creating slices

The quickest way is a slice literal. It looks like an array literal without a length:

Go Slice literals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

[]int and [5]int are different types. The compiler reads []int{...} as "create an array big enough for these values and give me a slice that covers all of it".

When you know the length but not the values, use the built-in make. It takes the type, a length and an optional capacity, and fills the new slice with zero values:

Go make with length and capacity

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

len(s) is the number of elements you can see. cap(s) is how many elements the slice can hold before append has to allocate a bigger array. You can only index up to len(s) - 1, even if the capacity is larger.

Indexing and ranging

Indexes start at 0 and are bounds-checked at run time. Reading or writing outside 0 <= i < len(s) panics. You loop with a for loop or range:

Go Indexing and range (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go has no negative indexes: langs[-1] with a constant index is a compile error, and a negative variable panics. The last element is langs[len(langs)-1].

The panic message is panic: runtime error: index out of range [5] with length 3, followed by a goroutine trace. Panics are covered in panic and recover.

Growing a slice with append

append adds elements to the end and returns the resulting slice. You must use the return value, normally by assigning it back to the same variable:

Go append

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The ... after more unpacks the slice into separate arguments, exactly as with variadic functions. A common special case: append([]byte("hello "), "world"...) appends a string's bytes to a byte slice.

Why must you assign the result? If the underlying array is full, append allocates a bigger one, copies the old elements across and returns a slice that points at the new array. Your old variable still points at the old one. How exactly that growth works is the topic of How Slices Work.

Slicing expressions

s[low:high] creates a new slice that covers elements low up to, but not including, high. Either bound can be omitted: s[:3] starts at 0, s[2:] runs to the end, and s[:] is everything.

Go Slicing expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

A sub-slice does not copy the data. part and s share the same elements, so writing through one is visible through the other. That is fast and often what you want, but it is also the most common source of slice bugs. Use copy (below) when you need independence.

The upper bound can go beyond len as long as it stays within cap, which lets you re-extend a slice. Anything beyond cap panics.

nil slices versus empty slices

A slice that was never assigned is nil. It has length 0 and capacity 0, and it behaves almost exactly like an empty slice:

Go nil versus empty

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The %#v verb shows the difference: []int(nil) versus []int{}. In practice, treat len(s) == 0 as the check for "no elements" and don't care whether the slice is nil. The one place it matters is encoding: encoding/json writes a nil slice as null and an empty one as [] (see JSON).

Prefer var items []Item when you plan to fill a slice with append. It is the idiomatic zero value, it allocates nothing and it is ready to use.

Slices cannot be compared

You can't use == on two slices. The only comparison the language allows is with nil. Trying anything else is a compile error:

Go Comparing slices (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler reports invalid operation: a == b (slice can only be compared to nil). The slices.Equal function from the slices package compares element by element. For this reason a slice also can't be a map key.

Copying with copy

copy(dst, src) copies elements and returns how many it copied: the smaller of len(dst) and len(src). The two slices end up independent.

Go copy and independent slices

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

A shorter way to clone a slice is slices.Clone(src), or append([]int(nil), src...) in older code.

Two-dimensional slices

Go has no built-in matrix type. You build one as a slice of slices, and each row is allocated separately, so rows can have different lengths:

Go Slices of slices

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Note that make([][]int, rows) creates rows nil slices; you must allocate each row. If you need one contiguous block for speed, allocate a single []int of length rows*cols and compute data[r*cols+c] yourself.

Inserting and deleting

Go has no insert or remove built-in. You compose them from append and slicing. These patterns are worth knowing:

Go Insert and delete idioms

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The in-place append(s[:i], s[i+1:]...) delete shifts the tail left but leaves a stale copy of the last element in the backing array. With pointers or large values that can keep memory alive. slices.Delete clears the vacated slots for you (since Go 1.22), which is one more reason to prefer it. How Slices Work explains the leak in detail.

clear, min and max

Go 1.21 added three small built-ins that work well with collections. clear(s) sets every element of a slice to its zero value (it does not change the length), and the same built-in empties a map. min and max take two or more ordered values; they do not take a slice (use slices.Min and slices.Max for that):

Go clear, min and max

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Slices and functions

A slice passed to a function is a small descriptor (pointer, length, capacity) copied by value. The function can change the elements the caller sees, but not the caller's length:

Go Passing slices to functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

That is why functions that may grow a slice return it, just like append itself. See pointers and functions for the full picture of pass-by-value.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of the expression []int{1, 2, 3}?

    A literal without a length creates a slice of type []int. [3]int would be an array.
  2. 2. After s := make([]int, 2, 5), what are len(s) and cap(s)?

    make takes the length first and the capacity second. The slice has two visible zero elements and room for five.
  3. 3. Given s := []int{1, 2, 3, 4} and t := s[1:3], what does t contain?

    The low bound is included and the high bound is excluded, so t holds s[1] and s[2].
  4. 4. Which line does NOT compile?

    Slices can only be compared to nil with ==. Use slices.Equal to compare contents.
  5. 5. What does copy(dst, src) return when dst has length 3 and src has length 5?

    copy copies min(len(dst), len(src)) elements and returns that count.

Summary

  • A slice ([]T) is a flexible view onto an array. Its length is not part of its type.
  • Create slices with literals, make([]T, len, cap) or by slicing an existing array or slice.
  • len is the number of elements; cap is how many fit before append must reallocate.
  • Always keep the result of append: s = append(s, x). Use append(a, b...) to join slices.
  • s[low:high] includes low and excludes high, and shares memory with s.
  • A nil slice behaves like an empty one for len, range and append. Slices can only be compared to nil.
  • copy makes independent copies; slices.Insert, slices.Delete and slices.Clone cover most editing.
  • clear, min and max are built in since Go 1.21.

Next: How Slices Work: Length, Capacity and Aliasing looks inside the slice header and explains growth and shared memory.