Introduction
Slices are one of the most important data types in Go, providing a more powerful and flexible interface to sequences than arrays. Unlike arrays, slices are dynamically-sized and are the standard way to work with collections in Go.
The Code
// _Slices_ are an important data type in Go, giving
// a more powerful interface to sequences than arrays.
package main
import (
"fmt"
"slices"
)
func main() {
// Unlike arrays, slices are typed only by the
// elements they contain (not the number of elements).
// An uninitialized slice equals to nil and has
// length 0.
var s []string
fmt.Println("uninit:", s, s == nil, len(s) == 0)
// To create a slice with non-zero length, use
// the builtin `make`. Here we make a slice of
// `string`s of length `3` (initially zero-valued).
// By default a new slice's capacity is equal to its
// length; if we know the slice is going to grow ahead
// of time, it's possible to pass a capacity explicitly
// as an additional parameter to `make`.
s = make([]string, 3)
fmt.Println("emp:", s, "len:", len(s), "cap:", cap(s))
// We can set and get just like with arrays.
s[0] = "a"
s[1] = "b"
s[2] = "c"
fmt.Println("set:", s)
fmt.Println("get:", s[2])
// `len` returns the length of the slice as expected.
fmt.Println("len:", len(s))
// In addition to these basic operations, slices
// support several more that make them richer than
// arrays. One is the builtin `append`, which
// returns a slice containing one or more new values.
// Note that we need to accept a return value from
// `append` as we may get a new slice value.
s = append(s, "d")
s = append(s, "e", "f")
fmt.Println("apd:", s)
// Slices can also be `copy`'d. Here we create an
// empty slice `c` of the same length as `s` and copy
// into `c` from `s`.
c := make([]string, len(s))
copy(c, s)
fmt.Println("cpy:", c)
// Slices support a "slice" operator with the syntax
// `slice[low:high]`. For example, this gets a slice
// of the elements `s[2]`, `s[3]`, and `s[4]`.
l := s[2:5]
fmt.Println("sl1:", l)
// This slices up to (but excluding) `s[5]`.
l = s[:5]
fmt.Println("sl2:", l)
// And this slices up from (and including) `s[2]`.
l = s[2:]
fmt.Println("sl3:", l)
// We can declare and initialize a variable for slice
// in a single line as well.
t := []string{"g", "h", "i"}
fmt.Println("dcl:", t)
// The `slices` package contains a number of useful
// utility functions for slices.
t2 := []string{"g", "h", "i"}
if slices.Equal(t, t2) {
fmt.Println("t == t2")
}
// Slices can be composed into multi-dimensional data
// structures. The length of the inner slices can
// vary, unlike with multi-dimensional arrays.
twoD := make([][]int, 3)
for i := range 3 {
innerLen := i + 1
twoD[i] = make([]int, innerLen)
for j := range innerLen {
twoD[i][j] = i + j
}
}
fmt.Println("2d: ", twoD)
}
Slice Fundamentals
Slice Declaration
var s []string
fmt.Println("uninit:", s, s == nil, len(s) == 0)
// uninit: [] true true
An uninitialized slice is nil and has length 0. Unlike arrays, the slice type doesn’t include the length - []string can be any length.
A nil slice has length 0, but a slice with length 0 isn’t necessarily nil. Both are valid and work the same way in most operations.
Creating Slices with make
s = make([]string, 3)
fmt.Println("emp:", s, "len:", len(s), "cap:", cap(s))
// emp: [ ] len: 3 cap: 3
Use make to create a slice with a specific length. Elements are zero-valued initially. You can also specify capacity:
s = make([]string, 3, 5) // length 3, capacity 5
Pre-allocating capacity with make([]T, 0, cap) can improve performance when you know the slice will grow to a certain size.
Length vs Capacity
- Length (
len): Number of elements in the slice
- Capacity (
cap): Number of elements in the underlying array
Slice Operations
Setting and Getting Values
s[0] = "a"
s[1] = "b"
s[2] = "c"
fmt.Println("get:", s[2]) // get: c
Access elements just like arrays using zero-based indexing.
Appending Elements
s = append(s, "d")
s = append(s, "e", "f")
fmt.Println("apd:", s) // apd: [a b c d e f]
append adds elements to a slice. Always assign the result back to the slice variable, as append may allocate a new underlying array.
Critical: Always use the result of append: s = append(s, value). The underlying array may change if capacity is exceeded.
Copying Slices
c := make([]string, len(s))
copy(c, s)
The copy function copies elements from source to destination. It copies min(len(src), len(dst)) elements.
Slice Operators
Slicing Syntax: [low:high]
l := s[2:5] // Elements at index 2, 3, 4
l = s[:5] // From start to index 4
l = s[2:] // From index 2 to end
The slice operator creates a new slice viewing a portion of the original:
[low:high]: from low (inclusive) to high (exclusive)
[:high]: from start to high (exclusive)
[low:]: from low (inclusive) to end
Slicing doesn’t copy data - it creates a new slice header pointing to the same underlying array. Changes to one affect the other.
Slice Initialization
t := []string{"g", "h", "i"}
Declare and initialize a slice literal in one line. The compiler automatically determines the length.
The Slices Package
import "slices"
t2 := []string{"g", "h", "i"}
if slices.Equal(t, t2) {
fmt.Println("t == t2")
}
The slices package (Go 1.21+) provides useful utilities:
slices.Equal(): Compare slices
slices.Sort(): Sort slices
slices.Contains(): Check if slice contains a value
- And many more…
Multi-Dimensional Slices
twoD := make([][]int, 3)
for i := range 3 {
innerLen := i + 1
twoD[i] = make([]int, innerLen)
for j := range innerLen {
twoD[i][j] = i + j
}
}
// Result: [[0] [1 2] [2 3 4]]
Unlike arrays, inner slices can have different lengths, making them more flexible for jagged/irregular data structures.
Slices Under the Hood
A slice is a descriptor containing:
- Pointer to an element in an underlying array
- Length of the slice
- Capacity of the underlying array
slice := []int{1, 2, 3, 4, 5}
┌───┬───┬───┬───┬───┐
│ 1 │ 2 │ 3 │ 4 │ 5 │ ← underlying array
└───┴───┴───┴───┴───┘
↑
ptr──┘ len: 5, cap: 5
Common Patterns
Filtering
var filtered []int
for _, v := range original {
if v > 10 {
filtered = append(filtered, v)
}
}
Pre-allocating
result := make([]int, 0, expectedSize)
for ... {
result = append(result, value)
}
Removing an element
// Remove element at index i
s = append(s[:i], s[i+1:]...)
Key Takeaways
- Slices are dynamically-sized, flexible views into arrays
- Type
[]T doesn’t include length (unlike arrays [n]T)
- Use
make([]T, length, capacity) to create slices
- Always assign the result of
append back to the slice
- Slicing operations
[low:high] create new views, not copies
len() returns length, cap() returns capacity
- The
slices package provides helpful utility functions
- Slices are passed by reference - changes affect the original
- Inner slices in multi-dimensional slices can have varying lengths